Reputation: 25
I would like to ask: How to check user input , which is stored in array with another array, I have defined... Something like this: User will give input 10,20,5 and I need to check, if it is from this array {5,10,20,50}
Any help appreciated :). Thanks
#include <stdio.h>
#include <stdlib.h>
int main ()
{
float bill;
int notes[] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01};
printf("Enter value of your bill: ");
scanf("%f",&bill);
if (bill<0 || bill>10000)
{
return -1;
}
else
{
for (int i=0; i<8;i++)
{
if (bill!=notes[i])
{
break;
}
}
}
return 0;}
Upvotes: 0
Views: 117
Reputation: 12022
#include<stdio.h>
int main(){
int inp,i,j;
int foo=0;
int arr[]={5,10,20,30};
for(j=0;j<3;j++){
scanf("%d",&inp);
for(i=0;i<4;i++)
{
if(inp == arr[i])
{
foo=1;
break;
}
}
if(foo==0)
break;
}
}
Upvotes: 0
Reputation: 551
To get user input you must use the scanf()
function. Here is an example, where it asks for three separate numbers.
#include <stdio.h>
int main(void) {
int one, two, three;
printf("Enter first number: ");
scanf("%d", &one);
printf("Enter second number: ");
scanf("%d", &two);
printf("Enter third number: ");
scanf("%d", &three);
printf("one: %d, two: %d, three: %d\n", one, two, three);
return 0;
}
Will produce the following:
Enter first number: 1
Enter second number: 2
Enter third number: 3
one: 1, two: 2, three: 3
Here is another way to use scanf, but the user must be more specific about how they answer the prompt.
#include <stdio.h>
int main(void) {
int one, two, three;
printf("Enter three numbers separated by a comma: ");
scanf("%d,%d,%d", &one, &two, &three);
printf("one: %d, two: %d, three: %d\n", one, two, three);
return 0;
}
Will produce the following:
Enter three numbers separated by a comma: 1,2,3
one: 1, two: 2, three: 3
UPDATE: Because you posted code that shows you know how scanf works.
To search through an array you must use a for loop.
#include <stdio.h>
int main(void) {
float n = 100;
int numbers[] = {5, 10, 20, 50, 100, 200, 500};
int i;
for (i = 0; i < 7; i++) {
if (n == numbers[i]) {
printf("Matching index for %f at %d\n", n, i);
}
}
return 0;
}
Upvotes: 2