219k views
4 votes
Write a program in c++ that asks the user for a sequence of n​integers, where the user provides the number of elements n​ then each of the elements. After storing the n​ values in the array, ask the user for a value to search within those elements and return the index of the first instance (starting with 0 as the first element). Each integer should be stored in an array in the order they were read from the user. Follow the prompts and output format listed below. The user is expected to enter no more than 256 elements, the array should be able to hold no less and no more​ than 256.

User Stephani
by
7.3k points

1 Answer

3 votes

Answer:

// here is code in C++.

#include <bits/stdc++.h>

using namespace std;

// function that return the first occurrence of item

int fun(int a[],int item,int n)

{

for(int y=0;y<n;y++)

{// find first occurance

if(a[y]==item)

// return index

return y;

}

}

// main function

int main()

{

// variables

int n,item;

// array that holds 256 number only

int a[256];

cout<<"enter the value of n:";

//read the value of n

cin>>n;

// if n is greater than 256, it will again ask for input

while(n>256)

{

cout<<"value of n should be less than 256:"<<endl;

cout<<"enter value of n again:";

cin>>n;

}

// read n numbers

cout<<"enter "<<n<<" numbers:";

for(int x=0;x<n;x++)

{

cin>>a[x];

}

// read item to be searched

cout<<"enter the number to be searched:";

cin>>item;

// calling the function and print the index

cout<<"item found at index "<<fun(a,item,n)<<endl;

}

Step-by-step explanation:

Declare a variable "n" and create an array of size 256.Then read the value of "n". If n is greater than 256 then it will again ask user to enter a number less than 256.Then it will read "n" numbers from user and store them into array.Then it will read item to be searched and call the function with parameter array, item and n. function will find the first occurrence of the item and return its index.

Output:

enter the value of n:280

value of n should be less than 256:

enter value of n again:7

enter 7 numbers:12 4 7 9 7 6 21

enter the number to be searched:7

item found at index 2

User ShaunOReilly
by
8.0k points