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...

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;

The C Programming Language, 2nd Edition*

This book is meant to help the reader learn how to program in C. It is the definitive reference guide, now in a second edition. Although the first edition was written in 1978, it continues to be a worldwide best-seller. This second edition brings the classic original up to date to include the ANSI standard. For evolution of the planet earth and our modern understanding of biology, there was Darwin's Origin of the Species. For mathematics, there was Newton's PhilosophiƦ Naturalis Principia Mathematica. Well, for the internet, for Facebook, for LinkedIn, Twitter, Instgram, Snapchat, WhatsApp, Pornhub and even the odious website for Justin Bieber would never have existed without Kernigan and Ritchie (more affectionately known as K&R)'s classic, The C Programming Language. What language was TCP/IP written in? C. What language inspired both C++ and Java (and the abominable C#)? C. What language are most libraries on most operating systems written in if not assembler? C. ...

Java Tutorial For Beginners: Part 2.

Problem: Java Program To Solve Tower Of Hanoi Problem Using Stacks import java.util.*; public class TowerOfHanoiUsingStacks { public static int N; @SuppressWarnings("unchecked") public static Stack<Integer>[] tower = new Stack[4]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); tower[1] = new Stack<Integer>(); tower[2] = new Stack<Integer>(); tower[3] = new Stack<Integer>(); System.out.print("Enter The Number Of Disks: "); int num = scan.nextInt(); N = num; toh(num); scan.close(); } /* Function to push disks into stack */ public static void toh(int n) { for (int d = n; d > 0; d--) tower[1].push(d); display(); move(n, 1, 2, 3); }

How Are The Web Pages Written?

Web pages are written in HTML, the web programming language that tells web browsers how to structure and present content on a web page. In other words, HTML provides the basic building blocks for the web. And for a long time, those building blocks were pretty simple and static: lines of text, links, and images. Today, we expect to be able to do things like play online chess or seamlessly scroll around a map of our neighborhood, without waiting for the entire page to reload for every chess move or every map scroll. The idea of such dynamic web pages began with the invention of the scripting language JavaScript. JavaScript support in major web browsers meant that web pages could incorporate more meaningful real-time interactions. For example, if you have filled out an online form and hit the “submit” button, the web page can use JavaScript to check your entries in real-time and alert you almost instantly if you had filled out the form incorrectly. But the dynamic web as we ...