194k views
0 votes
Write in C++

Output Numbers from 1 to N

Write a program that prints out every other number between 1 and N where N is entered by the user. The numbers must be separated by a comma and a space. The last number must not have a comma following it. The program is repeated until a number smaller than 1 is entered at which point the program outputs "Goodbye!"

Example:
Enter N: 7
1, 3, 5, 7
Enter N: 10
1, 3, 5, 7, 9
Enter N: -1

1 Answer

6 votes

Final answer:

To print every other number between 1 and N in C++, use a for loop that increments by 2 in each iteration and prints the current number. Add commas and spaces after each number, except for the last number. Finally, handle the case where N is smaller than or equal to 0 by outputting the message "Goodbye!".

Step-by-step explanation:

To print every other number between 1 and N in C++, you can use a for loop. First, prompt the user to enter the value of N. Then, use the for loop to iterate from 1 to N, incrementing by 2 in each iteration. Inside the loop, print the current number. Finally, add a comma and a space after each number, except for the last number where you should not add the comma and space. Here's an example:

#include <iostream>
using namespace std;

int main() {
int N;

do {
cout << "Enter N: ";
cin >> N;

if (N <= 0) {
cout << "Goodbye!" << endl;
break;
}

for (int i = 1; i <= N; i += 2) {
if (i != 1) {
cout << ", ";
}
cout << i;
}
cout << endl;
} while (true);

return 0;
}

User Peter Severin
by
9.8k points