Wednesday February 7th, 2018

C – Loops 2

By Ebubekir Sezer

In previous essay , I used if – else and while loops when make a program. In this essay , I will use do-while and for loops. Do – while loop is different type of while loops. You can see the previous essay in here.

Firstly , I will make a program , using with the do – while loop . In this program, Program will take a number from the user with a condition. Condition is number must be smaller than 50 (I will use if-else for condition) . Then program will add 5 to number until the number equal to 50.

#include<stdio.h>
int main()
{
int number ;
printf("Enter a number (Number should be smaller than 50):");
scanf("%d",&number);
if(number<50){
do
{
number = number + 5;
printf("%d\n",number);
}
while(number<50);
}
else 
{
printf("You entered bigger than 50. Restart again.");
}
return 0;
}

The differences between the while and do-while is, In do-while first run and control the situation but in while first control the situation then run the code.

Screen Outpu;

Enter a number (Number should be smaller than 50): 15
20
25
30
35
40
45
50

Now, I will make program , using with the for loop. Program will take 2 numbers from the user and compare with each other , then program will add 1 to the small number and when they are equal , program will be finish.

#include<stdio.h>
int main()
{
int number1,number2;
printf("Enter the first number:");
scanf("%d",&number1);
printf("Enter the second number:");
scanf("%d",&number2);
if(number1<number2)
{
for(number1 ; number1 <= number2 ; number1++)
{
printf("%d\n",number1);
}
}
else
{
for(number2 ; number2 <= number1 ; number2++)
{
printf("%d\n",number2);
}	
}
return 0;
}

In for loops , program look the condition in for , if the condition right , program will run.

Screen Output;

Enter the first number: 12
Enter the second number: 20
12
13
14
15
16
17
18
19
20

I will make fibonacci loop , using with the for loop. fibonacci loop is ,collecting the number from the previous one. Code syntax is ;

#include<stdio.h>
int main()
{
int number1 = 1, number2 = 1 , x;
int temporary ;
printf("%d\n%d\n",number1,number2);
// x is the variable for the for loop 
for(x=0 ;x < 10 ; x++)
{
temporary = number2;
number2 += number1;
number1 = temporary;
printf("%d\n",number2);
}
return 0;
}

Screen Output ;

1
1
2
3
5
8
13
21
34
55
89
144