You are on page 1of 5

C for Loop Exercises

Ex1 :

Write a program in C to print "Hello World" n times where the value of n will be provided by the user
and condition is 1 <= n <= 10

Ex2 :

Write a C program to print all odd numbers between 1 to n.

Write a C program to print all even numbers between 1 to n.

Ex3 :

 Write a program in C to display the pattern like right angle triangle using the starts.
The pattern like :
*
**
***
****
*****
******
Ex4 :
Write a program in C to display the pattern like right angle triangle with a number

The pattern like :

1
12
123
1234

Ex 5

Write a program in C to display the pattern like right angle triangle with a number

The pattern like :

Ex6

Ex7 :

 Write a program in C to display the pattern like right angle triangle using the starts.
The pattern like :
*
**
* *
* *
* *
* *
*******

Solution
EX1

#include <stdio.h>
int main(void)
{
//variable
int n, i;
//user input
printf("Enter value of n between 1 to 10: ");
scanf("%d", &n);

//check condition
if (n >= 1 && n <= 10) {
//print Hello World
for (i = 1; i <= n; i++) {
printf("Hello World\n");
}
}
else {
printf("Error: Value of n must be between 1 to 10.\n");
}
printf("End of code\n");
return 0;
} startsa

Ex 2
#include <stdio.h>

int main()
{
int i, num, isPrime;
printf("Enter any number to check prime: ");
scanf("%d", &num);

for(i=0; i<=num; i++)


{
/* Check divisibility of num */
if(i%2!=0)
{
printf( "the number is %d\n",i);
}
}
return 0;
}

Ex3 :
#include <stdio.h>
void main()
{
int i,j,rows;
printf("Input number of rows : ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
printf("*");
printf("\n");
}
}

EX4 :
#include <stdio.h>
void main()
{
int i,j,rows;
printf("Input number of rows : ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
}

Ex5 :
for(i=1 ; i<=5 ;i++){

for(j=5 ; j>=i ;j--){


printf("%d",j);
}

printf("\n");
}

EX7 :

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop
*/

int main() {

int i ,j;

for(i=1 ; i<=7 ; i++){


for(j=1 ; j<=i ; j++){

if(j==1 || i==7 || j==i){

printf("*");
}else{
printf(" ");
}

}
printf("\n");

return 0;
}

You might also like