CSE 115 Lab on nested loop (part 1) – Ara2
Write C programs to print the following patterns:
1. Square pattern for N lines. E.g. for N=4: 2. Hollow square pattern for N lines. E.g. for N=4:
**** ****
**** * *
**** * *
**** ****
#include <stdio.h> #include <stdio.h>
void main() void main()
{ {
int i, j, N; int i, j, N;
printf("No. of rows:"); printf("No. of rows:");
scanf("%d", &N); scanf("%d", &N);
//In each of N rows/lines for(i=1; i<=N; i++)
for(i=1; i<=N; i++) {
{ for(j=1; j<=N; j++){
//print N stars //Print star in first and last row as
for(j=1; j<=N; j++) well as in first and last column
{ if(i==1||i==N||j==1||j==N)
printf("*"); printf("*");
}//j else
printf(" ");
//Go to next line }//j
printf("\n"); printf("\n");
}//i }//i
} }
Try yourself 1a: Write a C program to print a rectangle pattern of size m*n. For e.g. for m=10, n=5 print:
**********
**********
**********
**********
**********
Try yourself 2a: Write a C program to print a hollow rectangle pattern of size m*n. For e.g. for m=10, n=5 print:
**********
* *
* *
* *
**********
Try yourself 2b: Write a C program to print a hollow right angled triangle of height n. For e.g. for n=7 print:
*
**
* *
* *
* *
* *
*******
3. Rhombus pattern for N lines. E.g. for N=4:
****
****
****
****
#include <stdio.h>
void main()
{
int i, j, N;
printf("Enter rows: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
//Print leading spaces
for(j=1; j<=N - i; j++)
printf(" ");
//Print stars after spaces
for(j=1; j<=N; j++)
printf("*");
printf("\n");
}
}
Exercise Problems:
1. Write a C program to print hollow rhombus star pattern of N lines. E.g. for N=5 print:
*****
* *
* *
* *
*****
Assignment Problems:
1. Write a C program to print a hollow parallelogram pattern of size m*n. E.g for m=10, n=5 print:
**********
* *
* *
* *
**********
2. Write a C program to print a right justified hollow right angled triangle of height n. For e.g. for n=7 print:
*
**
* *
* *
* *
* *
*******