0% found this document useful (0 votes)
5 views2 pages

C++ Basics: Loops and Sums

The document contains C++ code examples demonstrating basic programming concepts. It includes a program to print numbers from 1 to 5, a program to display 'Hello World!' five times, and a program to calculate the sum of the first n natural numbers. Each example is accompanied by comments explaining the purpose of the code.

Uploaded by

kkchandra34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

C++ Basics: Loops and Sums

The document contains C++ code examples demonstrating basic programming concepts. It includes a program to print numbers from 1 to 5, a program to display 'Hello World!' five times, and a program to calculate the sum of the first n natural numbers. Each example is accompanied by comments explaining the purpose of the code.

Uploaded by

kkchandra34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Example 1: Printing Numbers From 1 to 5

#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; ++i) {

cout << i << " ";

return 0;

Display a text 5 times

// C++ Program to display a text 5 times

#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; ++i) {

cout << "Hello World! " << endl;

return 0;

}
Find the sum of first n Natural Numbers

// C++ program to find the sum of first n natural numbers

// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>

using namespace std;

int main() {

int num, sum;

sum = 0;

cout << "Enter a positive integer: ";

cin >> num;

for (int i = 1; i <= num; ++i) {

sum += i;

cout << "Sum = " << sum << endl;

return 0;

You might also like