Skip to main content

C Programming #7 (More Complex Repetition)


The for loop:
Most of the time only few programmers use while loop as they are too busy using the for loop.
The for allows us to specify three thing about a loop in a single line:

  1. Setting a loop counter to an initial value.
  2. Testing the loop counter to determine whether it's value has reached the number of repetition desired.
  3. Increasing the value of loop counter each time the body of the loop has been executed.
General for of for statement:
for(initialize counter;test counter;increment counter)
{
do this;
and this;
and this;
}
Example program:
/*Calculation of simple interest for 3 sets of p, n and r*/
#include<stdio.h>
int main()
{
int p,n,count;
float r,si;
for(count=1;count<=3;count=count+1)
{
printf("Enter values of p,n and r");
scanf("%d%d%f,&p,&n,&r");
si=p*n*r/100;
printf("Simple Interest=Rs.%f\n",si");
}
return 0;
}
Explanation:
  • When the for statement is executed for first time the value of count is set to be an initial value 1.
  • After completion of program next time value is set to 3 and it will continue till the value reaches 3.
  • When the count reaches 4 the control exits the loop.
Nesting of loops:
  • Nesting of loops is very helpful for difficult conditions.
  • Nesting means you can use a for loop under for loop and give the conditions as per your requirement.
MULTIPLE INITIALIZATION IN FOR LOOP:
for (i=1;j=2;j<=10;j++)
The break statement:
  1. For the situation like we want to jump out of the loop instantly without waiting to get back to the condition we can use break.
  2. When the break is encountered in loop the control automatically gets out of the loop.
Example:
for(conditions)
{
do this
break;
}
Do while loop:
  • There is the minor difference between while and do while.
  • while test condition before executing the statements.
  • do-while execute test the condition after executing the statement.
Example for while is in my previous blog
Example for do-while:
#include<stdio.h>
int main()
{
do
{
printf("Hello there\n");
}while(4<1);
return 0;
}

Note:You can test this programs by compiling it and ask me any kind of question you have in comments.

Comments