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

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 Check Whether A Number Is Palindrome Or Not.

This program takes an integer from user and the integer is reversed. If the reversed integer is equal to the integer entered by user then that number is a palindrome. If not that number is not a palindrome.   #include <stdio.h> int main()  { int num, temp, remainder, reverse = 0; printf("Enter an integer: "); scanf("%d", &num); /*  original number is stored at temp */ temp = num; while (num > 0)  { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10;   }

The Basics Of C Programming - Part 3.

There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you can use: scanf("%d",&a); When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press Enter or Return, to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! The final missing piece in the jigsaw is using the printf function, the one we use to print the value currently being stored in a variable. To display the value stored in the variable a you can use: printf("The value stored in a is %d",a); Note: the scanf function does not prompt for an input. You should ge...

C++ Program To Implement Bank Management System.

#include<iostream> #include<fstream> #include<cctype> #include<iomanip> #include <cstdlib> using namespace std; class account { int acno; char name[50]; int deposit; char type; public: void create_account(); //function to get data from user void show_account() const; //function to show data on screen void modify(); //function to add new data void dep(int); //function to accept amount and add to balance amount void draw(int); //function to accept amount and subtract from balance amount void report() const; //function to show data in tabular format int retacno() const; //function to return account number int retdeposit() const; //function to return balance amount char rettype() const;  //function to return type of account }; void account::create_account() { cout<<"\nEnter The Account No. : "; cin>>acno; cout<<"\n\nEnter The Name Of The Account Holder : "; cin.ig...