Tech Blog   »   Home   »   Coders Forum   »   Computer Directory   »   Math Calculators   »   RSS:Directory|Forum 

C++ Source Code Examples

Click on Loops tab on far left for more for loops

C++ Source Code: Count even numbers using a: for loop C++

// - Count even numbers using a for loop
#include <iostream>
using namespace std;
int main()
{
	for (int count = 0; count <= 26; count += 2)
	{
		cout << count << ", ";
	}
	cout << endl;
	return 0;
}

/*==================[output]======================
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
Press any key to continue . . .
=================================================*/
// end of program






C++ Source Code: Count backwards even numbers using a for loop

// - Count backwards showing even numbers
#include <iostream>
using namespace std;
int main()
{
	for (int count = 26; count > -1; count -= 2)
	{
		cout << count << ", ";
	}
	cout << endl;
	return 0;
}

/*==================[output]======================
26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0,
Press any key to continue . . .
=================================================*/
// end of program






C++ Source Code: The sum of all numbers using a for loop

// Add all numbers up to the amount you enter.
#include <iostream>
using namespace std;
int main()
{
	int number = 0;  // Variable for user to enter a number.
	int sum = 0;    // To hold the running sum during all loop iterations.

	cout << "Enter a number: ";
	cin >> number;

	// Loop keeps adding until it reaches the number entered.
	for (int index = 0; index <= number; index++)
	{
		sum += index; // Each iteration Adds to the variable sum.
	}

	// cout statement is put after the loop.
	cout << "\nThe sum of all numbers from 0 to " << number
			<< " equals: " << sum << "\n\n";

	return 0;
}

/*===========================[output]===================================
Enter a number: 6

The sum of all numbers from 0 to 6 equals: 21

Press any key to continue . . .
========================================================================*/
// end of program






C++ Links


Code Examples:
Variables
Strings
Arrays

Functions:
Return Values
Pass by Value
Pass by Reference

Loops:
While loop
Do-while
For loops

Arrays:
Basic Array






More C++ source code

Forum Area maSpinner

The forum contains more programming examples, registration is free!




Validated with no errors:

Valid XHTML 1.0 Transitional     Valid CSS!


Site Map