Write a program to input an integer, n, between 1 and 9, and print a line of output consisting of digits from 1 to n, followed by descending digits from (n-1) to 1. For example, if n = 6, then the output will be 12345654321

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {
    int n;
    printf("Enter n (1 - 9): ");
    scanf("%d", &n);
    for ( int i = 1; i <= n;  i++)
        printf("%d", i);
    for ( int i = n - 1; i > 0; i--)
        printf("%d", i);

    return 0;

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

Enter n (1 - 9): 6

Brief Explanation

  • Program request the user to enter a value between 1-9
  • scanf function reads the value and assign it to the variable n
  • The first for loop iterates from 1 to n while the second begins from n-1 and decreases by 1 until it reaches a value less than or equal to zero.
  • In each iterations of the for loops, the value of i is printed to the stdout.

Add comment

Security code