C exercises and solutions: loops in C (more)


Loops in C exercises (con)

3. Write a C program that will print the patters as shown below:


*


***
*****
*******
*********
*********
*******
*****
***
*

Solution:

#include <stdio.h>
#include <conio.h>
 
 
int main()
{
 int i;
 int j;;
 
 for(i=1;i<=9;i=i+2){
  for(j=1;j<=i;++j)
    printf("*");         
               
    printf("\n");
      
}
 for(i=9;i>=1;i=i-2){
  for(j=i;j>=1;--j)
    printf("*");         
             
    printf("\n");
 
      
}
  
   printf("\n");
   system("PAUSE");
   return EXIT_SUCCESS;
}

Write a C program that will ask the user to input n positive numbers. The program will terminate if one of those number is not positive.

Solution
#include <stdio.h>
#include <conio.h>
 
int main()
{
 int x;
 while(x>0){
            printf("Enter a number:");            
           
scanf("&d",x);
            printf("\n");
            }
  
 
   system("PAUSE");
   return EXIT_SUCCESS;
}


Comments

mohd khaja raziuddin comment

 mohd khaja raziuddin

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

int main()
{int i,j=1,k=1,l=1,m;
printf("welcome to the world of loop example #3\n");
for(i=0;i<5;i++,k++)
{
for(j=1;j<=i+k;j++){
printf("*");

}
printf("\n");
}
int temp=j;
k=k-1;
i=i-1;
// printf("%d %d %d %d\n",temp,i,j,k);
for(m=0;m<5;i--,k--,m++)
{
for(j=1;j<=k+i;j++){
printf("*");

}
printf("\n");
}
return 0;
}
output:
welcome to the world of loop example #3
*
***
*****
*******
*********
*********
*******
*****
***
*


2017-02-14
Nikola comment

 Nikola

Here is the more complicated way :D

int main()
{


int i;
int j;
int k;

for(i=6;i<=10;i++){
printf("*");
for(k=i;k>6;k--){
printf("**");
}
printf("\n");
}

for(i=10;i>5;i--){
printf("*");
for(j=i;j>6;j--){
printf("**");
}
printf("\n");
}




return 0;
}


2016-06-20
CFx comment

 CFx

scanf("&d",x); ?
The format specifier is not true for above scanf condition and is not true for any scanf.

Correction: scanf("%d", &x);


2015-05-05



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.