In this chapter we will learn about
- C language and its features
- Data type, Keywords, operators and control structure use in C language
Modular programming is a technique of dividing program into small manageable parts or small manageable modules.
Advantage of modular programming
- program will be small
- program will be easy to read or understand
- easy to debug
- reuse the module
Software is set of program. Program is set instruction.
Structured programming is a technique of organizing and coding computer program in hierarchy of module. Structure programming follows top down approach in which developer separates the overall program structure into different subsection . Modular programming is an example of structure programming.
Benefits of structured programming language include ease of maintenance and ease of readability by other programmers.
What is C ?
C is very popular structured programming language developed by Dennis Ritche at Bet Lab in 1972/73 AD. In C language also program are divided into small logical functional modules or structures. It was named C because it was derived from earlier language called B.
C is general purpose high level language. As it is very much close to Assembly level language it is also known as middle level computer language.
Advantage of C Language
- C program is simple and easy to use and understand
- program can be divided into simple and manageable modules
- More one programmer or developer can work at the same time
- test ad debugging is easy and fast
- Program can be easily modified
Characteristics / Feature of C language
- its is structure programming language
- it is a powerful and flexible language
- It is very very fast
- It had very keyword(32 key word) and thus it is easy to learn
Differentiate between QBasic and C Language
Qbasic
|
C
Language
|
It
supports both function and sub procedure
|
It
supports only function procedure
|
Developed by John G. Kemeny and Thomas E. Kurtz on microsoft on 1985-1991 AD
|
It was developed by Dannis Ritche at Bell lab of USA around 1972-1973
AD
|
It
is high level Language
|
It
is middle level language
|
It has around 159 Key words
|
It was around 32 Keywords
|
It’s
mainly used for designing application software
|
It
is mainly used for designing system software
|
Basic Data types used in C language
C language has 2 types of data
- Basic Data types
- Derived data types
Basic
data types
|
Derived
data types
|
Int
(Integer)
|
Arrays
|
Char (Character)
|
Pointers
|
Float
|
Structure
|
Double
|
Unions
|
Void
|
Enums(Enumerations)
|
The data type in a programming language is a set of data with values having predefined characteristics. It is system for declaring variables of different types. The language usually specifies the range of values for the given data type, how the value are processed by the computer and how they are stored. C language supports 4 basic data types. They are char, int, float and double.
Data
Type
|
Description
|
Byte
|
Range
|
Char
|
Character
|
1
|
0
to 255
|
int
|
Integer
|
2
|
-32768 to 32767
|
float
|
Single
precision (decimal number)
|
4
|
6-digit
precision
|
double
|
Double precision
|
8
|
12-digit of precision
|
void
void means nothing or null value. We cannot create any variable of void type
For example,
void hello(void)
{
}
The above function "hello" does not require any parameter and also does not return any value.
C Token
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program. Each and every smallest individual unit in a C program are known
as C tokens.
C tokens are of six types. They are:
a) Keywords (eg: int, while),
b) Identifiers (eg: main, total),
c) Constants (eg: 10, 20),
d) Strings (eg: “total”, “hello”),
e) Special symbols (eg: (), {}),
f) Operators (eg: +, /,-,*)
C Keywords
Every C word is special words which are already define for some task. It is like statement in Qbasic. C has set of 32 keywords, which have their predefine meaning and cannot be used as a variable name.. These words are known as reversed words
C Character set
C character set is a group of valid character and symbol supported by a programming language. A character denotes any alphabet, digit or special symbol used to represent information.
The below table shows the valid alphabets, numbers and special symbols supported
by C language.
Identifiers
Identifiers are the name given to the entities such as variable, function, arrays structures and unios
for example,
int price;
float total
Here price and total are called identifiers.
Rules for naming Identifiers:
i) The Identifier must start with an alphabet or an under score (_).
ii) Identifier can be made from the combination of alphabets, digits and under score.
iii) No any C keyword can be used as an Identifier.
iv) Identifier must be unique and can be used for a single purpose only.
Format Specifier
The format specifier is used during input and output operation. It tells the compiler what type of data is stored in a variable during the input and output operation such as taking
data from keyboard and display data on the screen. Some examples are %c, %d, %f, etc.
Data
Type
|
Format
Specifier
|
Int
|
%d
|
Long int
|
%ld
|
Char
|
%c
|
float
|
%f
|
Double
|
%lf
|
Variable in C
Variable value changes during the program execution. Variable is used to hold data within your program. A variable represents a location in
your computer's memory. Every variable has two parts, a name and a data type.
Variable declaration
A variable declaration states the types of the variable, variable name and if necessary
initializes the variable to a given value.
For e.g.
int count;int number_of_students = 30;
Now, let’s look a whole program in C:
C program
There are four steps of writing program in C. Each step has its own importance and
must be completed stepwise.
Step 1:
At first, the program is written in C Compiler editor. It is called source code. This source
code can be saved as a program file and its extension is .C. This source code can be
edited at any time.
Step 2:
The second step is to compile the source code. During compilation, syntax error is
checked and removed from the source code. After compiling, the source code is changed
into binary format and creates a new file with the extension .obj. It is called object
program which cannot be edited.
Step 3:
The third step is called linking process. In this process, the required libraries are linked
to the program. Libraries prepare an appropriate environment to execute the C program.
Step 4:
After the linking process, an executable file is created with the extension .exe. This
executable file can be run in any other computer without compiler.
Structure of C Program
Example of C program
Parts of a C Program
i) Pre-processor directives
As part of compilation, the C compiler runs a program called the C pre-processor. The
preprocessor is able to add and remove code from your source file. One of the major
functions of C preprocessor is Tokenizing. The final step of the preprocessor is to link
the resulting program with necessary programs and library.
While writing program in C, we need to include different header files in the beginning.
In the above program, printf ( ) and scanf ( ) functions are used for output and input
operation. These functions are defined in the header file . So, this header file
is included at the beginning of program which contains the code of printf() and scanf()
functions. All the code of header files will be added to the program during compilation.
C Header Files
Different library functions are used to do different tasks in C language. For example,
we use scanf() function to ask data from keyboard. Each function is defined in a special
type of file. These files are called Header File and have extension .h. These header files
must be included using #include directive otherwise the compiler doesn’t understand the
library function we use and gives an error message. Here is the list of some commonly
used Header file and their purposes:
ii) Global Directives
In this section of C program, Global variables and User-defined function are declared.
iii) main () function
C program must start with main() function. This is the entry point of the program.
iv) { } Parenthesis
In C language, each function is defined inside parenthesis ({ })
v) User-defined function
As in QBASIC, we can create different user-defined function as per our requirements.
Output Function in C
Output function is used to show the calculated result or output on the screen. In C
language, printf() is one of the output function defined in header file.
printf() function
In C Language, printf() function is used to print the valued on the screen. It is defined in
header file. So, the header file must be added to use this function.
Syntax:
printf(“format string”,argument list);
format string is the combination of format identifier, escape sequence or string constant.
Escape Sequence
Escape Sequence is a pair of character that is used with printf() function to display
non-printing character or a special character on the screen.
Some Examples of Escape Sequence:
\n - new line
\t - tab
\b - backspace
\o - null character
\? - question mark
\\ - slash
\' - single quote
\” - double quote
Format Identifier
We need to include format identifier to tell the data type in the area of format string of
printf() function. For example,
Variable
type
|
Format
Specifier
|
Int
|
%d
|
Long int
|
%ld
|
Char
|
%c
|
float
|
%f
|
Double
|
%lf
|
String Constant
String constant is a message to be displayed along with the other values stored in
variables. It is enclosed within double quotation (" ").
Argument List
It is a list of variables to be used in printf ( ) function.
For example,
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=10;
clrscr();
printf("\n Value of a and b are %d and %d ",a,b);
getch();
}
In the above program,
\n prints from a new line
"Value of a and b are" → String Constant
%d → Format Identifier of int data type
a,b → Arugement List (Variables)
The output of the above program:
Note: Each C statement must be terminated by a semicolon(;)
Input Function
in C
Input function is used to ask data for processing. In C language, scanf() is one of the
input function defined in header file.
scanf() function
scanf() is one of the most important functions of C Program. This function is also defined
in the header file and used to ask value from keyboard.
Syntax:
scanf("format string", argument list);
format string is the combination of format identifier, escape sequence or string constant.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf ("Type an integer ");
scanf ("%d",&a);
printf ("\n The value of a is %d.",a);
getch();
}
In the above program,
scanf ("%d",&a);
%d → Format Identifier of int data type
&a → & – address operator,
a – variable
This function in the above program asks an integer form keyboard and stores in the
variable ‘a’.
getch() function
getch() function is another input function of C language. This function is define in the header file <conio.h>.This function is used to ask any one character from keyboard.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
ch=getch();
printf("The typed character is %c.",ch);
getch();
}
Note: You can see the use of getch() function in every example of C program. The purpose of using this function in the sample program is to let the user to
read output on the screen. If such type of function is not used, the output screen will be
closed immediately after showing the output and returns to the coding window. In the
above program, after showing the output by printf() function, getch() asks a character
and get chance to see the output until the character is not typed.
Arithmetic Calculations in C Program
There are basically four types of arithmetic operations:
i) Addition
ii) Subtraction
iii) Multiply
iv) Division
To perform the above arithmetic operations, C language supports the below arithmetic
operators:
List of Arithmetic Operators in C
If A=10 and B=20,
C Expression
An expression consists of at least one operand with one or more operators. It is a legal
combination of symbols that represents a value.
For example,
C=A+B
Example of Arithmetic Calculation #1
// Calculate area and volume of a room
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int l,b,h,a,v;
printf ("Type length, breadth and
height ");
scanf ("%d%d%d",&l,&b,&h);
a=l*b;
v=l*b*h;
printf("\nArea=%d",a);
printf ("\nVolume=%d",v);
getch();
}
Example of Arithmetic Calculation #2
/* Calculate total marks
and percentage */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int e,m,c,t;
float p;
printf("Marks in English, Math &
Computer ");
scanf("%d%d%d",&e,&m,&c);
t=e+m+c;
p=t/3;
//Full mark for all subject is
100
printf("\nTotal Marks = %d ",t);
printf("\nPercentage = %f ",p);
getch();
}
Logical Calculation in C
The calculation that is done based on one or more conditions is called logical calculations.
Several relational or comparison operators are used to check the condition which gives
True or False as a calculated result.
Relational Operators in C
Relational Operator checks the relationship between two operands and returns either 1
(True) or 0 (False). In C programming, relational operators can be used to take decisions
and provide condition in looping statements.
List of Relational Operators in C
If A=5 and B=10,
Control structures in C
C is a structured programming language. Control structures form the basic entities of a
“structured programming language“. C supports three types of basic control structures,
which are used to alter the flow of execution of the program.
a) Sequence structure (straight line paths)
b) Selection structure (one or many branches)
c) Loop structure (repetition of a set of activities)
a) Sequential structure
In sequential structure, the statements are executed
one after another sequentially from top to bottom
without changing the flow of program.
b) Selection Structure
It is also called branching structure. In this structure, the control of the program is
transferred from one part of the program to another on the basis of specified condition
or without condition.
c) Looping Structure
Looping is the process of repeating the execution of a statement or a block of statements
guided by a condition. A loop is terminated when the given condition is satisfied.
if statement
if statement is used to test one or more condition and execute statement(s) if the given
condition is True.
Syntax:
if (condition)
{
statements
…………………
}
If the condition mentioned in the syntax is True, then the statements written inside the
parenthesis { } will be executed.
example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf ("Type your marks ");
scanf ("%d",&a);
if(a>=40)
{
printf ("You are Pass");
printf ("\nCongratulations!!!");
}
getch();
}
if … else statement
The previous if statement executes the statement only if the given condition is True.
This statement is used to check one or more condition and execute the condition either
the condition is True or False.
Syntax :
if (condition)
{
statements
…………..
}
else
{
statements
…………..
}
example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf ("Type your marks ");
scanf ("%d",&a);
if(a>=40)
{
printf ("You are Pass");
}
else
{
printf ("You are Fail");
}
getch();
}
In the above program, if the value of a is greater than or equal to 40 then the message
“You are Pass” will be printed, otherwise, the program shows “You are Fail”.
Example of Logical Calculation #1
//Check ODD or EVEN
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n;
printf("Type any number ");
scanf("%d",&n);
if (n%2==0)
{
printf ("\nIt is even.");
}
else
{
printf ("\nIt is odd.");
}
getch();
}
Example of Logical Calculation #2
/* Find the GREATER number */
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a,b;
printf("Type first number ");
scanf("%d",&a);
printf("Type second number
");
scanf("%d",&b);
if(a>b)
{
printf("Greater number
is %d ",a);
}
else
{
printf("Greater number
is %d ",b);
}
getch();
return 0;
}
Looping in C
The looping statement allows a set of instructions to be performed repeatedly until a
certain condition is fulfilled. The looping statements are also called iteration statements.
Looping statements in C
C provides three kinds of loops:
i) while loop
ii) do loop
iii) for loop
i) while loop
The while loop continues executing a block of code till the given condition is t rue. The
loop will be terminated when the condition becomes false.
Syntax:
initial variable declaration
while (condition)
{
statements
………………
// increment of counter
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1;
clrscr();
while (num<=10)
{
printf ("%d ",num);
num++;
}
getch();
}
output:
1 2 3 4 5 6 7 8 9 10 _
In the above program, the value of variable (counter) num is initialized as 1. The loop
continues till the values of num is less than or equal to 10. In each iteration (loop), the
current value of num is printed and the value of num is increased by 1. When the value
of num becomes 11, the condition becomes false and the loop will be terminated.
ii) do loop
The do loop also executes a block of code as long as a condition is satisfied. The
difference between a "do" loop and a "while" loop is that the while loop tests its condition
before the execution of loop; the "do" loop tests its condition after the execution of loop.
Syntax:
initial value declaration
do
{
statement
………………
// increment of counter
}
while (condition);
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1;
clrscr();
do
{
printf ("%d ",num);
num++;
}
while (num<=10);
getch();
}
output:
1 2 3 4 5 6 7 8 9 10 _
Difference between while/do loop
iii) for loop
The for loop can execute a block of code for a fixed number of repetitions. It is easy to
use and defined in a single statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int c;
for (c=1;c<=10;c++)
{
printf ("%d ",c);
}
getch();
}
output:
1 2 3 4 5 6 7 8 9 10 _
Syntax:
for (intialization, condition, increment/decrement )
{
statement
……………….
}
Example:
Use of Loop – Example #1
//Fibonocci series 1 2 3 5 8 13 ...
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=1,b=2,c,n=1;
do
{
printf ("%d ",a);
c=a+b;
a=b;
b=c;
n++;
}
while (n<=10);
getch();
}
output
1 2 3 5 8 13 21 34 55 89
Use of Loop – Example #2
//Series 1 2 4 8 ... upto 10th terms
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n=1,c;
for (c=1;c<=10;c++)
{
printf ("%d ",n);
n=n*2;
}
getch();
}
output
1 2 4 8 16 32 64 128 256 512
Use of Loop – Example #3
//Check PRIME or COMPOSITE
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,i,c=0;
printf ("Type any number ");
scanf ("%d",&n);
for (i=2;i<=n-1;i++)
{
if(n%i==0)
{
c++;
}
}
if (c==0)
{
printf("The number is
prime. ");
}
else
{
printf("The number is
composite. ");
}
getch();
}
Use of Loop – Example #4
//Sum of individual digits
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0;
clrscr();
printf("Type any one integer ");
scanf("%d",&n);
while (n!=0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf("Sum of individual digits
= %d",s);
getch();
}
Thank you for your Visit
Comments
Post a Comment