easy
1 views

Function Print from N+1 to 2N – CTS PATTERN

Fix the logical error in a function that prints integers from N+1 to 2N inclusive

Understand the Problem

Problem Statement

Function Print from N+1 to 2N: You are required to fix all logical errors in the given code. You can click on run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.

Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.

The function printNto2N(int N) accepts an integer N as the input. The function prints from N+1 to 2N.

The function looks fine but gives a compilation error.

Your task is to fix the program so that it passes all test cases.

Constraints

  • N must be a positive integer (N ≥ 1)
  • The output should contain integers from N+1 to 2N, inclusive
  • Each integer should be followed by a space
  • The function should not return any value (void)

Examples

Example 1
Input
3
Output
4 5 6 
Explanation

For N=3, we print numbers from 4 to 6 (inclusive). N+1 = 4 and 2N = 6, so we print 4, 5, 6.

Example 2
Input
5
Output
6 7 8 9 10 
Explanation

For N=5, we print numbers from 6 to 10 (inclusive). N+1 = 6 and 2N = 10, so we print 6, 7, 8, 9, 10.

Example 3
Input
1
Output
2 
Explanation

For N=1, we print numbers from 2 to 2 (inclusive). N+1 = 2 and 2N = 2, so we print just 2.

Solution

#include <stdio.h>

void printNto2N(int N){
    int ctr = N + 1;
    while(ctr <= 2 * N){
        printf("%d ", ctr);
        ctr++;
    }
    printf("\n");
}

// Test function to demonstrate usage
int main() {
    printNto2N(3);
    printNto2N(5);
    printNto2N(1);
    return 0;
}
Time:O(N) - The loop runs exactly N times (from N+1 to 2N)
Space:O(1) - Only uses a constant amount of extra space (one integer variable)
Approach:

C Solution Explanation:

  • #include <stdio.h> - Include standard I/O library for printf
  • void printNto2N(int N) - Function takes integer N as parameter
  • int ctr = N + 1 - Initialize counter to N+1 (starting point)
  • while(ctr <= 2 * N) - Loop while counter is less than or equal to 2N
  • printf("%d ", ctr) - Print current counter value followed by space
  • ctr++ - Increment counter by 1
  • printf("\n") - Print newline after loop completes

The key fix was replacing the HTML entity &lt; with the actual less-than operator <.

Visual Explanation

Loading diagram...