samedi 26 juin 2021

This is a program to search a number and also display its index position if found in an array

This is a C++ program to search a number and also display its index position if found in an array.
Program works fine. I just wanted to ask why we used k=1 in if statement because if we don't use it, then program won't work. Please explain the significance of k=1 in 2nd for loop in if statement.

#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Size of Array: ";
cin>>n;
int arr[n];
cout<<"Type Elements of Array: ";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int k;
cout<<"Enter No to be found: ";
cin>>k;
for(int i=0; i<n; i++)
{
if(arr[i]==k)
{
    k=1;
    cout<<"No is found at index position: "<<i<<endl;;    
    break;
}
else
{
    cout<<"No is not found"; 
    break;   
}
}
return 0;
}

Aucun commentaire:

Enregistrer un commentaire