Loop Statements in C++ | Display Series of Numbers

The following code provides a solution for printing a sequence of values using a for loop in C++. This code demonstrates a simple yet effective way to print a series of numbers that follow a specific pattern, in this case, the sequence of odd numbers from 1 to 13.

Which Compiler is best?

  • For Laptop, Offline or PC Devices use Visual Studio Code or CFree , Dev C++.
  • For Mobile Devices you can use online Compilers such as w3shools.

Code Elements:

<iostream> Library:

The code begins by including the iostream library, which provides functions for input and output operations..

cout command:

We will use cout commands to print our output on the screen.

Loop Statement:

he main function is then defined and inside the main function, we have a while loop. The while loop is used to iterate over a range of values, in this case, the range of odd numbers from 1 to 13.

Compound Operator:

Compound Operators like +=, *= is used to add and multiply values directly into the variable;

Final Coding:

Now we will write the final code :

1- Library

We are using iostream library and int main body.

#include <iostream>
using namespace std;
int main () {
}

2- Declaring Variables

int _x = 1;

3- Using While Loop

The loop initializes a variable i to 1 and sets the termination condition to i <= 13. This means that the loop will run until i becomes greater than 13. The increment expression i += 2 updates the value of i by adding 2 in each iteration, thus making it an odd number.

	while(_x<=13)
	{
		cout<<_x <<endl;
		_x+=2;
	}

Inside the loop, the cout function is used to print the value of i on the screen. The cout function writes the output to the standard output stream, which is usually the screen. The << operator is used to concatenate the value of i with the space character to separate each number in the sequence.

Finally, the endl function is used to insert a newline character, which causes the program to print each number on a separate line. The return 0 statement at the end of the main function is used to indicate that the program has completed successfully.

In conclusion, this code provides a simple and efficient way to print a sequence of values using a for loop in C++. The for loop is a powerful construct that can be used to iterate over a range of values, and in this case, it makes it easy to print the desired sequence of odd numbers.

Leave a Reply

Featured Posts

FSc 2nd year Physics Chapter 12 Notes – LQs, SQs, Numericals, MCQs

READ
canva pro for free

What is Canva ? How to get Canva Pro & its features

READ

Average Atomic Mass: Determination, Examples

READ

FSc 2nd year Chemistry Chapter 12 Notes – Eiman.pk

READ

FSc 2nd year Computer Science Chapter 14 Notes

READ

FSc 2nd year Physics Chapter 19 Notes – LQs, SQs, Numericals, MCQs

READ