This C program prompts the user to input an integer value for the side length of a square and prints a square of asterisks with that side length.
#include<stdio.h>
int main()
{
int x, y, side_length;
printf("Side Length: ");
scanf("%d",&side_length);
for(x = 0; x < side_length; x++)
{
for(y = 0; y < side_length; y++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Result:
Side Length: 10
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
Process returned 0 (0x0) execution time : 3.099 s
Press any key to continue.
Here is a line-by-line explanation:
#include<stdio.h>
This line includes the standard input-output header file.
int main()
{
int x, y, side_length;
printf("Side Length: ");
scanf("%d",&side_length);
This block of code declares three integer variables: x
, y
, and side_length
. It then prompts the user to enter the side length of the square, and the user's input is stored in the side_length
variable using the scanf
function.
for(x = 0; x < side_length; x++)
{
for(y = 0; y < side_length; y++)
{
printf("*");
}
printf("\n");
}
This block of code uses two nested for
loops to print a square of asterisks with side length side_length
.
The outer for
loop initializes the loop variable x
to 0 and increments it by 1 on each iteration as long as it is less than side_length
.
The inner for
loop initializes the loop variable y
to 0 and increments it by 1 on each iteration as long as it is less than side_length
. On each iteration of the inner loop, an asterisk is printed using the printf
function.
After the inner loop has finished iterating for a given value of x
, a newline character is printed using the printf
function to move the cursor to the next line.
return 0;
}
This line returns 0 to indicate successful execution of the program.
No comments:
Post a Comment