Learning LOOPS in C

What is a LOOP ?
A loop is simply a statement which can execute a set of defined statements repetitively. You can write any valid C statement within a loop and you can also set how many times to execute that certain statement.

There are three parts in a loop

1. Initialization ( loop starting form number mostly 1 or 0 )
2. Condition ( to stop the loop at certain point )
3. Increment ( adding a certain number in variable to reach the stopping condition )

Three types of loops in C are
1. For loop
2. While loop
3. Do While loop

Today we will discuss for loop.
Printing a table of any number using FOR LOOP:

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files is just for using a function which can pause the screen until the user hits any key.
  1. int main(){
  2. int number = 1;
  3. int count = 1; //to start the number multiplying by 1
  4. int ans = 0;
  1. printf(“Enter a number to print the table : “);
  2. scanf(“%d”,&number);

Now we are taking inputs from the user, The user will enter the number and then we will run a loop to find the table of that number.

  1. for(count =1; count<=20;count++){
  2. ans = number * count;
  3. printf(” %d * %d = % d\n,number,count,ans);
  4. }//end for
  5. }//end main

In the for loop notice that there are two semi colon’s which divides the bracket into three parts. The condition before first semicolon is the initialization. The condition before second semi colon is condition and the condition after semi colon is the increment.
We will simply multiply the number (given by user) with the for loop variable count which will start from 1 and go till 20. Incrementing every time the for loop runs. Then we end the program.
Execute > compile
then Execute > run

This entry was posted in C and tagged . Bookmark the permalink.

Leave a comment