0% found this document useful (0 votes)
2 views53 pages

Loops Example

The document provides an overview of loops in C++, including examples of for loops and switch statements. It explains how to use loops for repetitive tasks, such as calculating factorials and creating a simple calculator. Additionally, it covers array manipulation, string handling, and the use of input/output functions in C++.

Uploaded by

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

Loops Example

The document provides an overview of loops in C++, including examples of for loops and switch statements. It explains how to use loops for repetitive tasks, such as calculating factorials and creating a simple calculator. Additionally, it covers array manipulation, string handling, and the use of input/output functions in C++.

Uploaded by

akalkidan760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

loops are used to execute a block of code repeated.

Loops are used to execute repetitive code.

For Loop in C++ Example 1


#include <iostream>
using namespace std;
int main() {
for (int x=0; x<5; x=x+1) {
cout << "X is: " << x << endl;
}
return 0;
}
Output:

Here is a screenshot of the code:

1
Code Explanation:

1. Including the iostream header file in our code. It will allow us to read
from and write to the console /support.
2. Including the std namespace so as to use its classes
and functions without calling it.
3. Calling the main() function inside which the logic of the program
should be added. The { marks start of body of the main() function.
4. Creating a for loop. The initialization creates an integer variable x and
assigns it a value of 0. The condition states that the value of x must be
less than 5. The increment increases the value of x by 1 after every
iteration. The { marks the beginning of the body of the for loop.
5. To print the value of variable x alongside other text on the console. The
endl is a C++ keyword meaning end line. The cursor will print in the
next line in the next iteration.
6. End of the loop body.
7. The main() function should return an value if the program runs fine.
8. End of the body of the main() function.

For Loop in C++ Example 2


#include <iostream>
using namespace std;
int main()
{
int x, num, factorial = 1;
cout << "Type positive number: ";
cin >> num;

2
for (x = 1; x <= num; ++x) {
factorial *= x; // factorial = factorial * x;
}
cout << "Factorial of " << num << " = " << factorial;
return 0;
}
Output:

Here is a screenshot of the code:

Code Explanation:

1. Including the iostream header file in our code. It will allow us to read from and write to
the console.
2. Including the std namespace so as to use its classes and functions without calling it.
3. Calling the main() function inside which the logic of the program should be added.
4. The { marks start of body of the main() function.

3
5. Declaring integer variables, x, num, and factorial. The variable factorial has been
assigned a value of 1.
6. Printing some text on the console.
7. Prompting user to enter a value for variable num.
8. Creating a for loop. The initialization creates an integer variable x and assigns it a value
of 1. The condition states that the value of x must be less than or equal to value of
variable num. The increment increases the value of x by 1 after every iteration. The
{ marks the beginning of the body of the for loop.
9. Calculating the value of factorial using the formula factorial = factorial * x.
10. End of the loop body.
11. To print the value of variables num and factorial alongside other text on the console.
12. The main() function should return an value if the program runs fine.
13. End of the body of the main() function.

4
Example: Create a Calculator using the switch Statement
// Program to build a simple calculator using switch Statement
#include <iostream>
usingnamespacestd;

intmain() {
char oper;
float num1, num2;
cout<<"Enter an operator (+, -, *, /): ";
cin>> oper;
cout<<"Enter two numbers: "<<endl;
cin>> num1 >> num2;

switch (oper) {
case'+':
cout<< num1 <<" + "<< num2 <<" = "<< num1 + num2;
break;
case'-':
cout<< num1 <<" - "<< num2 <<" = "<< num1 - num2;
break;
case'*':
cout<< num1 <<" * "<< num2 <<" = "<< num1 * num2;
break;
case'/':
cout<< num1 <<" / "<< num2 <<" = "<< num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout<<"Error! The operator is not correct";
break;
}

return0;
}

5
Output 1

Enter an operator (+, -, *, /): +


Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *


Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

6
Enter an operator (+, -, *, /): ?
Enter two numbers:
2.3
4.5
Error! The operator is not correct.

How This Program Works


1. We first prompt the user to enter the desired operator. This input is then
stored in the char variable named oper .

2. We then prompt the user to enter two numbers, which are stored in the float
variables num1 and num2 .

3. The switch statement is then used to check the operator entered by the user:
o If the user enters + , addition is performed on the numbers.
o If the user enters - , subtraction is performed on the numbers.
o If the user enters * , multiplication is performed on the numbers.
o If the user enters / , division is performed on the numbers.
o If the user enters any other character, the default code is printed.

Let’s take the same example but this time with break statement.
#include <iostream>

using namespace std;

int main(){

int i=2;

switch(i) {

case 1:

cout<<"Case1 "<<endl;

break;
7
case 2:

cout<<"Case2 "<<endl;

break;

case 3:

cout<<"Case3 "<<endl;

break;

case 4:

cout<<"Case4 "<<endl;

break;

default:

cout<<"Default "<<endl;

return 0;

Output:

4. Case2
5. Now you can see that only case 2 got executed, rest of the subsequent
cases were ignored.

8
#include <iostream>
using namespace std;

int main()
{
int day = 3;

switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
return0;
}}

9
#include <iostream>

using namespace std;

int main(){

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cout << cars[0];

// Outputs Volvo

return 0;}

Accessing Array Elements in C++


#include <iostream>

using namespace std;

int main() {

int a[] = {25, 50, 75, 100};

cout << a[0] << '\n';

cout << a[1] << '\n';

cout << a[2] << '\n';

cout << a[3] << '\n';

10
return 0;

Output
25
50
75

100

Changing the Elements of an Array in C++


To change the value of a specific element, refer to the index number:

#include <iostream>

using namespace std;

int main()

int a[] = {25, 50, 75, 100, 45};

a[3] = 60;

cout << a[3] << '\n';

return 0;

Output
60
11
Traversing an Array in C++
 To traverse an array, for loop is used.

Example

#include <iostream>

#include <string>

using namespace std;

int main() {

string fruits[5] = {"Apple", "Mango", "Banana", "Orange", "Grapes"};

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

cout << fruits[i] << '\n';

return 0;

Output
Apple
Mango

12
Banana
Orange
Grapes

input and Output Array Elements in C++


We can use the cin function to take inputs of an array from the user.

Example
// Program to take values of the array from the user and print the array
#include<iostream>
usingnamespace std;

intmain(){
int a[5];
cout <<"Enter the values of an integer array:"<< endl;

// Taking input and storing it in an array


for (int i = 0; i <5; ++i) {
cin >> a[i];
}

cout <<"Displaying integers:"<< endl;

// Printing elements of the array


for (int i = 0; i <5; ++i) {
cout << a[i] << endl;
}
return0;
}
The above code uses the for loop to take input values for an array a. After storing
the elements in an array, it again uses the for loop to print all of them.

Output
Enter the values of an integer array:
1
2
3
4
5
Displaying integers:
1
2
3

13
4
5

Variables of string type are able to store sequences of characters, such as words or sentence.

The program needs to include the header where the type is defined within the standard library
(header <string>):

// my first string

#include <iostream>

#include <string>

using namespace std;

int main ()

string mystring;

mystring = "This is a string";

cout << mystring;

return 0;

14
C++ String

#include <iostream>

using namespace std;

int main (){

char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

15
cout << "This is a greeting message: ";

cout << greet << endl;

return 0;

}
Output:

C++ String Class Introduced in C++

#include <iostream>

using namespace std;

int main(){

string greet = "Hello";

cout << "This is a greeting message: ";

cout<<greet<<endl;

16
Output:

Example: string

// C++ Program to demonstrate strings

#include <iostream>

usingnamespacestd;

intmain()

chars[] = "GeeksforGeeks";

cout << s << endl;

return0;

Output
GeeksforGeeks

17
Example: string

#include <iostream>

usingnamespacestd;

intmain()

string str(5, 'g');

cout << str;

return0;

Output:

ggggg

18
// C++ Program to demonstrate C-style string declaration

#include <iostream>

usingnamespacestd;

intmain()

chars1[] = { 'g', 'f', 'g', '\0'};

chars2[4] = { 'g', 'f', 'g', '\0'};

chars3[4] = "gfg";

chars4[] = "gfg";

cout << "s1 = "<< s1 << endl;

cout << "s2 = "<< s2 << endl;

cout << "s3 = "<< s3 << endl;

cout << "s4 = "<< s4 << endl;

return0;

Output
s1 = gfg
s2 = gfg
s3 = gfg

19
s4 = gfg

Using Cin

The simplest way to take string input is to use the cin command along with the stream
extraction operator (>>).
Syntax:
cin>>s;
Example:
 C++

// C++ Program to demonstrate string input using cin

#include <iostream>

usingnamespacestd;

intmain() {

string s;

cout<<"Enter String"<<endl;

cin>>s;

cout<<"String is: "<<s<<endl;

return0;

Output
Enter String
String is:

20
There are 3 types of loops in C++.

 for loop
 while loop
 do...while loop

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;

Output

1 2 3 4 5

21
Decrement number for loops
# include <iostream>
using namespace std;

int main()
{
for(int i = 5; i>0;)
{
i--;
cout <<i<<" ";
}
return 0;
}
The output of this code would be 4 3 2 1 0.

Example 2: 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;

22
Output

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Example 3: 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;

23
Note that we have used a for loop.

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

Here,

 int i = 1 : initializes the i variable


 i <= num : runs the loop as long as i is less than or equal to num

 ++i : increases the i variable by 1 in each iteration


When i becomes 11 , the condition is false and sum will be equal to 0 + 1 + 2

+ ... + 10 .

Ranged Based for Loop

In C++11, a new range-based for loop was introduced to work with


collections such as arrays and vectors. Its syntax is:

for (variable : collection) {


// body of loop
}

Here, for every value in the collection , the for loop is executed and the value
is assigned to the variable .

24
Code 3: Printing half pyramid using Alphabets

Similarly, we will replace the �x with the desired alphabets to print a pyramid of alphabets.

Source Code:

#include<bits/stdc++.h>
usingnamespace std;

int main(){

int rows;
// Getting the number of rows.
cout <<"Enter the Number of rows - ";
cin >> rows;

cout <<"Triangle of "<< rows <<" using characters -\n";

// Main logic to print triangle.


for( int i = 0; i < rows; i++ ) {
for( int j = 0; j <= i; j++ ){
cout << (char)('A' + j) <<" ";
}
cout<<endl;
}

return0;
}

Output:

Enter the Number of rows - 6


Triangle of 6 using * -
A
A B
A B C
A B C D
A B C D E
A B C D E F

Code 2: Printing half pyramid using numbers

Again to print a pyramid of numbers, we need to replace �x with �+1i+1,


where �+1i+1 denotes the row number. Here it is �+1i+1 because we are
starting �i from 0.

25
Source Code:

#include<bits/stdc++.h>
usingnamespace std;

int main(){

int rows;
// Getting the number of rows.
cout <<"Enter the Number of rows - ";
cin >> rows;

cout <<"Triangle of "<< rows <<" using integers -\n";

// Main logic to print triangle.


for( int i = 0; i < rows; i++ ) {
for( int j = 0; j <= i; j++ ){
cout << i + 1<<" ";
}
cout<<endl;
}

return0;
}

Output:

Enter the Number of rows - 6


Triangle of 6 using * -
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6

Example 1 – Program in C++ to print half star


pyramid pattern
In the following C++ program, the user can enter a number of rows to print

the half-star pyramid pattern as he wishes, then the result will be displayed

on the screen:

Code:

26
#include<iostream>

usingnamespace std;

intmain()

{
int i, j, n;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j =1; j <= i; j++)
{
cout <<"* ";
}
//Ending line after each row
cout <<"\n";
}
return0;
}
Example 2- Program in C++ to print an inverted
half-star pyramid pattern
In the following C++ program, the user can enter the number of rows to

print the inverted half-star pyramid pattern as he wishes, then the result will

be displayed on the screen:

Code:

#include<iostream>
27
usingnamespace std;
intmain()
{
int i, j, n;
cout <<"Enter number of rows: ";
cin >> n;
for(i = n; i >=1; i--)
{
for(j =1; j <= i; j++)
{
cout <<"* ";
}
// ending line after each row
cout <<"\n";
}
return0;
}
Example 3- Program in C++ to print star pyramid
pattern
In the following program, the user can enter the number of rows to print the

star pyramid pattern as he wishes, then the result will be displayed on the

screen:

#include<iostream>

using namespace std;

int main()

int n, s, i, j;

cout << "Enter number of rows: ";

28
cin >> n;

for(i = 1; i <= n; i++)

//for loop for displaying space

for(s = i; s < n; s++)

cout << " ";

//for loop to display star equal to row number

for(j = 1; j <= (2 * i - 1); j++)

cout << "*";

// ending line after each row

cout << "\n";

}
}

29
Example 4- Program in C++ to enter a number of
rows to print the star pyramid pattern
In the following program, the user can enter a number of rows to print the

star pyramid pattern as he wishes, then the result will be displayed on the

screen:

#include<iostream>

using namespace std;

int main()

int n, s, i, j;

cout << "Enter number of rows: ";

cin >> n;

for(i = n; i >= 1; i--)

//for loop to put space

for(s = i; s < n; s++)

cout << " ";

//for loop for displaying star

for(j = 1; j <= (2 * i - 1); j++)


30
cout << "* ";

// ending line after each row

cout << "\n";

return 0;
}
Example 5– Program in C++ to print an inverted
star pyramid pattern
In the following program, the user can enter a number of rows to print the

inverted star pyramid pattern as he wishes, then the result will be displayed

on the screen:

Code:

#include<iostream>
usingnamespace std;
intmain()
{
int n, s, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i = n; i >=1; i--)
{
//for loop to put space
for(s = i; s < n; s++)
cout <<" ";
//for loop for displaying star
for(j =1; j <= i; j++)
cout <<"* ";
// ending line after each row

31
cout <<"\n";
}
return0;
}
Example 7 – Program to print full star diamond
pattern in C++
In the following program, the user can enter the number of rows for the

diamond dimension to print the diamond pattern as he wishes, then the

result will be displayed on the screen:

Code:

#include<iostream>
usingnamespace std;
intmain()
{
int n, s, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =0; i <= n; i++)
{
for(s = n; s > i; s--)
cout <<" ";
for(j=0; j<i; j++)
cout <<"* ";
cout <<"\n";
}

32
for(i =1; i < n; i++)
{
for(s =0; s < i; s++)
cout <<" ";
for(j = n; j > i; j--)
cout <<"* ";
// ending line after each row
cout <<"\n";
}
return0;
}

Example 8

#include<iostream>
usingnamespace std;
intmain()
{
int n, i , j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j =1; j <= i; j++)
{
cout <<"*";
}
cout<<"\n";
}
for(i = n; i >=1; i--)
{
for(j =1; j <= i; j++)

33
{
cout <<"*";
}
// ending line after each row
cout<<"\n";
}
return0;
}
Example 9
Code:

#include<iostream>
usingnamespace std;
intmain()
{
int n, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j = i; j < n; j++)
{
cout <<" ";
}
for(j =1; j <= i; j++)
{
cout <<"*";
}
cout <<"\n";

34
}
for(i = n; i >=1; i--)
{
for(j = i; j <= n; j++)
{
cout <<" ";
}
for(j =1; j < i; j++)
{
cout<<"*";
}
// ending line after each row
cout<<"\n";
}
return0;
}

Example 10-Program to print hollow star pyramid


In the following program, the user can enter a number of rows to print the

hollow star pyramid pattern as he wishes, then the result will be displayed on

the screen:

Code:

#include<iostream>
usingnamespace std;

35
intmain()
{
int r, i, j, s;
cout <<"Enter number of rows: ";
cin >> r;
for(i =1; i <= r; i++)
{
//for loop to put space in pyramid
for(s = i; s < r; s++)
cout <<" ";
//for loop to print star
for(j =1; j <=(2* r -1); j++)
{
if(i == r || j ==1|| j ==2*i -1)
cout <<"*";
else
cout <<" ";
}
//ending line after each row
cout <<"\n";
}
return0;
}

C++ While Loop Example


Let's see a simple example of while loop to print table of 1.

36
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:

C++ While Loop


#include <iostream>

using namespace std;

int main() {

int i = 0;

while (i < 5) {

cout << i << "\n";


37
i++;

return 0;

While Loop example in C++


#include<iostream>
usingnamespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}

Output:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6

C++ While Loop Program Example


#include <iostream>

using namespace std;

int main(){

38
int i = 1;

while (i < 5){

cout << "You are unstoppable!\n";

i++;}

return 0;

Output:

You are unstoppable!


You are unstoppable!
You are unstoppable!
You are unstoppable!

Explanation:

1. In the above code snippet, we declare and initialize a variable i with the value of
1. We then make use of a while loop to print some statements.

2. A test expression (i<5) is checked, and the control moves to the first statement.

3. We use the cout statement inside the while loop to print the statement 'You are
unstoppable.

4. After the statement gets printed for the first time, the value of i then becomes 2
because of the update expression (i++).

5. The program again checks the condition, which is true, and the statement is
executed for the second time.

6. This is continued until i becomes 6, the condition (6<5) becomes false, and we
exit the loop.

39
Example 3: Display Numbers from 1 to 5 do...while Loop
// C++ Program to print numbers from 1 to 5

#include<iostream>

usingnamespacestd;

intmain(){
int i = 1;

// do...while loop from 1 to 5


do {
cout<< i <<" ";
++i;
}
while (i <= 5);

return0;
}
Run Code

Output

1 2 3 4 5

Example 4: Sum of Positive Numbers Only


// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include<iostream>
usingnamespacestd;

intmain(){
int number = 0;
int sum = 0;

40
do {
sum += number;

// take input from the user


cout<<"Enter a number: ";
cin>> number;
}
while (number >= 0);

// display the sum


cout<<"\nThe sum is "<< sum <<endl;

return0;
}
Run Code

Output 1

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

Here, the do...while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not
added to the sum variable.

Do-While Loop In C++

A do-while loop is similar to the while loop with one major difference. It
is an exit-controlled loop in which the condition is checked after

41
executing the body of the loop, unlike the while loop, which is an entry-
controlled loop. This can be used as an alternative to a while loop as
well.

#include <iostream>

using namespace std;

int main(){

int x = 9;

do {

cout << x << "\n";

x++;

} while (x < 10);

return 0;}

using namespace std;

42
#include<conio.h>

int gvar1;

int main()

// int means data type

// sum means name of function

// ( this name is Parenthesis

// int x,int y this is name list of parameter or

Argument

// (int x,int y) this name of formal parameter or

Argument

// formal parameter or Argument separeted by this , or

coma means int x, int y,

// = this operater name is assginment operater

// * means multiplby the values of x

// cout<<"x=="<<x<<endl; this is display the values of x

// cout<<"x=="<<y<<endl; this is display the values of

43
//int z=x+y; this means function Definition

int sum(int x,int y);{

int x=x*2;

cout<<"x=="<<x<<endl;

cout<<"y=="<<y<<endl;

int z=x+y;

rerurn z;

44
C++ Function example by values ,references code

explanation

#include<iostream>

using namespace std;

// test means local variable declaration

int test (int a, int b)

a=4;

b=5;

//this is main function

int main()

//this means pass or call by values

//int a=2,b=3; this is the name of formal parameteres

int a=2,b=3;

45
//this means show the output 2 and 3 not show 4 and 5 b/c

not call refereneces syntax

cout<<a<<endl;

cout<<b<<endl;

// to calling function from the local variables 4,5 by

int test varabile

//test(a,b) means name of actual parameters

test(a, b);

cout<<"this is calling by refereneces in local

variables"<<endl;

cout<<a<<endl;

cout<<b<<endl;

//calling by refereneses show 2,3 and 4,5 the output add

unperson commandes like this &,&

return 0;

46
#include<conio.h>

int gvar1;

int main()

// int means data type

// sum means name of function

// ( this name is Parenthesis

// int x,int y this is name list of parameter or

Argument

// (int x,int y) this name of formal parameter or

Argument

// formal parameter or Argument separeted by this , or

coma means int x, int y,

// = this operater name is assginment operater

// * means multiplby the values of x

// cout<<"x=="<<x<<endl; this is display the values of x

47
// cout<<"x=="<<y<<endl; this is display the values of

//int z=x+y; this means function Definition

int sum(int x,int y);{

int x=x*2;

cout<<"x=="<<x<<endl;

cout<<"y=="<<y<<endl;

int z=x+y;

rerurn z;

48
#include<iostream>
using namespace std;
int main()
{
int odd[10]={1,3,5,7,9,11,13,15,17,19};
cout<<odd[7]<<endl; this means show the number of
15
odd[7]=67;this means show 15 by replace by 67
cout<<odd[7]<<endl;
cout<<odd[0]+56<<" the number is"<<endl; this ishow
to add initial number `1+56= the result is 57
cout<<odd[0]<<" the number is"<<endl;
cout<<odd[1]<<" the number is"<<endl;
cout<<odd[2]<<" the number is"<<endl;
cout<<odd[3]<<" the number is"<<endl;
cout<<odd[4]<<" the number is"<<endl;
cout<<odd[5]<<" the number is"<<endl;
cout<<odd[6]<<" the number is"<<endl;
cout<<odd[7]<<" the number is"<<endl;
cout<<odd[8]<<" the number is"<<endl;
cout<<odd[9]<<" the number is"<<endl;
return 0;
}

49
one dimensional array example code
#include<iostream>

using namespace std;

int main()

int array1[5] = {10, 20, 30, 40, 50};

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

printf("%d ", array1[i]);

printf("\nArray1 elements after copying: ");

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

printf("%d ", array1[i]);

Output:
Array1 elements: 1020304050
 Initialize One Dimensional Array in C++ :

 data_type array_name[array_size] = {comma_separated_element_list};

 Example : int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

 One Dimensional Array Program in example

#include<stdio.h>

int main () {

int arr[10];

int i,j;

50
for ( i = 0; i < 10; i++ ) {

arr[i] = i + 10;

//this means display command of the result

for (j = 0; j < 10; j++ ) {

printf("arr[%d] = %d\n", j, arr[j] );

return 0;

Two-dimensional array example in C

1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5

51
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

Two-dimensional array example in C

#include<stdio.h>

int main(){

int i=0,j=0;

int arr[4][3]={{2,3,4},{7,8,9},{2,5,1},{8,3,2}};

//traversing 2D array

for(i=0;i<4;i++){

for(j=0;j<3;j++){

printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);

}//end of j

}//end of i

return 0;

52
Two-dimensional array example in C

#include<stdio.h>

int main(){

int i=0,j=0;

int arr[5][4]={{1,2,3},{2,3,4},{3,4,5},{4,5,6},{5,6,7}};

for(i=0;i<5;i++){

for(j=0;j<4;j++){

printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);

return 0;

53

You might also like