Roles of loops in C with example?

Download excellent quality study note and ebooks of amie section a on Computing and Informatics (AD 303) in pdf,ppt,doc format
Post Reply
subham
Site Admin
Site Admin
Posts: 955
Joined: Sun Apr 29, 2012 11:23 pm

Roles of loops in C with example?

Post by subham »

In Programming, There may be a situation, when you need to execute a set of statements several number of times. Loop statement allow to program to execute a set of instructions repeatedly until a certain condition is satisfied. Loop Used in performing repetitive task in programming.

There are three types of loops

1. Using while statement-It repeat a statements or group of statement while a given condition is true. It test the condition before executing the loop body.
Syntax of while loop

while(condition)

{

Statements;

}

The “while loop” in c language starts with reserved word while followed by condition in parenthesis.This is followed by a single statements or a block of statements in enclosed in braces to define the beginning and end of the block.for single statements braces are not required.

Example

Program-Write a program to display multiplication table of number

main()

{

Int n,i;

printf(“enter the number”);

scanf(“%d”,&n);

i=1;

while (i<=5)

{

printf(“%3d * %3d = %3d\\n”,n,i,n+1);

i++;

}

}

Using a do while statement-Do-While loop is similar to while loop.Only difference between these two loops is that, in while loops ,condition is checked at first but in do while loops statements is executed first then the condition is checked, so the code are executed at least once in do while loops, even if the condition fails for the first time.
Syntax:

Do

{

Statement/s;

}

While(condition);

There is semicolonin end of While(); in do while loop

Program-Write a program to display multiplication table of a number.

main()

{

Int num,i;

printf(“enter the number “);

scanf(“%d”,&num);

i=1;

do

{

printf(“%3d * %3d = %3d\\n”,n,i,n+i);

i++;

}

while(i<=5);

}

3. Using a for statement:-For loop is most used statement in c.It causes a statement block to be executed for fixed number of times.

For loops allows us to specify three things about a loop in a single line:

(a). setting a loop counter to initial value

(b). Testing the loop counter to determine whether its value has reached the number of repetitions desired.

(c). Increasing the value of loop counter each time the program segments within the loop has been executed.

Syntax:

For(initialise counter; test counter; increment counter)

{

Statement block;

}

Program-Write a program to display the mathematical table of the number.

main()

{

Int n,i;

printf(“enter the number”);

scanf(“%d”,&n);

for(i=1;i<=5;i++)

printf(“%3d * %3d = %3d\\n”,n,i,n*1);

}



Output of all Program

enter the number 5

5*1=5

5*2=10

5*3=15

5*4=20

5*5=25

Roles of loops in C with example?

Sponsor

Sponsor
 

Post Reply

Return to “Computing and Informatics (AD 303)”