Reputation: 11
Quick, probably super basic question. If I declare an array of 10 doubles and prompt a user to input how many double they want in the index (between 1 and 10, obviously), how would I enforce that range? I assume with an if/else statement, but is there a more optimal way to enforce that range?
Again, probably really simple. I'm new so not yet familiar C++ or JavaScript.
Upvotes: 1
Views: 314
Reputation: 2251
Another solution maybe if you wrap the value within the required range using % (modulo) operator.
int n;
int arr[10];
printf("Enter a number : ");
scanf("%d",&n);
printf("%d",arr[n%10]);
The expression n%10
will always result in a value between 0 to 9.
Edit (for a better validation):
#include<stdio.h>
main()
{
int x, n;
int arr[]={0,1,2,3,4,5,6,7,8,9,10,11,12};
printf("Enter a number : ");
if( scanf("%d",&n)!=1 )
{
printf("Not a valid integer!!");
return;
}
n=(n<0)?-n:n;
printf("%d",arr[n%10]);
}
Upvotes: 1
Reputation: 496
First you should read the documentation because this is a very basic example.
Second avoid requesting code here. You should always try to found solution then post your code and your error here to correct it.
You can try this:
#include<stdio.h>
int main(){
int n = 0;
while(!(n > 1 && n < 10)){
printf("Enter an integer between 1 and 10: \n");
scanf("%d", &n);
}
}
Upvotes: 0
Reputation: 675
Get that no. of elements from user till that no. is not within your range.
Say n is number that you want in range 1 to 10.
Solution:
int n = 0;
while(n<1 || n>10) {
printf("Enter Correct value on n i.e. within range 1 to 10:\t");
scanf("%d", &n);
}
Upvotes: 1