loop

Sometimes we want some part of our code to be executed more than once. We can either repeat the code in our program or use loops instead. It is obvious that if for example we need to execute some part of code for a hundred times it is not practical to repeat the code. Alternatively we can use ourrepeating code inside a loop.
There are three methods forwhile and do-while which we can repeat a part of a program.

1. while loop

while loop is constructed of a condition or expression and a single command or a block of commands that must run
in a loop.
//for single statement  
while(expression)
statement;

//for multiple statement
while(expression)
{
block of statement
}
The statements within the while loopwould keep on getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
The general form of while is as shown below:
initialise loop counter;  
while (test loopcounter using a condition)
{
do this;
and this;
increment loopcounter;
}

Example

#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

2. for loop

for loop is something similar to while loop but it is more complex. forloop is constructed from acontrol statement that determines how many times the loop will run and a command section. Command section is either a single command or a block of commands.
//for single statement  
for(control statement)
statement;

//for multiple statement
for(control statement)
{
block of statement
}
Control statement itself has three parts:
for ( initialization; test condition; run every time command )
  • Initialization part is performed only once at for loop start. We can initialize a loop variable here.
  • Test condition is the most important part of the loop. Loop will continue to run if this condition is valid (true). If the condition becomes invalid (false) then the loop will terminate.
  • Run every time command section will be performed in every loop cycle. We use this part to reach the final condition for terminating the loop. For example we can increase or decrease loop variable’s value in a way that after specified number of cycles the loop condition becomes invalid and for loop can terminate.

Example

#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

3. do-while loop

The while and for loops test the termination condition at the top. By contrast, the third loop in C, the do-while, tests at the bottom after making each pass through the loop body; the body is always executed at least once.
The syntax of the do is
do
{
statements;
}while (expression);
The statement is executed, then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates. Experience shows that do-while is much less used than while and for. A do-whileloop is used to ensure that the statements within the loop are executed at least once.

Example

#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

4. Break and Continue statement

We used break statement in switch...case structures in previouslly. We can also use
"break" statement inside loops to terminate a loop and exit it (with a specific condition).
In above example loop execution continues until either num>=20 or entered score is negative.
while (num<20) 
{
printf("Enter score : ");
scanf("%d",&scores[num]);
if(scores[num]<0)
break;
}
Continue statement can be used in loops. Like breakcommand continuechanges flow of a program. It does not terminate the loop however. It just skips the rest of current iteration of the loop and returns to starting point of the loop.

Example 1 (break)

#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
if( a > 15) {
/* terminate the loop using break statement */
break;
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

Example 2 (continue)

#include<stdio.h> 
main()
{
while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}
}
In above example, program accepts all input but omits the '.' character from it. The text will be echoed as you enter it but the main output will be printed after you press the enter key (which is equal to inserting a "\n" character) is pressed. As we told earlier this is because getchar()function is a buffered input function.

5. Goto and labels

C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it. We have not used goto in this book.
Nevertheless, there are a few situations where gotos may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop. Thus:
for ( ... )
{
for ( ... )
{
...
if (disaster)
{
goto error;
}
}
}
...
error:
/* clean up the mess */
This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.
label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.

Example

#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Note - By uses of goto, programs become unreliable, unreadable, and hard to debug. And yet many programmers find goto seductive.

Examples:

1Print All ASCII values - C Language Programming..
/**********************************************************
Statement - Print All ASCII Values
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
**********************************************************/


#include<stdio.h>
#include<conio.h>

void main()
{
int i = 0;
char ch;
clrscr();

for (i = 0; i < 256; i++)
{
printf("%c ",ch);
ch = ch + 1;
}

getch();
}

2. Convert a given Binary number into Decimal number - C Language Programming..

./**********************************************************************************
 Statement - Convert the given binary number into decimal
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
**********************************************************************************/

#include <stdio.h>
#include <conio.h>

void main()
{
int num, bnum, dec = 0, base = 1, rem ;
clrscr();

printf("Enter a binary number(1s and 0s)\n");
scanf("%d", &num); /*maximum five digits */

bnum = num;

while( num > 0)
{
rem = num % 10;
dec = dec + rem * base;
num = num / 10 ;
base = base * 2;
}

printf("The Binary number is = %d\n", bnum);
printf("Its decimal equivalent is =%d\n", dec);

getch();
} /* End of main() */

/*---------------------------------------------
Output
Enter a binary number(1s and 0s)
10101
The Binary number is = 10101
Its decimal equivalent is =21
----------------------------------------------*/


3. Print Diamond Shape - C Language Programming..

    *
***
*****
***
*
/*******************************************************
Statement - Print Diamond
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
*******************************************************/


#include <stdio.h>
#include <conio.h>

void main()
{
int n, c, k, space = 1;
clrscr();

printf("Enter number of rows\n");
scanf("%d", &n);

space = n - 1;

for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");

space--;

for (c = 1; c <= 2*k-1; c++)
printf("*");

printf("\n");
}

space = 1;

for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");

space++;

for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");

printf("\n");
}

getch();
}


4. Check leap year in a range give by user - C Language Programming..

/*******************************************************
Statement - Check leap year in a range.
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
*******************************************************/


#include <stdio.h>
#include <conio.h>

void main(){
int year;
int min_year,max_year;
clrscr();

printf("Enter the lowest year: ");
scanf("%d",&min_year);

printf("Enter the heighest year: ");
scanf("%d",&max_year);

printf("Leap years in given range are: ");
for(year = min_year;year <= max_year; year++){
if(((year%4==0)&&(year%100!=0))||(year%400==0))
printf("%d ",year);
}

getch();
}

/*

Definition of leap year:
------------------------
Rule 1:
-------
A year is called leap year if it is divisible by 400.
For example:
------------
1600, 2000 etc leap year while 1500, 1700 are not leap year.

Rule 2:
-------
If year is not divisible by 400 as well as 100 but it is divisible by 4 then that year are also leap year.
For example:
------------
2004, 2008, 1012 are leap year.


Leap year logic or Algorithm of leap year or Condition for leap year:
---------------------------------------------------------------------
IF year MODULER 400 IS 0
THEN leap_year
ELSE IF year MODULER 100 IS 0
THEN not_leap_year
ELSE IF year MODULER 4 IS 0
THEN leap_year
ELSE
not_leap_year

*/


5. Convert a given Binary number into Decimal Number Using Bitwise Operators - C Language Programming..

/**********************************************************
Statement - Convert number to binary using bitwise operators
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
**********************************************************/


#include<stdio.h>
#include<conio.h>

//Display integer number into binary using bitwise operator
void printBinary(int num)
{
int mask = 0x4000;
if ((num & 0x8000) == 0)
printf("0");
else
printf("1");
while (mask != 0) {
if ((num & mask) == 0)
printf("0");
else
printf("1");
mask = mask >> 1;
}
}

void main()
{
int intNum;
clrscr();

printf("\nEnter a integer number :");
scanf("%d", &intNum);

printf("\nInteger number in binary format :");
printBinary(intNum);

getch();
}

6. Find the value of sin(x) using the series up to the given accuracy without using library function - C Language Programming..

/**********************************************************************************
Statement - Find the value of sin(x) using the series up to the given accuracy
(without using user defined function). Also print sin(x) using library function.
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
**********************************************************************************/


#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>

void main()
{
int n, x1;
float acc, term, den, x, sinx=0, sinval;

clrscr();

printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);

x1 = x;

/* Converting degrees to radians*/

x = x*(3.142/180.0);
sinval = sin(x);

printf("Enter the accuary for the result\n");
scanf("%f", &acc);

term = x;
sinx = term;
n = 1;

do
{
den = 2*n*(2*n+1);
term = -term * x * x / den;
sinx = sinx + term;
n = n + 1;

} while(acc <= fabs(sinval - sinx));

printf("Sum of the sine series = %f\n", sinx);
printf("Using Library function sin(%d) = %f\n", x1,sin(x));

getch();

} /*End of main() */

/*------------------------------
Output
Enter the value of x (in degrees)
30
Enter the accuary for the result
0.000001
Sum of the sine series = 0.500059
Using Library function sin(30) = 0.500059

RUN 2
Enter the value of x (in degrees)
45
Enter the accuary for the result
0.0001
Sum of the sine series = 0.707215
Using Library function sin(45) = 0.707179
---------------------------------------------*/
                                                                            
  
Statement Control..                                                                                                   Array..
<-Previous Artical                                                                                                                      Next->