Check whether multiple values exist within an array (C) Say I have a set of numb
ID: 3717006 • Letter: C
Question
Check whether multiple values exist within an array (C)
Say I have a set of numbers from 1-40 and I have used scanf to scan in 10 of these numbers into an array
How would I code it so that my program will check whether some numbers (say 5,6,7,15,19,21) are in my array and then for each number that is in the array, assign it to a variable?
eg: I scan in 1,2,3,4,5,6,7,8,9,10 , but want my program to check that 5 or 6 or 7 or 15 or 19 or 21 are in the array, then after checking it would assign 5 to variable_1, 6 to variable_2, 7 to variable_3 since they are present in the array
Explanation / Answer
#include<stdio.h>
int main()
{
int i,j,index;
int arr[10];
//list to check in array
int check[]={5,6,7,15,19,21};
//variables to store if element is present in the array
int variable_1,variable_2,variable_3,variable_4,variable_5,variable_6;
//prompt user to enter 10 elements into array
printf("Enter 10 elements into an Array: ");
for(i=0;i<10;i++)
{
scanf("%d",&arr[i]);
}
//check 5 is present in the array or not
index=0;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_1=arr[i];
break;
}
}
//check 6 is present in the array or not
index=1;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_2=arr[i];
break;
}
}
//check 7 is present in the array or not
index=2;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_3=arr[i];
break;
}
}
//check 15 is present in the array or not
index=3;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_4=arr[i];
break;
}
}
//check 19 is present in the array or not
index=4;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_5=arr[i];
break;
}
}
//check 21 is present in the array or not
index=5;
for(i=0;i<10;i++)
{
if(check[index]==arr[i])
{
variable_6=arr[i];
break;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.