EXP3 Writeup-2
EXP3 Writeup-2
Date of Performance:
Date of Submission:
THEORY:
for loop:
The for loop is an entry-controlled loop that executes the statements till the given condition.
All the elements (initialization, test condition, and increment) are placed together to form
a for loop inside the parenthesis with the for keyword.
Nested-for loop:
It is also possible to place a loop inside another loop. This is called a nested loop. The "inner
loop" will be executed one time for each iteration of the "outer loop". This structure is
particularly useful when working with multidimensional arrays, intricate patterns, or
scenarios that require repeated calculations. Code readability and maintainability are
improved by nested loops in C.
Syntax:
SOURCE CODE:
3a. Write a program to print following pattern:
1
2 2
3 3 3
Algorithm
1. Start the program.
2. Initialize two integer variables i and j.
3. Set a loop to iterate i from 1 to 3 (inclusive):
o a. For each value of i:
▪ i. Set another loop to iterate j from 1 to i (inclusive):
1. Print the value of i.
2. Print a space character.
o b. After exiting the inner loop, print a newline character to move to the
next line.
End the program
Code:
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=3;i++)
{
for(j=1;j<=i; j++)
{
printf("%d",i);
printf(" "); // for single space “/t” for 3 spaces
}
printf("\n");
}
return 0;
}
Output:
Code:
#include <stdio.h>
int main() {
int i, space, rows, k = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
}
while (k != 2 * i - 1) {
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
Output:
3c. Input a string from the user and print in the following pattern
D M C E
D M C
D M
D
Algorithm:
1. Start the program.
2. Declare a character array (string) to hold the user input.
3. Prompt the user to enter a string.
4. Read the input string and store it in the character array.
5. Determine the length of the string and store it in a variable n.
6. Set a loop to iterate i from 0 to n - 1 (inclusive):
o a. For each value of i, set a nested loop to iterate j from 0 to n - i - 1
(inclusive):
▪ i. Print the character at position j of the string followed by a space.
o b. Print a newline character to move to the next line after each iteration of i.
7. End the program.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, j;
printf("Enter a string: ");
scanf("%s",str);
int len = strlen(str);
for(i = len; i > 0; i--)
{ for(j = 0; j < i; j++)
{
printf("%c ", str[j]);
}
printf("\n");
}
return 0;
}
Output:
CONCLUSION: