Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
66 views

C Programming

This document outlines the contents of a C programming course divided into 5 units. Unit I covers basic concepts like variables, data types, and input/output. Unit II covers operators, expressions, and conditional statements. Unit III discusses decision making using if/else statements and switches. Unit IV introduces arrays. Unit V covers functions, structures, and unions. The document also provides definitions and examples of common C programming concepts like variables, data types, operators, and the overall structure of a C program.

Uploaded by

Rajamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

C Programming

This document outlines the contents of a C programming course divided into 5 units. Unit I covers basic concepts like variables, data types, and input/output. Unit II covers operators, expressions, and conditional statements. Unit III discusses decision making using if/else statements and switches. Unit IV introduces arrays. Unit V covers functions, structures, and unions. The document also provides definitions and examples of common C programming concepts like variables, data types, operators, and the overall structure of a C program.

Uploaded by

Rajamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT-I C Constants, variables, Data-type, Declaration of variables, assigning values to

variables.

UNIT-II: Operators Arithmetic, Relational, Logical, Assignment, Increment and decrement,


Conditional, Arithmetic Expressions, Evaluation of Expressions, Precedence of Arithmetic
operators, Formatted input and output.

UNIT-III: Operators Decision making and branching If, simple if, If else, Nesting of if - else,
Else - If ladder, Switch statement, the?: operator, Go to statement. Decision making with
looping: While, Do, for statement, Jumps in loops.

UNIT-IV: Arrays One - dimensional array, two - dimensional array, Initializing arrays, Multi -
dimensional arrays.

UNIT-V: User-Defined Function Need for User-defined function, Multi-function program, the
form of C-Function, Return Value and their types. Structures and Unions: Structure definition,
Structure initialization, Comparison of structure variables, union.
Constants

Constant is a quantity that does not change throughout the execution of a program.

There are 4 types of constants in C.

o Integer constants
o Character constants
o Real/Floating point constants
o String constants

Integer Constants

An integer constant is an integer quantity which contains a sequence of digits. It should not
have a decimal point. Blanks and commas are not allowed within an integer constant .An integer
constant can be either +ve or -ve. The constant must lie within the range of the declared data type
(including qualifiers long, short etc.).

Example of valid integer constants:- 976 8987 5 -25 etc.

Example of invalid integer constants:- 78.43 7-8 89,76 etc.

Floating Point Constants

They are also known as real constants. A real constant contains a decimal point or an
exponent. It can be either +ve or -ve. Commas and blank space are not allowed within a real
constant.

Examples:– 254.175, -16.47 -0.5e-7 +4.1e8


Character Constant

A character constant is a character which is enclosed in single quotes. A character constant is of


size 1byte and can contain only 1 character. A character can be an alphabet like a,b,A,C etc or a
special character like &,^, $, #,@ etc or a single digit from 0 through 9. It can also be an escape
sequence character like space ‘ ‘ or a null character ‘\o’ or a new line ‘\n’ etc.

Example: ‘A’ ‘a’ ‘ b’ ‘8’ ‘#’ etc.

String Constants

 A string constant is a collection of characters enclosed in double quotations “”


 It may contain alphabets, digits, special characters and blank space.

Example: “Circuits Today123”

Data types in C Language


Data types specify how we enter data into our programs and what type of data we enter. C
language has some predefined set of data types to handle various kinds of data that we can use in
our program. These data types have different storage capacities.
C language supports 2 different type of data types :

1. Primary data types:

These are fundamental data types in C namely integer(int), floating point(float),


character(char) and void.

2. Derived data types:

Derived data types are nothing but primary data types but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be
declared as what data-type it is.
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255

long int or signed long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Floating point type


Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.
Variable
Variables are changeable, we can change value of a variable during execution of a program. A
programmer can choose a meaningful variable name. Example : average, height, age, total etc.
A variable in C language must be given a type, which defines what type of data the variable will
hold.
It can be:

 char: Can hold/store a character in it.


 int: Used to hold an integer.
 float: Used to hold a float value.
 double: Used to hold a double value.
 void

Rules to name a Variable

1. Variable name must not start with a digit.


2. Variable name can consist of alphabets, digits and special symbols like underscore _.
3. Blank or spaces are not allowed in variable name.

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

4. Keywords are not allowed as variable name.


5. Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested
to keep the variable names in lower case.
Declaring, Defining and Initializing a variable
Declaration of variables must be done before they are used in the program. Declaration does the
following things.

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about allocating memory
space to the variable.
4. Declaration is more like informing the compiler that there exist a variable with following
data type which is used in the program.
5. A variable is declared using the extern keyword, outside the main() function.

extern int a;
extern float b;
extern double c, d;
Defining a variable means the compiler has to now assign a storage to the variable because it
will be used in the program. It is not necessary to declare a variable using extern keyword, if you
want to use it in your program. You can directly define a variable inside the main() function and
use it.
To define a function we must provide the data type and the variable name. We can even define
multiple variables of same data type in a single line by using comma to separate them.
int a;
float b, c;
Initializing a variable means to provide it with a value. A variable can be initialized and defined
in a single statement, like:
int a = 10;
A program in which we will use some variables.
#include <stdio.h>

// Variable declaration(optional)
extern int a, b;
extern int c;

int main () {

/* variable definition: */
int a, b;
/* actual initialization */
a = 7;
b = 14;
/* using addition operator */
c = a + b;
/* display the result */
printf("Sum is : %d \n", c);

return 0;
}

Sum is : 21
You must be thinking how does this printf() works, right? Do not worry, we will learn about it
along with other ways to input and output data in C language in the next tutorial.

Structure of c program

 Documentation section : The documentation section consists of a set of comment


lines giving the name of the program, the author and other details, which the
programmer would like to use later.

 Link section : The link section provides instructions to the compiler to link
functions from the system library.

Definition section : The definition section defines all symbolic constants.


 Global declaration section : There are some variables that are used in more
than one function. Such variables are called global variables and are declared in the
global declaration section that is outside of all the functions. This section also declares
all the user-defined functions.

Operator
Operator Description
Description Example
Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

 Main () function section : Every C program must have one main function section.
This section contains two parts; declaration part and executable part

 Declaration part : The declaration part declares all the variables used in the
executable part.

 Executable part : There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.

 Subprogram section : The subprogram section contains all the user-defined functions
that are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.
Note:All section, except the main () function section may be absent when they are not
required

Unit II

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
&& Called Logical AND operator. If both the operands are non-zero, (A &&
then the condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non- (A || B)


zero, then the condition becomes true. is true.

! Called Logical NOT Operator. It is used to reverse the logical state !(A &&
of its operand. If a condition is true, then Logical NOT operator B) is
will make it false. true.

 Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic. Assume variable A holds 10 and variable B holds
20 then

Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the (A == B) is
condition becomes true. not true.

!= Checks if the values of two operands are equal or not. If the values are (A != B) is
not equal, then the condition becomes true. true.

> Checks if the value of left operand is greater than the value of right (A > B) is not
operand. If yes, then the condition becomes true. true.

< Checks if the value of left operand is less than the value of right operand. (A < B) is
If yes, then the condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is
right operand. If yes, then the condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand. If yes, then the condition becomes true. true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −

The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −

Assignment Operators
The following table lists the assignment operators supported by the C language −

Show Examples

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to left side C = A + B will
operand assign the value
of A + B to C

+= Add AND assignment operator. It adds the right operand to the left operand and C += A is
assign the result to the left operand. equivalent to C
=C+A

-= Subtract AND assignment operator. It subtracts the right operand from the left C -= A is
operand and assigns the result to the left operand. equivalent to C
=C-A

*= Multiply AND assignment operator. It multiplies the right operand with the left C *= A is
operand and assigns the result to the left operand. equivalent to C
=C*A

/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent to C
=C/A

%= Modulus AND assignment operator. It takes modulus using two operands and C %= A is
assigns the result to the left operand. equivalent to C
=C%A
Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.

// C Program to demonstrate the working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

return 0;
}

Output

++a = 11

--b = 99

++c = 11.500000

++d = 99.500000
C Ternary Operator (?:)

Ternary operator is a conditional operator that works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

 The first expression conditional expression is evaluated first. This expression evaluates to
1 if it's true and evaluates to 0 if it's false.
 If conditional Expression is true, expression1 is evaluated.
 If conditional Expression is false, expression2 is evaluated.

Example 7: C conditional Operator


#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);

// If test condition (February == 'l') is true, days equal to 29.


// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;

printf("Number of days in February = %d",days);


return 0;
}

Output

If this year is leap year, enter 1. If not enter any integer: 1

Number of days in February = 29

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left


Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Arithmetic Expressions

C has a wide range of operators. An arithmetic expression is composed of operators and


operands. Operators act on operands to yield a result. Commonly used arithmetic operators are +,
-, *, / and %.

The plus sign (+) is used to add two values, the minus sign (-) to subtract one value from another,
the asterisk(*) to multiply two values, the division (/) to divide a value and the modulus (%) to
obtain the reminder of integer division. These are known as binary operators since they operate
on two values or variables.

Following are examples of arithmetic expressions :

result= x - y;
total = principle + interest;
numsquare = x * x;
celcius = (fahrenheit - 32) / 1.8

Notice the equal sign (=) in the above expressions, it is known as the assignment operator. It
assigns the value on the right hand side of the equal sign to the variable on the left hand side.

In the last expression, parentheses are used to perform a certain operation first. This is because in
C, operators follow a precedence rule. *, / and % have a higher precedence over + and -. Hence
to override the precedence, parentheses should be used. Expressions having operators of the
same precedence are generally evaluated from left to right. Another point to note is that in an
expression which involves division, care should be taken to avoid a division by zero, since this
results in infinity or an abnormal value. In Chapter 5 on control statements, we will see how a
check can be done before a division occurs and prevent such operations.

Program 4.1

#include <stdio.h>

main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;

printf("Sum of var1 and var2 is %d\n", result);


result = var3 * var3;
printf("Square of var3 is %d\n", result);
result = var2 +var3 * var4; /* precedence */
printf("var2 + var3 * var4 =%d\n", result);
}
Formatted Input and output

C provides standard functions scanf() and printf(), for performing formatted input and
output .These functions accept, as parameters, a format specification string and a list of variables.

The format specification string is a character string that specifies the data type of each variable to
be input or output and the size or width of the input and output.

Now to discuss formatted output in functions.

Formatted Output

The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.

Syntax:

printf (format, data1, data2,……..);

In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (“%c”, data1);

The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.

See the following table conversion character and their meanings.

Conversion
Meaning
Character
D The data is converted to decimal (integer)
C The data is taken as a character.
The data is a string and character from the string , are printed until a NULL,
S
character is reached.
F The data is output as float or double with a default Precision 6.

Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)

Example
printf (“%c\n”,data1);

The format specification string may also have text.

Example

printf (“Character is:”%c\n”, data1);

The text "Character is:" is printed out along with the value of data1.

Example with program

1. #include<stdio.h>
2. #include<conio.h>
3. Main()
4. {
5. Char alphabh="A";
6. int number1= 55;
7. float number2=22.34;
8. printf(“char= %c\n”,alphabh);
9. printf(“int= %d\n”,number1);
10. printf(“float= %f\n”,number2);
11. getch();
12. clrscr();
13. retrun 0;
14. }
15. Output Here…
16. char =A
17. int= 55
18. flaot=22.340000

Operator precedence

If more than one operators are involved in an expression, C language has a


predefined rule of priority for the operators. This rule of priority of operators is called
operator precedence.

In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational


operators(==, !=, >, <, >=, <=) and precedence of relational operator is higher than
logical operators(&&, || and !).

Example of precedence

19. (1 > 2 + 3 && 4)


20. This expression is equivalent to:

21. ((1 > (2 + 3)) && 4)

22. i.e, (2 + 3) executes first resulting into 5

23. then, first part of the expression (1 > 5) executes resulting into 0 (false)

24. then, (0 && 4) executes resulting into 0 (false)

25. Output

26. 0

Associativity of operators

27. If two operators of same precedence (priority) is present in an expression, Associativity of


operators indicate the order in which they execute.

Example of associativity

28. 1 == 2 != 3

29. Here, operators == and != have same precedence. The associativity of both == and != is left
to right, i.e, the expression on the left is executed first and moves towards the right.

30. Thus, the expression above is equivalent to :

31. ((1 == 2) != 3)

32. i.e, (1 == 2) executes first resulting into 0 (false)

33. then, (0 != 3) executes resulting into 1 (true)

34. Output

35. 1
36. The table below shows all the operators in C with precedence and associativity.

37. Note: Precedence of operators decreases from top to bottom in the given table.

Summary of C operators with precedence and associatively

Operator Meaning of operator Associatively

() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection

! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)

* Multiply
/ Divide Left to right
% Remainder

+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)

<< Left shift


Left to right
>> Right shift

< Less than


<= Less than or equal
Left to right
> Greater than
>= Greater than or equal
Summary of C operators with precedence and associatively

Operator Meaning of operator Associatively

== Equal to
Left to right
!= Not equal to

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

Simple assignment
=
Assign product
*=
Assign quotient
/=
Assign remainder
%=
Assign sum
-=
Assign difference Right to left
&=
Assign bitwise AND
^=
Assign bitwise XOR
|=
Assign bitwise OR
<<=
Assign left shift
>>=
Assign right shift

, Separator of expressions Left to right


Decision Making And Branching

‘C’ language processes decision making capabilities supports the flowing statements
known as control or decision making statements

1. If statement

2. switch statement

3. conditional operator statement

4. Go to statement

If Statement : The if statement is powerful decision making statement and is used to control the
flow of execution of statements The If statement may be complexity of conditions to be tested

(a) Simple if statement

(b) If else statement

(c) Nested If-else statement

(d) Else –If

Simple If Statement : The general form of simple if statement is

If(test expression)

{ statement block;

} statement-x ;

The statement -block may be a single statement or a group of statement if the test
expression is true the statement block will be executed. Otherwise the statement -block will be
skipped and the execution will jump to the statement –X. If the condition is true both the
statement –block sequence .

Flow chart :

Ex : If(category = sports)

{ marks = marks + bonus marks;

} printf(“%d”,marks);
If the student belongs to the sports category then additional bonus marks are added to
his marks before they are printed. For other bonus marks are not added .

If –Else Statement : The If statement is an extension of the simple If statement the general form
is

If (test expression)

true-block statements;

else

false-block statements;

statement – x;

If the test expression is true then block statement are executed, otherwise the false –block
statement are executed. In both cases either true-block or false-block will be executed not both.

Flow chart :

Ex : If (code == 1)

boy = boy + 1;

else

girl = girl + 1;

st-x;

Here if the code is equal to ‘1’ the statement boy=boy+1; Is executed and the control is
transfered to the statement st-n, after skipping the else part. If code is not equal to ‘1’ the
statement boy =boy+1; is skipped and the statement in the else partgirl =girl+1; is executed
before the control reaches the statement st-n.
Nested If –else statement : When a series of decisions are involved we may have to use more
than one if-else statement in nested form of follows .

If(test expression)

{ if(test expression)

{ st –1;

else

{ st – 2;

}else

st – 3;

}st – x;

If the condition is false the st-3 will be executed otherwise it continues to perform the
nested If –else structure (inner part ). If the condition 2 is true the st-1 will be executed
otherwise the st-2 will be evaluated and then the control is transferred to the st-x

Some other forms of nesting If-else

If ( test condition1)

{ if (test condition2)

st –1 ;
} else

if (condition 3)

{ if (condition 4)

st – 2;

}st – x;

Else-If ladder : A multi path decision is charm of its in which the statement associated with
each else is an If. It takes the following general form.

If (condition1)

St –1;

Else If (condition2)

St –2;

Else if (condition 3)

St –3;

Else

Default – st;

St –x;
This construct is known as the wise-If ladder. The conditions are evaluated from the top
of the ladder to down wards. As soon as a true condition is found the statement associated with
it is executed and the control the is transferred to the st-X (i.e.., skipping the rest of the ladder).
when all the n-conditions become false then the final else containing the default – st will be
executed.

Ex : If (code = = 1) Color = “red”;

Else if ( code = = 2) Color = “green”

Else if (code = = 3) Color = “white”;

Else Color = “yellow”;

If code number is other than 1,2 and then color is yellow.

Switch Statement : Instead of else –if ladder, ‘C’ has a built-in multi-way decision statement
known as a switch. The general form of the switch statement is as follows.

Switch (expression)

case value1 : block1;

break;

case value 2 : block 2;

break;

default : default block;

break;

st – x;
The expression is an integer expression or character value1, value-2---- are constants or
constant expressions and also known as case lables. Each of the values should be a unit within a
switch and may contain zero or more statements.

When the switch is executed the value of the expression is successively compared against
the values value-1,value-2------- If a case is found whose value matches with the of the
expression then the block of statements that follows the case are executed .

The break statement at the end of each block signals the end a particular case and causes
an exist from the switch statement transfering the control to the st-x following the switch. The
default is an optional case . If will be executed if the value of the expression doesn’t match with
any Of the case values then control goes to the St-x.

Ex : switch (number)

case 1 : printf(“Monday”);

break;

case 2 : printf(“Tuesday”);

break;

case 3 : printf(“Wednesday”);

break;

case 4 : printf(“Thursday”);

break;

case 5 : printf(“Friday”);

break;

default : printf(“Saturday”);

break;

The Conditional ( ? : ) Operator : These operator is a combinations of question and colon and
takes three operands this is also known as conditional operator. The general form of the
conditional operator is as follows
Conditional expression? Expression 1:expression2

The conditional expression is evaluated first If the result is non-zero expression is


evaluated and is returns as the value of the conditional expression, Otherwise expression2 is
evaluated and its value is returned.

Ex : flag = ( x<0) ? 0 : 1

It’s equalent of the If-else structure is as follows

If ( x<0)

Flag = 0;

Else

Flag = 1;

Goto Statement : The goto statement is used to transfer the control of the program from one
point to another. It is something reffered to as unconditionally branching. The goto is used in the
form

Goto label;

Label statement : The label is a valid ‘C’ identifier followed by a colon. we can precode any
statement by a label in the form

Label : statement ;

This statement immediately transfers execution to the statement labeled with the label
identifier.

Ex : i = 1;

bc : if(1>5) Output : 1

goto ab; 2

printf(“%d”,i); 3

++i; 4

goto bc; 5

ab : {

printf(“%d”,i); }
How to use Loops in C
In any programming language including C, loops are used to execute a set of statements
repeatedly until a particular condition is satisfied.

How it Works
The below diagram depicts a loop execution,

As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false
then the execution breaks out of the loop. After the loop is successfully executed the execution
again starts from the Loop entry and again checks for the Test condition, and this keeps on
repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body. After every execution of the loop body, condition is verified, and if it is found to
be true the loop body is executed again. When the condition check returns false, the loop body is
not executed, and execution breaks out of the loop.

Types of Loop
There are 3 types of Loop in C language, namely:
while loop

1. for loop

2. do while loop

while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.

 Variable initialization.(e.g int x = 0;)

 condition(e.g while(x <= 10))

 Variable increment or decrement ( x++ or x-- or x = x + 2 )


Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}

Example: Program to print first 10 natural numbers


#include<stdio.h>

void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}

1 2 3 4 5 6 7 8 9 10

for loop
forloop is used to execute a set of statements repeatedly until a particular condition is satisfied.
We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
It first evaluates the initialization code.

1. Then it checks the condition expression.

2. If it is true, it executes the for-loop body.

3. Then it evaluate the increment/decrement condition and again follows from step 2.
4. When the condition expression becomes false, it exits the loop.

Example: Program to print first 10 natural numbers


#include<stdio.h>

void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}

1 2 3 4 5 6 7 8 9 10

Nested for loop


We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}

Example: Program to print half Pyramid of numbers


#include<stdio.h>

void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}

21

321

4321

54321

do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the
loop first and at the end, the condition is checked using while statement. It means that the body
of the loop will be executed at least once, even though the starting condition inside while is
initialized to be false. General syntax is,
do
{
.....
.....
}
while(condition)

Example: Program to print first 10 multiples of 5.


#include<stdio.h>

void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}

5 10 15 20 25 30 35 40 45 50

Jumping Out of Loops


Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the
loop as soon as certain condition becomes true. This is known as jumping out of loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.

2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On
encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.

You might also like