Printing Vector Elements in C++: ForEach, For, and While Loops, Lecture notes of C programming

C++ code examples for printing elements of a vector using foreach, for, and while loops. It covers the use of indexing and accessing vector elements during each iteration.

Typology: Lecture notes

2021/2022

Uploaded on 09/27/2022

myfuture
myfuture 🇺🇸

4.4

(18)

258 documents

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C++ Print Vector Elements
To print elements of C++ vector, you can use any of the looping statements or foreach statement.
Print Vector Elements using ForEach
In the following program, we shall use C++ Foreach statement to print the elements of vector.
C++ Program
Output
Print Vector Elements using While Loop
In the following program, we shall use C++ While Loop to print the elements of vector from starting to end. We
shall use index to access an element of vector during each iteration.
C++ Program
C++ Print Vector Elements
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push_back(53);
nums.push_back(47);
nums.push_back(85);
nums.push_back(92);
for (int element: nums)
cout << element << endl;
}
53
47
85
92
#include <iostream>
pf3

Partial preview of the text

Download Printing Vector Elements in C++: ForEach, For, and While Loops and more Lecture notes C programming in PDF only on Docsity!

C++ Print Vector Elements

To print elements of C++ vector, you can use any of the looping statements or foreach statement.

Print Vector Elements using ForEach

In the following program, we shall use C++ Foreach statement to print the elements of vector. C++ Program Output

Print Vector Elements using While Loop

In the following program, we shall use C++ While Loop to print the elements of vector from starting to end. We shall use index to access an element of vector during each iteration. C++ Program

C++ Print Vector Elements

#include #include using namespace std; int main() { vector< int > nums; nums.push_back(53); nums.push_back(47); nums.push_back(85); nums.push_back(92); for ( int element: nums) cout << element << endl; } 53 47 85 92 #include

Output

Print Vector Elements using For Loop

In the following program, we shall use C++ For Loop to print the elements of vector. As in while loop, we shall use index to access elements of vector in this example as well. C++ Program Output #include #include using namespace std; int main() { vector< int > nums; nums.push_back(53); nums.push_back(47); nums.push_back(85); nums.push_back(92); int i = 0; while (i < nums.size()) { cout << nums[i] << endl; i++; } } 53 47 85 92 #include #include using namespace std; int main() { vector< int > nums; nums.push_back(53); nums.push_back(47); nums.push_back(85); nums.push_back(92); for ( int i = 0; i < nums.size(); i++) { cout << nums[i] << endl; } } 53 47 85 92