medium
0 views

1 to N – Mixed Pattern Printing

Print numbers from 1 to N in alternating pattern: 1, N, 2, N-1, 3, N-2, ...

Understand the Problem

Problem Statement

The program must accept a number N and print the numbers from 1 to N with the first number being 1, second number being N, third being 2 and the fourth being N-1 and so on.

Constraints

  • 1 <= N <= 500
  • N must be a positive integer
  • Output must be space-separated numbers
  • Pattern alternates between low and high values

Examples

Example 1
Input
9
Output
1 9 2 8 3 7 4 6 5
Explanation

Starting with 1, then 9, then 2, then 8, then 3, then 7, then 4, then 6, then 5. The pattern alternates between low values (1,2,3,4,5) and high values (9,8,7,6).

Example 2
Input
6
Output
1 6 2 5 3 4
Explanation

Starting with 1, then 6, then 2, then 5, then 3, then 4. The pattern alternates between low values (1,2,3) and high values (6,5,4).

Solution

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    
    int low = 1;
    int high = n;
    
    while (low <= high) {
        printf("%d ", low);
        if (low < high) {
            printf("%d ", high);
        }
        low++;
        high--;
    }
    
    return 0;
}
Time:O(N)
Space:O(1)
Approach:

C Solution Explanation:

  1. Read integer N using scanf
  2. Initialize two pointers: low starting at 1, high starting at N
  3. Use while loop that continues while low <= high
  4. Print the low value first
  5. Check if low < high (to avoid printing the middle element twice in odd-length sequences)
  6. If condition is true, print the high value
  7. Increment low and decrement high to move towards center
  8. Continue until all numbers are printed

Visual Explanation

Loading diagram...