This is a C++ Program to Print the Element at a Given Position.
The program takes an array of elements and prints the element at a given position.
1. The program takes an array of elements and stores them in an array.
2. The position whose element is to be printed is taken.
3. Using a for loop, the element at that position is printed.
4. Exit.
Here is the source code of C++ Program to Print the Element at a Given Position. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
char arr[10], ele;
int i, n, pos;
cout << "Enter size of the array : ";
cin >> n;
cout << "\nEnter elements of the array : ";
for (i = 1; i <= n; i++)
cin >> arr[i];
cout << "\nEnter the position : ";
cin >> pos;
for (i = 1; i <= n; i++)
if (pos == i)
ele = arr[i];
cout << "\nElement at position " << pos << " is : " << ele;
return 0;
}
1. The user is asked to enter the size of the array and the value is stored in ‘n’.
2. Elements of the array are asked to enter and stored in character variable ‘arr’.
3. The position is entered and stored in the variable ‘pos’.
4. Using a for loop and initializing ‘i’ as 1, the array is traversed.
5. If pos is equal to i, then element at that position is stored in the variable ‘ele’.
6. The result is then printed.
Case 1 : Enter size of the array : 3 Enter elements of the array : T O P Enter the position : 2 Element at position 2 is : O Case 2 : Enter size of the array : 5 Enter elements of the array : 8 4 5 2 9 Enter the position : 1 Element at position 1 is : 8 Case 3 : Enter size of the array : 4 Enter elements of the array : SWIM Enter the position : 3 Element at position 3 is : I
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check Computer Science Books
- Apply for C++ Internship
- Check C++ Books
- Practice Programming MCQs
- Apply for Computer Science Internship