How2Lab Logo
tech guide & how tos..


Control Statements in C


For executing a group of statements repetitively, C provides three types of loop constructs, viz. for, while, and do-while. These classes of statements are also referred as control statements.

Let us understand each of these:

while loop

 ...
 <statement 1> 
 while(<expression>)
 {
    <statement 2>
 }
 <statement 3> 
 ...

In the while loop construct as shown above, after executing <statement 1>, the C program will jump to evaluate <expression>. If <expression> evaluates to true (i.e. a non-zero value), the program will enter the loop and execute <statement 2> (this could be a set of statements enclosed within the curly braces). After execution of <statement 2>, program will again return to <expression> to re-evaluate it. The expression may contain certain variables whose values change each time <statement 2> is executed. On the second evaluation of <expression>, if it again evaluates to true, loop will be re-entered and <statement 2> will be executed again. After execution of <statement 2> again the program will return to <expression>. This process will go on until <expression> evaluates to false. When the expression evaluates to false, control will jump out of the loop to <statement 3> and the rest of the program will be executed in sequential order.


do-while loop

 ...
 <statement 1> 
 do
 {
    <statement 2>
 } while(<expression>); 
 <statement 3> 
 ...

In the do-while loop construct as shown above, after executing <statement 1>, the C program will jump to execute <statement 2> (this could be a set of statements enclosed within the curly braces). After execution of <statement 2>, program will evaluate <expression>. If <expression> evaluates to true (i.e. a non-zero value), the program will enter the loop again and re-execute <statement 2> After execution of <statement 2> again the program will jump to <expression>. This process will go on until <expression> evaluates to false. When the expression evaluates to false, control will jump out of the loop to <statement 3> and the rest of the program will be executed in sequential order.


for loop

 ...
 <statement 1>
 for(<expression1>; <expression2>; <expression3>) 
 { 
    <statement 2>
 }
 <statement 3> 
 ...

In the for loop construct, after executing <statement 1>, the C program will jump to execute <expression1>. This expression is executed only once, just before entering the loop for the first time. Thereafter, <expression2> is evaluated. If it evaluates to true, loop is entered and <statement 2> is executed. This could be a set of statements enclosed within the curly braces. After execution of <statement 2>, program will jump to <expression3>, execute it and then return back to <expression2>. If <expression2> evaluates to true again, the program will re-enter the loop and re-execute <statement 2> After execution of <statement 2> again the program will jump to <expression3> & then <expression2>. This looping process of expression2 - statement2 - expression3 will go on until <expression2> evaluates to false. When the expression2 evaluates to false, control will jump out of the loop to <statement 3> and the rest of the program will be executed in sequential order.


Let us look at an example of the same logic implemented using the 3 loop constructs. Consider a program for computation of average. This program can be implemented using the 3 loop constructs as demonstrated below.

The program will accept a number from the user in every pass. After all numbers are accepted, it will compute their average.

while loop

 #include <stdio.h> 
 main() 
 {
	int ntot, n=1; 
	float num, avg, sum=0; 
	printf("\nSpecify how many numbers you will feed: ");
	scanf("%d", &ntot);
 
	while(n <= ntot)
	{
		printf("Give Number %d: ",n);
		scanf("%f", &num);
		sum += num;
		n++;
	}

	avg = sum/ntot;
	printf("\nThe average is %f\n", avg);
 }

do-while loop

 #include <stdio.h> 
 main() 
 {
	int ntot, n=1; 
	float num, avg, sum=0; 
	printf("\nSpecify how many numbers you will feed: ");
	scanf("%d", &ntot);
 
	do
	{
		printf("Give Number %d: ",n);
		scanf("%f", &num);
		sum += num;
		n++;
	} while(n <= ntot);
  
	avg = sum/ntot;
	printf("\nThe average is %f\n", avg);
 }

for loop

 #include <stdio.h> 
 main() 
 {
	int ntot, n; 
	float num, avg, sum=0; 
	printf("\nSpecify how many numbers you will feed: ");
	scanf("%d", &ntot);
 
	for(n = 1; <= ntot; n++)
	{
		printf("Give Number %d: ",n);
		scanf("%f", &num);
		sum += num;
	}

	avg = sum/ntot;
	printf("\nThe average is %f\n", avg);
 }

Another Example

 /* Program to check whether a given number is a palindrome or not */
 #include <stdio.h>
 main()
 {
	int number, digit, reverse=0, store_num;

	printf("Give a Number:");
	scanf("%d", &number); fflush(stdin);
	store_num = number;

	do
	{
		digit = number % 10;
		reverse = (reverse * 10) + digit;
		number /= 10;
	}while(number != 0);

	number = store_num;
	if(number == reverse)
		printf("The number is a palindrome.\n");
	else
		printf("The number is not a palindrome.\n");

    return;
 }


Comma operator

This operator is used in a for statement to separate multiple statements in the expressions within
for(<expression1>; <expression2>; <expression3>). Let us understand this through the below example.

 for(i=1,j=2; i<5,j<10; ++i,j++)
 {
	...
 }

In the above code snippet, <expression1> consists of two statements, viz. i=1 and j=2. Now normally in a C program you would separate statements with a semi-colon (;). However, in the for construct, since semi-colon itself acts as the separator to separate out the 3 expressions, introducing a semi-colon to also separate the statements within each expression would confuse the C compiler. To overcome this, C allows the statements within an expression in the for construct to be separated by comma.

Note that the comma operator is only relevant in case of for loop construct, not for while and do-while.



break & continue statements

The break statement is used to jump out of a loop. You would have also noticed the usage of break earlier in the switch construct.

The continue statement is used to bypass/skip the remaining statements in a loop and jump to the next pass.

The break and continue statements can be used in all 3 types of loop constructs. We will see usages of these statements in various C programs as we move ahead in C, with articles posted in future.



Nested loops

In a complex program it will often be necessary to nest one loop inside another loop. The structure of a nested loop is depicted below.

 /* begin loop1 */ 
 {
	<statement 1>;
	/* begin loop2 */
	{
		<statement 2>;
	} /* end of loop2 */
	<statement 3>;
 } /* end of loop1 */ 

Loops 1 & 2 can be any of the 3 types of loop constructs. Suppose loop1 was designed to execute 5 times and loop2 was designed to execute 4 times. Then, for each pass of loop1, loop2 will run 4 passes. Since loop1 will run 5 passes, loop2 will effectively run 20 passes, 4 in each pass of loop1.

The example below illustrates the usage of nested loops in computing average grade of students in different subjects.

 #include <stdio.h> 
 #define no_of_students 30 
 main() 
 {
   int no_of_courses_registered, grade, credit;
   int total_credits, course_no, i=1, j, sum; 
   float average_grade; 
   char student_name[61], subject[41]; 

   printf("Begin AVERAGE GRADE COMPUTATION for %d students\n", no_of_students);

   /* begining of the outer loop */ 
   while(i <= no_of_students) 
   {
      printf("\nEnter Name of student%d and number of courses registered by him: ",i); 
      scanf("%s %d",student_name,&no_of_courses_registered); fflush(stdin);
      sum = 0;
      total_credits = 0; 
      if(no_of_courses_registered == 0) 
      {
         printf("\nStudent %s has not registered in any course.\n", student_name); 
         i++;
         continue;
      }

      printf("Processing grades of student %s\n", student_name);

      /* begining of the inner loop */
      for(j=1; j <= no_of_courses_registered; j++) 
      {
         printf("\nEnter Course No., Subject, Credit & Grade in course %d: ", j); 
         scanf("%d %s %d %d", &course_no, subject_name, &credit, &grade); fflush(stdin);
         sum += credit * grade;
         total_credits += credit; 
      } /* end of the inner loop */ 

      average_grade = sum / total_credits; 
      printf("\nAverage grade obtained by %s is %f\n", student_name, average_grade); 
      i++; 
   } /* end of outer loop */ 
   printf("End of AVERAGE GRADE COMPUTATION.\n"); 
 }


goto statement

The goto statement can be used to unconditionally alter the program execution sequence. This statement is written as goto label;.

As a result of the goto statement, the program execution jumps to a new statement which is identified by the label. In the target statement the label must be followed by a colon (:). The labeled statement can be any statement inside the current function. You cannot jump across functions using goto.

Example:

 #include <stdio.h> 
 main() 
 {
	int a, b, sum;
	...
	...
	sum += (a + b);
	goto printf_statement;
	...
	...
	...
	printf_statement : printf("sum is %d\n", sum);
	...
	...
 }

Here after computation of sum, the program execution will jump to the statement having label print_statement and will print the value of sum.

Although the usage of goto may at times be convenient to programmers, it is desirable that usage of such statement is avoided as far as possible. In fact structured programming approach forbids the usage of goto statement. An unrestricted usage of goto statement, makes program debugging very difficult and may at times introduce logical errors.



LAB WORK

(1) Enter compile and run the following program to understand the use of while 
    and for statement with pre and post decrement operators.

	(a)	#include <stdio.h>
		main()
		{
			int n= 0,a = 0;
			while (n)
			{
				a++;
				n--;
				printf("value of a is %d\n",a);
				a = 0; n = 10;
				a++;
				printf("value of a is %d\n",a);
			}
		}

	(b)	#include <stdio.h>
		main()
		{
			int n, i, k;
			printf("Enter a positive value\n");
			scanf("%d",&n);
			i = 10;
			k = 1;
			q = n/i;
			while(q != 0)
			{
				i = i * 10;
				k++;
				q = n/i;
			}
			printf("\n The no. of digits in %d is %d\n",n,k);
		}

	(c)	#include <stdio.h>
		main()
		{
			char ch;
			ch = 'A';
			while (ch <= 'Z')
			{
				putchar(ch);
				++ch;
			}
			putchar ('\n');
			ch = 'z';
			while (ch >= 'a');
			{
				putchar(ch);
				--ch;
			}
		}

	(d)	#include <stdio.h>
		main()
		{
			int  i, j, sum = 0, prod = 0, k = 0;
			for(i = 0; i <= 10; i ++)
				sum += i;
			printf("The sum up to 10 is %d\n",sum);
			for(i = 10; i == 0,j <= 10; i ==,  j++)
				prod = prod + i * j;
			printf("The producer is %d\n",prod);

			//Note that in for below expression1 & expression 2 are not there
			//Yet ; is there to tell the compiler that i!=0 is expression 2
			for(;i!=0;)
			{
				i = i/3;
				k++;
			}
			printf("This loop has executed %d times \n",k);
		}

	(e)	#include <stdio.h>
		main()
		{
			char ch;
			for(ch = 'A'; ch <= 'Z'; ++ch)
				putchar(ch);
			putchar('\n');
			for(ch = 'z'; ch>= 'a'; --ch)
				putchar(ch);
			putchar('\n');
		}


(2) Write a C program, which calculates the sum of every 5th integer starting with i=2,
    for all value of i that are less than 200.
    (Hint: Find the sum of 2 + 7 + 12 + 17 + ...)
    Write the iteration part,
	(a) using a while statement 
	(b) using a do-while statement
	(c) using a for statement

(3) Write a C program, which continuously accepts characters (within a loop) from the 
    user (max. 80 times), and displays the corresponding ASCII value.
    Implement the loop using while, do-while and for constructs.

(4) Consider a modification of the previous problem, in which the program should print:
     - how many characters read are letters,
     - how many are digits,
     - how many are whitespace characters, and
     - how many are of other types
    (Hint: make use of switch construct as well)

(5) Write a C program to construct a pyramid of digits.
    The user provides the depth of the pyramid.
    For example if the user inputs 5, the pyramid to be contructed is as follows:
             1
           2 3 2
          3 4 5 4 3
        4 5 6 7 6 5 4
      5 6 7 8 9 8 7 6 5

(6) Write a C program, which will print the maximum and the minimum numbers from
    a list of number entered by the user.

(7) The Fibonacci number are members of a sequence in which each number is equal
    to the sum of the previous two numbers in the series. Thus, fi = (fi-1) + (fi-2),
    where fi is the i-th Fibonacci number.
    Write a program that will print Fibonacci numbers up to 100. Note: fo = f1 = 1

(8) A natural number is called a prime number if it is perfectly divisible (i.e. has 
    no remainder when divided) only by 1 or by itself.
    Write a program to display the first 50 prime numbers. 

(9) For each student in a class, the following data is to be entered:
	roll no		integer
	name		string
	course		string
	attendence_record	float
	fees cleared	char ('y' to indicate yes, 'n' to indicate no)

    A student is allowed to appear in the final examination if he/she has cleared 
    the fees and has more than 80% attendance.

    Write a C program to accept student information from the user and print 
    the Name and Roll number of the students who can attend the examination.

    The program should halt when the user indicates no further input.



Share:
Buy Domain & Hosting from a trusted company
Web Services Worldwide | Hostinger
About the Author
Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of premier engineering colleges & management institutes, and IT professionals.

Rajeev has founded Computer Solutions & Web Services Worldwide. He has hands-on experience of building variety of websites and business applications, that include - SaaS based erp & e-commerce systems, and cloud deployed operations management software for health-care, manufacturing and other industries.


Refer a friendSitemapDisclaimerPrivacy
Copyright © How2Lab.com. All rights reserved.