Array and String
1. One Dimentional Array
1. Write simple c++ Array display types of five cars out put
#include <iostream>
#include <string>
0 = Volvo
using namespace std; 1 = BMW
2 = Ford
3 = Mazda
int main() { 4 = Tesla
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout<< i <<" = "<< cars[i] <<"\n";
return 0;
}
2.. Write a C++ program to find the second smallest elements in a given array of
integers.
C++ Code :
# include<iostream>
using namespace std;
int find_Second_Smallest(int array_num[],int n){
int smallest_num,second_smallest_num;
if(array_num[0]<array_num[1]){
smallest_num=array_num[0];
second_smallest_num=array_num[1];
}else{
smallest_num=array_num[1];
second_smallest_num=array_num[0];
for(int i =0; i < n; i++){
if(smallest_num>array_num[i]){
second_smallest_num=smallest_num;
smallest_num=array_num[i];
}else
if(array_num[i]<second_smallest_num&&array_num[i]>smallest_num){
second_smallest_num=array_num[i];
return second_smallest_num;
}
int main(){
int n =7;
int array_num[7]={
5,
6,
7,
2,
3,
4,
12
};
int s =sizeof(array_num)/sizeof(array_num[0]);
cout<<"Original array: ";
for(int i=0; i < s; i++)
cout<<array_num[i]<<"";
int second_smallest_num=find_Second_Smallest(array_num, n);
cout<<"\nSecond smallest number: "<<second_smallest_num;
return 0;
}}
Copy
Sample Output:
Original array: 5 6 7 2 3 4 12
Second smallest number: 3
3 .Here are some C++ example programs that demonstrate one-dimensional
arrays. The following is the first example program:
#include<iostream>
using namespace std;
int main()
{
intarr[5] = {1, 2, 3, 4, 5};
for(int i=0; i<5; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
return 0;
}
The output of this C++ program is as follows:
1
2
3
4
5
4.
#include<iostream>
using namespace std;
int main()
{
int i, arr[5];
cout<<"Enter 5 elements for the array: ";
for(i=0; i<5; i++)
cin>>arr[i];
cout<<"\nThe array is:\n";
for(i=0; i<5; i++)
cout<<arr[i]<<"\t";
cout<<endl;
return 0;
}
The following snapshot shows the initial output produced by the above
program:
5. .#include <iostream> out put
using namespace std;
c
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout<< letters[0][2];
return 0;
}
6 .One Dimantional Array
# include <iostream>
using namespace std;
int main()
{
int y=5;
int odd[10]={1,3,5,7,9,11,13,15,17,19};
cout<<odd[0]+50<<" ";
cout<<odd[1]<<" ";
cout<<odd[2]<<" ";
cout<<odd[3]<<" ";
return 0;
}
7. Write a program which asks the user to type 5 float
numbers and display the smallest one
# include <iostream>
using namespace std;
int main()
{
float n[5];
cout<<"Enter the integer numbers";
for(int j=0;j<=5; j++)
cin>>n[j];
float small=n[0];
for(int i=0; i<5; i++)
if(n[i]<small)
small=n[i];
cout<<small;
return 0;
}