Write a complete C program that does the following.
1. It asks the user to enter an integer that is at least 3.
2. The program reads a value x entered by the user. If the value is not legal, the program repeatedly makes the user type in another value until a legal value of x has been entered.
3. The program prints a picture with x columns. For example, if the user enters 3 for x the program should print the following picture.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {
    int x;
    printf("Enter an integer that is at least 3: ");
    scanf("%d", &x);
    while (x<3) {
        printf("Must be at least 3. Try again: ");
        scanf("%d", &x);
    }
    int rows = 2*x;
    int columns = 2*x;
    for (int r = 0; r <= rows; r++) {
        for (int c = 0; c <= columns; c++) {
            if ( (r + c == 2*x) || (r - c == 2*x) || r == c )
                printf("x");
            else
                printf(" ");
        }
        printf("\n");
    }

    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Enter an integer that is at least 3: 3

Brief Explanation

  • The 'while' loop ensures that the user enters a number that is at least 3.
  • Notice ‘for’ loop initial declarations in the two for loops. In c99 and above, the type of a variable can be specified in the loop.
  • The variables r and c are only valid within the for loops.
  • To compile this code, you need to use option -std=c99 or -std=gnu99 or -std=c11  

Add comment


Security code
Refresh