Friday, 30 August 2013

The “ while ” loop | C Programming Language Tutorial pdf



The “ while ” loop:

The simplest of all the looping structures in C is.
Syntax:
Initialization Expression;
while( Test Condition)
1
1 2
1 2 3
1 2 3 4
4 3 2 1
3 2 1
2 1
1
{
Body of the loop
Updaion Expression
}

=> The while is an entry – controlled loop statement.
=> The test condition is evaluated and if the condition is true, then the body of the loop is executed.
=> The execution process is repeated until the test condition becomes false and the control is transferred out of the loop.
=> On exit, the program continues with the statement immediately after the body of the loop.
=> The body of the loop may have one or more statements.
=> The braces are needed only if the body contains two or more statements.
=> It's a good practice to use braces even if the body has only one statement.
= = = = = = = = = =
Sum = 0; \ * Initialization * /
n = 1;
while(n<=10) \* Testing * /
{
Sum = Sum + n * n;
n = n+1; \* Incrementing * /
}
printf(“sum = %d \n”, Sum) ;
= = = = = = = = = = =
=> Program to add 10 consecutive numbers starting from 1. Use the while loop.
# include<stdio.h>
# include<conio.h>
main( )
{
int a=1, Sum=0;
clrscr( ) ;
while(a<=10)
{
Sum = Sum + a;
a++;
}
printf(“Sum of 1 to 10 numbers is: %d”, sum);
getch( );
}

Ouput:
Sum of 10 numbers is: 55

Program to calculate factorial of a given number use while loop.
# include<stdio.h>
# include<conio.h>
main ( )
{
long int n, fact =1;
clrscr( ) ;
printf( “\n Enter the Number:”);
scanf(“%ld”, &n);
while(n>=1)
{
fact = fact*n;
n - - ;
}
printf(“ \n factorial of given number is %d”, fact);
getch( );
}

Output :
Enter the Number :5 /* logic 5 * 4 * 3 * 2 * 1 = 120 */
Factorial of given number is 120

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved