Skip to main content

The Basics Of C Programming - Part 6.

You may encounter situations, when a block of code needs to be executed multiple times. Loops are used in programming languages to repeat a specific block until some end condition is met. There are three loops in C programming:

1.   for loop
2.   while loop
3.   do...while loop

A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop is:
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and if the condition is true (nonzero), codes inside the body of while loop is evaluated. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop.

The key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.


Example:
// write a program to find the factorial of a number.
#include <stdio.h>
int main()
{
int number;
long long factorial;

printf("Enter an integer: ");
scanf("%d",&number);

factorial = 1;

// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial *= number;  // factorial = factorial*number;
--number;   // for a positive integer n, factorial = n*….3*2*1
}
printf("Factorial= %lld", factorial);
return 0;
}
Output:
Enter an integer: 5
Factorial = 120

A for loop is a repetition control structure that allows to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop is:
for (init; condition; increment)
{
statement(s);
}
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.

Example:
// Program to calculate the sum of first n natural numbers
#include <stdio.h>
int main()
{
int n, count, sum = 0;

printf("Enter a positive integer: ");
scanf("%d", &n);

// for loop terminates when n is less than count
for(count = 1; count <= n; ++count)
{
sum += count;
}
printf("\nSum = %d", sum);
return 0;
}
Output:
Enter a positive integer: 10
Sum = 55

Explanation: The value entered by the user is stored in variable n. Let the user entered 10. The count is initialized to 1 and the test expression is evaluated. Since, the test expression count <= n (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will be equal to 1.

Then, the update statement ++count is executed and count will be equal to 2. Again, the test expression is evaluated. The test expression is evaluated to true and the body of for loop is executed and the sum will be equal to 3. And, this process goes on. Eventually, the count is increased to 11. When the count is 11, the test expression is evaluated to 0 (false) and the loop terminates.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. The syntax of a do...while loop is:
do
{
statement(s);
}
while(condition);

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

Example:
#include <stdio.h>
int main()
{
double number, sum = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);
return 0;
}
Output:
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

C language allows nested loops i.e. to use one loop inside another loop. The following section shows a few examples to illustrate the concept.

The syntax for a nested for loop statement is:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

The syntax for a nested while loop statement is:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement is:
do
{
statement(s);
do
{
statement(s);
}
while( condition );
}
while( condition );

You can put any type of loop inside any other type of loop. For example, a for loop can be inside a while loop or vice versa.

Example:
#include <stdio.h>
int main ()
{
int i, j;

for(i = 2; i<20; i++)
{
for(j = 2; j <= (i/j); j++)

if(!(i%j))
break; // if factor found, not prime

if(j > (i/j))
printf("%d ", i);
}
return 0;
}
Output:
2 3 5 7 11 13 17 19

A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.

Example:
#include <stdio.h>
int main ()
{
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for( ; ; ) construct to signify an infinite loop. You can terminate an infinite loop by pressing Ctrl + C keys. 

Popular posts from this blog

Screenshots from Windows 1.01

Windows 1.0 is a graphical personal computer operating environment developed by Microsoft, released on November 20, 1985, as the first version of the Microsoft Windows line. Version 1.01 , also released in 1985, was the first point-release after Windows 1.00.   Screenshots from Windows 1.01: ⇰ Desktop  First Run Empty Desktop Desktop With Applications ⇰  Office Applications Notepad Text Editor Calculator Calendar Clock Address Book ⇰  Multimedia Applications Media player, CD player, Volume level, and Sound: This GUI doesn’t have these features. ⇰  Networking Applications Terminal Phone Dialer: This GUI doesn’t have this feature. ⇰  Internet Applications Browser, and Mail: This GUI doesn’t have these features. ⇰  Accessibility Applications Keyboard Map:  This GUI doesn’t have this feature. ⇰  Settings Desktop themes,  Display,  S...

Introduction To Algorithms, 3rd Edition

Before there were computers, there were algorithms. But now that there are computers, there are even more algorithms, and algorithms lie at the heart of computing. This book provides a comprehensive introduction to the modern study of computer algorithms. It presents many algorithms and covers them in considerable depth, yet makes their design and analysis accessible to all levels of readers. In this book, the authors tried to keep explanations elementary without sacrificing depth of coverage or mathematical rigor. Each chapter presents an algorithm, a design technique, an application area, or a related topic. Algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming. The book contains 244 figures — many with multiple parts — illustrating how the algorithms work. It also includes careful analysis of the running times of all algorithms. In this third edition, the entire book once again updated including changes cove...

C++ Program To Implement Casino Number Guessing Game.

#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; void drawLine(int n, char symbol); void rules(); int main() { string playerName; int amount; int bettingAmount; int guess; int dice; char choice; srand(time(0)); drawLine(70,'_'); cout << "\n\n\n\t\tCASINO GAME\n\n\n\n"; drawLine(70,'_'); cout << "\n\nEnter Your Name : "; getline(cin, playerName); cout << "\n\nEnter Deposit Amount To Play Game : $"; cin >> amount;

C++ Program To Implement Student Report Card System.

#include<iostream> #include<fstream> #include<iomanip> #include <cstdlib> using namespace std; class student { int rollno; char name[50]; int p_marks, c_marks, m_marks, e_marks, cs_marks; double per; char grade; void calculate(); public: void getdata(); void showdata() const; void show_tabular() const; int retrollno() const; }; void student::calculate() { per=(p_marks+c_marks+m_marks+e_marks+cs_marks)/5.0; if(per>=60) grade='A'; else if(per>=50)  grade='B'; else if(per>=33) grade='C'; else grade='F'; }