Sunteți pe pagina 1din 10

UNIT-2.

2
The loop is defined as the block of statements which are repeatedly executed for certain number
of times. There are two types of loop statements are available: Those loops which check the test
condition at the entry level itself, and the other checks test condition at the exit level.
The loop in a program consists of two parts, one is body of the loop and another is control
statement. The control statement is used to test the condition and then directs the repeated
execution of the statements in the body of the loop. Any looping statement would include1. Initialization of a condition variable.
2. Test the control statement.
3. Executing the body of the loop depending on the condition.
4. Updating the variable.
There available loop structures available in C is

The While Loop


The while loop is an entry controlled loop statement, means the condition is evaluated first and
if it is true, then the body of the loop is executed. After executing the body of the loop, the
condition is once again evaluated and if it is true, the body is executed once again, the process
of repeated execution of the body of the loop continues until the condition finally becomes
false and the control is transferred out of the loop.

In itia liz a tio n

/* A d d itio n o f n a tu r a l n u m b e r s u p to 5 u s in g w h ile lo o p * /

S y n ta x :

w h ile
{
.............
B o d y o f th e lo o p
.............
}

F a ls e
C o n d itio n

True
B o d y o f th e L o o p

# in c lu d e < s td io .h >
m a in ( )
{
in t i, s u m = 0 ;
w h ile (i< = 5 )
{
s u m = s u m + i;
i+ + ;
}
p r in tf ( " T h e s u m o f n u m b e r s u p to 5 is % d :" ,s u m ) ;
}

E x p l a n a t i o n : H e r e , f i r s t e v a l u a t e s w h e t h e r 'i ' i s l e s s t h a n o r e q u a l t o 5 . A t f i r s t i = 1 s o t h e c o d i t i o n i s t r u e ,
n o w s u m i s a d d e d w i t h t h e v a l u e o f 'i ' a n d g e t s u m a s o n e , t h e n 'i ' i s i n c r e m e n t e d b y 1 , t h e n i t e v a l u a t e s
th e c o n d itio n a g a in . T h is p ro c e s s is g o in g o n till th e c o n d itio n is fa ls e . W h e n th e c o n d itio n is fa ls e th e
p r in tf() s ta te m e n t is e x e c u te d a n d d is p la y s th e re s u lt.

Do-While Loop
It is also repetitive control structure and executes the body of the loop once irrespective of the
condition, and then it checks the condition and continues the execution until the condition
becomes false.
The statements within the body of the loop is executed once, then it evaluates for the condition,
if it is true, then it executes body until the condition becomes false.
In itia liz a tio n
S y n ta x :
do{
{
.............
B o d y o f th e lo o p
.............
} w h ile (c o n d itio n )

B o d y o f th e L o o p

Tru e

C o n d itio n

F a ls e

/* A d d it io n o f n a t u r a l n u m b e r s u p t o 5 u s in g d o - w h ile lo o p * /
# in c lu d e < s td io .h >
m a in ()
{
in t i, s u m = 0 ;
do
{
s u m = s u m + i;
i+ + ;
} w h ile (i< = 5 );
p r in tf ( " T h e s u m o f n u m b e r s u p to 5 is % d :" ,s u m ) ;
}

E x p la n a tio n : In th e a b o v e p ro g ra m th e v a lu e o f i is e v a lu a te d a s 1 a n d v a lu e o f s u m is in itia liz e d a s 0 .


I n th is p r o g r a m th e d o ..w h ile is e x e c u te d tje b o d y a n d c a lc u la te s th e s u m a n d in c r e m e n t th e i v a lu e b y
1 u n til th e c o n d itio n s a tis fie s i< = 1 0 . T h e n p rin ts s u m v a lu e a s o u tp u t.

T h e d o ...w h ile c o m m a n d s t r c u r e

For Loop
The for loop is another repetitive control structure, and is used to execute set of instructions
repeatedly until the condition becomes false.
The assignment, incrementation or decrementation and condition checking is done in for
statement only, where as other control structures are not offered all these features in one
statement.
For loop has three parts
1. Initialize counter.
2. Test condition is used to initialize counter variable.
3. Increment/decrement is used to increment or decrement counter variable.

In itia liz a tio n


S y n ta x :
B o d y o f th e L o o p

fo r (in itia liz a tio n ; c o n d itio n ;in c re /d e c re m e n t


{
.............
B o d y o f th e lo o p
.............
}

I n c r e m e n t/D e c r e m e n t

True

C o n d itio n

F a ls e

E x a m p le : P ro g ra m to p rin t n n u m b e rs
u s in g f o r..lo o p s tru c tu re .
/* P ro g ra m to p rin t n n u m b e rs * /
# in c lu d e < s td io .h >
v o id m a in ()
{
in t i,n ;
c lrs c r();
p rin tf(" E n te r a n u m b e r :" );
s c a n f ( " % d " ,& n );
fo r(i = 0 ; i< n ; i= i+ 1 )
{
p r in tf ( " T h e n u m b e r s a r e % d \n " ,i) ;
}
g e tc h ();
}

E x p la n a tio n : In th e a b o v e p ro g ra m p rin ts th e n n u m b e rs o n th e s c re e n , u s in g fo r lo o p th e n v a lu e c a n b e
s u p p lie d b y th e u s e r. i.e ., if w e g iv e n a s 5 it p rin ts 0 ,1 ,2 ,3 ,4 ,5 if w e g iv e s 1 0 it p r in ts 0 ,1 ,2 .....9 a n d s o o n .

Comparison between while and do while


S .N o
1

W h ile
T h is is th e to p te s te d lo o p

d o ..W h ile
T h is is th e b o tto m te s te d lo o p

T h e c o n d itio n is firs t te s te d if
th e c o n d itio n o s tru e th e n th e
b lo c k is e x e c u te d u n til th e
c o n d itio n b e c o m e s fa ls e

It e x e c u te s b o d y o n c e , a fte r it
c h e c k s th e c o n d itio n , if it is tru e
th e b o d y is e x e c u te d u n til th e
c o n d itio n b e c o m e s fa ls e .

L o o p w ill n o t b e e x e c u te d if
th e c o n d itio n is fa ls e

L o o p is e x e c u te d a tle a s t o n c e e v e n
th ro u g h th e c o n d itio n is fa ls e .

Nesting Of For Loop


3

Like if statement for loop also nested. The loop within the loop is called nested loop. In nested
for loops two or more for statements are included in the body of the loop. The number of
iterations in this type of structure will be equal to the number of iterations in the outer loop
multiplied by the number of iterations in the inner loop.
Example :
/* Program using nesting of for loops */
#include<stdio.h>
main()
{
int i,j;
for(i=1;i<=3;i++)
{
printf("\n");
for(j=1;j<=3;j++)
printf("%d\t",j);
}
}
Additional features of for loop.
1. We can initialize more than one variable at a time.
Example: for (i=1, j=1; i<=10;i++)
2. One or more section of for loop may be omitted, if necessary
Example: for(; i<=100;)
3. The test condition may have any compound relation
Example: for(i=1;i<10 && sum <100; j++)
{
Sum=sum+j;
}
The Break Statement
The break statement is used to terminate the loop. When the keyword break is used inside
any 'C' loop, control automatically transferred to the first statement after the loop.
When the break statement is encounted inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
Syntax: break;
A break is usually associated with an if statement. /* Program using break statement */
Example : Program to print the number upto 5 using break statement.
#include<stdio.h>
4

main ()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break; /* break statement */
printf("%d", i);
}
}
The Continue Statement
In some situations, we want to take the control to the beginning of the loop, bypassing the
statements inside the loop which have not yet been executed, for this purpose the continue
is used. When the statement continues is encountered inside any 'C' loop control
automatically passes to the beginning of the loop.
Syntax: continue
Like break statement the continue statements also associate with if statement.
/* Program to calculate the sum of the given positive numbers */
#include<stdio.h>
main
{
int i,n,sum=0;
for(i=1;i<=5;i++)
{
printf("Enter any number.....\n");
scanf("%d",&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf("Sum is .....%d",sum);
}

b reak

S .N o
1
2
3

c o n tin u e

B re a k s ta te m e n t ta k e s th e c o n tro l C o n tin u e s ta te m e n t ta k e s th e c o n tro l


to th e b e g in n in g o f th e lo o p .
to th e o u ts id e o f th e lo o p .
It is a ls o u s e d in s w itc h s ta te m e n t T h is c a n b e u s e d o n ly in lo o p
s ta te m e n t
A lw a y s a s s o c ia te d w ith if
c o n d itio n in lo o p s

T h is is a ls o a s s o c ia te d w ith if
c o n d itio n

Goto Statement
C' provides the goto statement to transfer control unconditionally from one place to another
place in the program.
A goto statement can cause program control almost anywhere in the program
unconditionally.
The goto statement requires a label to identify the place to move the execution. A label is a
valid variable name and must be ended with colon (:).
Example :

/* Program using goto statement */

#include<stdio.h>
main ()
{
int a, b;
printf("\nEnter the numbers");
scanf("%d %d",&a,&b);
if(a==b)
goto vahini;
else
{
printf("\n A and B are not equal");
exit(0);
}
vahini:
printf("A and B are equal");
}

Strings in C
6

In C language the group of characters, digits and symbols enclosed within quotation
marks are called as strings otherwise strings are array of characters. Null character (\0) is
used to mark the end of the string.
The terminating null (\0) is important, because it is the only way the functions that work
with a string can know where the string ends.
V
65512

65512

65512

65512

A
65512

I
65512

\0
65512

Initialization of Strings
char name[ ]="VAHINI";
char name[]= V, A ,H ,I ,N ,I;
The characters of the string are enclosed within a pair of double quotes.
The initialization of NULL character is not essential because the C compiler inserts the
NULL (\0) character automatically at the end of the string.
Reading And Writing String
The '%s' control string can be used in scanf() statement to read a string from the terminal
and the same may be used to write string to the terminal in printf() statement.
#include<stdio.h>
main( )
{
char name[ ] = "Vahini Engg College" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] );
i++ ;
}
}
The output is...

Vahini Engg College

Strings Manipulations
The 'C' compiler provides the following string handling functions, which are contained in
the header file--string.h. Most commonly performed operations over strings areFUNCTION

PURPOSE

strlen()

Used to find length of the string

strcpy()

Used to copy one string to another

strcat()

Used to combine two strings

strcmp()

Used to compare characters of two strings.


7

strrev()

Used to reverse a string

strlwr()

Used to convert strings into lower case

strupr()

Used to convert strings into upper case

strdup()

Used to duplicate a string

strncpy()

Used to copy first 'n' characters of one string into another

strncmp()

Used to compare first 'n' characters of two strings.

strcmpi()

Used to compare two strings without regarding the case.


/* Program using strcat() function * /

#include<stdio.h>
main ()
{
char source[]="vahini";
char target[10]= "college";
strcat(target,source) ;
printf("\n Target string is %s",target) ; /* output: collegevahini*/
}
/* Program using strcpy() function * /
#include<stdio.h>
main ()
{
char source[]="vahini";
char target[10];
strcpy(target,source) ;
printf("\n Source string is %s",source) ; /* output: vahini */
printf("\n Target string is %s",target) ; /* output: vahini */
}
/* Program using strlen() function * /
#include<stdio.h>
main ()
{
char source[]="vahini";
int length;
length=strlen(source) ;
printf("\n The length of the string is%d",length) ; /* output: 6 */
8

Input/Output
These statements are used to Input/Output a single/group of characters from/to the
input/output devices. Here the user cannot specify the type of data that is going to be
input/output.
Input and Output Functions
(1) Unformatted Input/Output Statements:
Input

Output

getc( );

putc( );

getchar( );

putchar( );

gets( );

puts( );

(2) Formatted Input/Output Statements:


Input

Output

scanf( );

printf( );

fscanf( );

fprintf( );

getc() Function
This is used to accept a single character from the standard input to a character variable.
Syntax

character variable=getc();

Description

Character variable is the valid 'c' variable of the type of char data type

Example

char c;
c=getc();

putc() Fucntion
This is used to display a single character in a character variable to standard output device.
Syntax

putc (character variable);

Description

Character variable is the valid 'c' variable of the type of char data type

Example

char c;
putc(c);

gets & puts Function


The gets () function is used to read the string (string is a group of characters) from the
standard input device (keyboard).
The puts () function is used to display/write the string to the standard output device
(Monitor).
/* Program using gets() and puts() function */
#include<stdio.h>
9

main()
{
char stu_name[40];
puts("Enter Name:");
gets(stu_name); /* gets the character from keyboard */
puts("Print the Name:");
puts(stu_name);
}
Single Character I/P Function: getchar(): getchar() is used to read a character from the
terminal, the syntax isch=getchar();
A Single character can be given to the computer using 'C' input library function getchar().
where, ch is a variable of char type. As a result of this, a character types at the terminal is
assigned to the variable ch. This can be used repeatedly to accept a line of characters.
Single Character I/O Function: putchar() is the counterpart of getchar(). It is used to
display a character on the monitor. It takes the general form of putchar(ch);
which ch represents a variable type char or a character constant. It displays the character
stored in ch on the monitor. The putchar() function is used to display one character at a time
on the standard output device. This function does the reverse operation of the single
character input function.
Character Test Function
The 'C' language provides many of character test functions that are used to test the character
taken from the input. The below table summarizes some of the 'C' character test functions.
Function

Test

isalnum(ch)

Is ch an alphanumeric character?

isalpha(ch)

Is ch an alphabetic character?

isdigit(ch)

Is ch a digit?

islower(ch)

Is ch a lowercase letter?

isupper(ch)

Is ch a uppercase letter?

isspace(ch)

Is ch a blank space character?

tolower(ch)

Convert ch to lowercase.

toupper(ch)

Convert ch to uppercase.

10

S-ar putea să vă placă și