Loops in C Programming - ProgrammerTech
Language:

Search

Loops in C Programming

  • Share this:
Loops in C Programming

Concept Loops

Loops We use loops in programming to make it easier for us not to write the same code several times, if we want to use it for many times, we put it inside a loop and it will, in turn, repeat it according to our request and the terms of the code. There are three iterative loops in C language:

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

Each of these episodes we use in a specific work in the program, we will learn in the examples the importance of the episodes and their use. This lesson is one of the most important lessons in the C language, which is iterative loops. We will learn about each type of loop and how to build it.

 

For Loop in C Language

An iterative for loop is used to iterate the execution of a specified operation several times and takes the following form

For(initial-value ; condition ; increment)
Statements;
  • initial-value is the initial value.
  • condition The termination of repetition.
  • increment value increment in iterability.

Example 1

Write a program that prints programmer tech ten times using only the printf command without using loops.

#include<stdio.h>
main()
{
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
    printf("Programmmer tech \n");
}

When we run this code we will get its result which is printed ten times

Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech
Programmer tech

We notice that we have repeated the print command several times and it took a lot of trouble to write it and the size of the code, what if I want to print "1000" lines of this sentence, but there is a solution, which is to use the iterative for loop, which is writing a very small code.

Example 2

Write a program that prints the word programmer tech ten times using an iterative for loop in C.

#include<stdio.h>
main()
{
    Int a;
    For(a=0;a<10;a++)
    printf("Programmmer tech \n");
}

We set a scalar variable a and then enter an iterative loop and set the condition a equals 0 and if. A value less than 10 type the word Programmmer tech and in each cycle increase the counter 1 until it reaches 10 cycles. When the code is executed, the result will be the same as in the first example, but here briefly using a for loop.

Example 3

Write a program that repeats a set of texts, namely CS, DB, and Kaissar, using the for loop, and let the program print them ten times and stop.

#include<stdio.h>
main()
{
    int  a;
    for(a=0;a<10;a++)
    {
printf("cs \n");
printf("DB \n");
printf("Kaissar \n");
    }
}

Notice that we've opened grouping parentheses after the for loop because we've made multiple statements.

cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar
cs
DB
Kaissar

Now let's not use those parentheses after the previous episode

#include<stdio.h>
main()
{
    int  a;
    for(a=0;a<10;a++)
printf("cs \n");
printf("DB \n");
printf("Kaissar \n");
}

And executing this code will only print cs ten times for us as .

cs
cs
cs
cs
cs
cs
cs
cs
cs
cs
DB
Kaissar

Now the idea became clear to us, when using parentheses in the first code and not using them in the second code, the following happened:

  • If parentheses are used in iteration, all the statement in the loop will be "executing a set of sentences".
  • If parentheses are not used, the repetition of the first statement will be "execute the first sentence".

Example 4

Write a program that prints numbers from 0 to 9.

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

When you run this code, the result will be from 0 to 9 as follows

a= 0
a= 1
a= 2
a= 3
a= 4
a= 5
a= 6
a= 7
a= 8
a= 9

Example 5

Write a program that prints a set of numbers and increments by 2 difference between each number.

#include<stdio.h>
main()
{
    int a;
    for(a=0;a<10;a+=2)
printf("\n a= %d  \n" , a) ;
}

When we run the code, the result will be

a= 0
a= 2
a= 4
a= 6
a= 8

Example 6

Write a program that prints numbers in descending order, from 10 to 1.

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

The result of executing this code is:

a= 10
a= 9
a= 8
a= 7
a= 6
a= 5
a= 4
a= 3
a= 2
a= 1

Example 7

Write a program that prints numbers from 1 to 5 in ascending order and then prints numbers from 5 to 1 in descending order.

#include<stdio.h>
main()
{
    int a , b;
    for(a=0;a<5;a++)
    {
        printf("\n a= %d  \n" , a);
    }
    for(b=5;b>=0;b--)
    {
printf("\n b= %d  \n" , b);
    }
}

This code when you press run, the result will be from 1 to 5 and then from 5 to one as follows.

a= 1
a= 2
a= 3
a= 4
b= 5
b= 4
b= 3
b= 2
b= 1
b= 0

 

while Loop in C Language

The while loop in C language is used to repeat the execution of a certain sentence or group of sentences and the iteration stops when the number in the condition is executed. The general form of a while loop in C is.

while(condition)
Statements;

This means that as long as the condition is true, execute the sentence, and if the condition is false, stop repeating.

Example 8

I am writing a program that prints CS ten times using a while loop and stops the eleventh time.

#include<stdio.h>
main()
{
    int a=0;
    while(a<10(
    {
    printf(" \n CS ");
        a++;
    }
}

Where int a=0 is the initial value of a, when the code is run it will print it ten times as

CS
CS
CS
CS
CS
CS
CS
CS
CS
CS

Example 9

A program that repeats more than one sentence: saja, doha, ahmed.

#include<stdio.h>
main()
{
    int a=0;
    while(a<2)
    {
    printf(" \n Saja ");
    printf(" \n Doha ");
    printf(" \n Ahmed \n");
        a++;
    }
}

Because the initial value is zero and the loop will only iterate twice in the form

Saja
Doha
Ahmed
Saja
Doha
Ahmed

 

The difference between the for and while loops in C

  1. A for loop is integer dependent on a certain number and iteration ends with the number of iterations.
  2. The while loop is a loop that repeats the following sentences as long as the condition is true and ends with the condition being broken, i.e. until the condition is invalid.

 

Do while Loop in C Language

The do while loop in C is used to repeat the execution of a statement or group of sentences more than once based on a specific condition, as when using while. But the difference between them is that while tests if the condition is true or not, while do - while executes the next sentence first and then tests the condition. The general syntax of a do while loop in C is as follows.

Do{
Statements;}While(condition)

Example 10

Write a program called CS that prints numbers from 1 to 15 using a do - whlie loop.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i = 1;
    do{
        printf("\n%d",i);
        i++;
    }while(i<16);
}

When you run this code, it will print all numbers from 1 to 15.

Example 11

Write a program that prints the word Programmer Tech ten times using a do-while loop in C.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int x = 0;
    do{
        printf("\n Programmer Tech");
        x++;
    }while(x<10);
}

Programmer Tech will print ten times and stop.

Example 12

Write a program that asks the user to write a number of N and the program combines the number with the numbers less than it until it reaches 0 using a do-while loop using this C language.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int N;
    printf("enter the number: ");
    scanf("%d", &N);
    int s = 0; int i=1;
    do{
        s = s+ i;
        i++;
    }while(i<N+1);
    printf("sum: %d",s);
}

If the user enters the number 5, the result of the code will be in the form.

enter the number: 5
sum: 15

We note that when the user enters the number 5, the program gave us the number 15, which means that he combined the same number 5 with the number less than 4, then with the number 3, then the number 2, then 1 and the total was 15.

 

Loops Nested in C Language

Nested Loops This means using a for loop inside a second for loop or any second iterative loop.

And if you mastered dealing with nested loops, you will develop your analysis capabilities further. What do we expect to happen if we repeat a line of code three times and then three times?

for (int j = 0; j < 3 j++ )
{
    for (int j = 0; j < 3 j++ )
    {
        printf("* ");
    }
    printf("\n");
}

If we have a for clause, it is repeated for us to print the asterisk three times, and this statement is inside the for clause, which is repeated three times and prints a new line after the end of the inner for loop. First, the value of i starts with zero and passes to the inner for loop, and the value of the variable j will start with zero as well, and the inner for will start printing what is inside and iterating until it ends with the inner for loop. It prints a new line and then increments the value of i for the outer loop and starts spinning again and it will enter the inner loop. Again, you recognize j from scratch again, and you'll do the same thing until we have a square with three stars. And the length of three stars and this is the answer to what happens if we have a line of code that repeats a line of code three times.

Example 13

Make a program to print a square of stars. The user is asked to write the width and length of the square for this width.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char** argv)
{
    int h;
    printf("Enter the length of the square \n");
    scanf("%d", &h);
    for(int j = 0 ; j < h; j++)
    {
        for(int i = 0 ; i < h; i++)
        {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

At first we created a scalar variable int which is h for the length of this box and then by the scanf function which asks the user to enter a number. We asked the user through it to write the length of the square he wants by typing %d ie it asks for a number and h means the length variable and then we created a for loop in which j starts from zero and then we set that j be less than h i.e. the number the user enters and j++ One increment per cycle.

And we created a for second loop inside the first loop and set the variable i equal to 0 and when i is less than h it makes a cycle and increments it by one and prints on the screen * ie prints a number of stars from the number entered by the user in the form of a square and then Prints a new line.

When you run the program and enter the number 6 by the user will be.

Enter the length of the square
6
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *

When user number 3 is entered, the result will be:

Enter the length of the square
3
* * *
* * *
* * *

Example 14

Make a program that prints a rectangle of stars, asking the user to enter the length, then the width, and then print the rectangle.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char** argv)
{
    int h;
    int w;
    printf("Enter the length of the rectangle\n");
    scanf("%d", &h);
    printf("Enter the width of the rectangle \n");
    scanf("%d", &w);
    for(int j = 0 ; j < h; j++)
    {
        for(int i = 0 ; i < w; i++)
        {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

At the beginning of this program, we created two numerical variables, the variable h for the length of the rectangle and the variable w for the width of the rectangle. Then we ask the user via scanf to first enter the length of the rectangle h. And then he asks him to enter the width of the rectangle w and we enter an external iterative loop and it has a numerical variable j and its value is 0, then we put that j is less than the length of the rectangle h.

Then it increments by 1 on it and there was also a second small iterative loop inside the previous loop and the variable was i equal to 0. Then we set it to i to be less than the width w and it increments by 1 in a cycle, then it prints the stars with the numbers that The user entered it and typed a new line.

And when you run this code and the user enters the length 6 and the width 8, the result will be as follows.

Enter the length of the rectangle
6
Enter the width of the rectangle
8
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

Example 15

A program has been written that builds a triangle from the number 7 and goes down the number of a number until it reaches the number 1 and produces a right-angled triangle.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char** argv)
{
    for(int i = 7; i >= 1; i--)
    {
        for(int j = 0; j < i; j++)
            printf("%d", i);
        printf("\n");
    }
    return 0;
}

We created an external for loop with a scalar variable i and its value 7, which is the starting point. Then we told him that i is less than or equal to 1 and then we put i -- which is a decrease of one. And then we created a second loop inside it and the variable in it is j and its value is 0, then we set that j be less than i and it increments by one each cycle. And i represents the starting point which is 7 and then we asked him to print the value of i in each cycle and go down a new line after that.

And when you run this program, the result will be as follows.

7 7 7 7 7 7 7
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

If you master Loops Nested, you will develop your analysis capabilities even further.


Saja Alsadig

Saja Alsadig

من السودان مبرمجة مواقع ويب و تطبيقات أندرويد اتقن لغات "html, css, php, js" بالإضافة للتعامل مع اندرويد ستوديو و بناء التطبيقات, مهتمة بمجال التقنية منذ الصغر و كان لدي شقف كبير للدخول بالجامعه بقسم البرمجة و دخلته في عام 2013 و تعلمت كل شيئ ضمن الجامعة و خارجها من التعليم الذاتي و اتمنى أن أكون عند حسن ظن الجميع و إيصال الأمانة لكم, اعمل حاليا في إدارة موقع جامعة السودان.