Lab 7 Array An array is used to process a collection of data all of which is of the same type, such as a list of temperatures or a list of names. Structure of array Initializing arrays Initializing arrays Program 1 Write a C++ program that stores ‘a’, ‘b’, ‘c’ in an array and print the values of the array using for loop. Solution to Program 1 #include <iostream> using namespace std; int main() { char symbol[3] = {'a', 'b', 'c'}; for (int index = 0; index < 3; index++) cout << symbol[index]; } Program 2 Write a C++ program that stores numbers from zero to nine in an array using a for loop and print the values of the array using a different for loop. Solution to Program 2 #include <iostream> using namespace std; int main() { int i, temp[10]; for (i = 0; i < 10; i++) temp[i] = i; for (i = 0; i < 10; i++) cout << temp[i] << " "; } Program 3 Write a C++ program that stores numbers from zero to nine in an array and print the values of the array using only one for loop. Solution to Program 3 #include <iostream> using namespace std; int main() { int i, temp[10]; for (i = 0; i < 10; i++) { temp[i] = i; cout << temp[i] << " "; } } Program 4 Write a C++ program that stores the following values in an array and prints the total and average. 23, 6, 47, 35, 2, 14 Solution to Program 4 #include <iostream> using namespace std; int main() { int sample_array[]={23, 6, 47, 35, 2, 14}; int total=0; for (int index = 0; index <= 6; index++) total=total+sample_array[index]; cout<<"total is "<< total<<" the average is "<<total/6; } Program 5 Write a C++ program that stores the following values in an array and print the first five values in the array using a for loop. 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 Program 6 Write a C++ program that accepts five numbers from the user and store them in an array and prints out the maximum number. Note use for loop. Program 7 Write a C++ program that stores the following letters in an array and prints out them as one word. Note use for loop to print. ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ Program 8 Write a C++ program that prints the following output using an array and for loop.
© Copyright 2024