Wednesday 3 June 2015

Print Increment Numbers On The Same Line But With Spaces Between Them In C++

Printing increment numbers in C++ can be helpful when you want to display a list of numbers to a user, such as for a calendar. Create increment numbers by adding 1 to the previous number and repeating the step. Decide what range of numbers to print and then use a "for" loop combined with the "printf" or "cout" method to print the numbers.


Instructions


1. Open the C++ source file in an editor such as Microsoft Visual Studio Express.


2. Include the "stdio" header file to access the "printf" function by adding the following code at the top of your file:


#include


Alternatively, include the "iostream" header to access the "cout" output stream by adding the code:


#include


using namespace std;


3. Declare 2 integer variables that will store the first and last increment numbers you want to print by adding the following code in your function:


int first = 0;


int last = 5;


4. Use a "for" loop to repeatedly print a number with "printf," increasing it by 1 each iteration, by adding the code:


for (int n=first; n<=last; n++) {


printf("%d ", n);


}


The "%d" specifier indicates a signed decimal integer. Using the example, this will display "0 1 2 3 4 5 ."


Alternatively, use "cout" from the "iostream" to print the numbers with the code:


for (int n=first; n<=last; n++) {


cout << n << " ";


}


5. Save the C++ file, compile and run the program to view the increment numbers.

Tags: increment numbers, adding code, adding following, adding following code, code first