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.
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);
}
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]);
}
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);
}
}
Related
In an interview they asked me to find out the missing number from an array.
array will be having number from 1 to N.
My Approach:
int main()
{
int ar[20];
int sum = 0;
int n;
printf("enter numb of elements\n");
scanf("%d", &n);
printf("enter array numbers\n");
for(int i = 0; i<n;i++){
scanf("%d", &ar[i]);
sum +=ar[i];
}
printf("missing num=%d", ((n*(n+1))/2)-sum);
}
But interviewer did not call back after first round of interview.
I don't know what is wrong with my approach.
Some issues with your code:
The algorithm is wrong (off by one): If the array contains all numbers from 1 to N except for one missing number, then it has N-1 elements. Your code reads N elements. (Alternatively, if the array actually has N elements, then the target sum is (N + 1) * (N + 2) / 2 (sum of numbers from 1 to N+1), not N * (N + 1) / 2.)
Includes are missing (in particular, #include <stdio.h>). That means the calls to printf / scanf have undefined behavior.
int main() should be int main(void).
None of the scanf calls check their return value. That means your code doesn't realize when reading input fails, producing garbage output.
If n is bigger than 20, your code silently writes outside the bounds of ar. That's a classic buffer overflow.
The previous point is especially unfortunate because your code doesn't even need the array. All you do with the input numbers is to add them up in sum, which doesn't require a separate array.
Your formatting is inconsistent in for(int i = 0; i<n;i++){. Why is there no space in for(int and i<n;i++){, but there are spaces around i = 0;?
Depending on how big N is, n*(n+1) could overflow.
The last line of output produced by your code is missing its terminating newline: printf("missing num=%d\n", ...);
The title is kinda lame, but here's the explanation:
I want to check if the user input (integer) is in this form --> N = 4k + 1 (number 1, 5, 9, 13 and so on) and if the input isn't one of those numbers, I want keep asking the user to input the number until it's right.
I tried to do it like this:
I made a loop that checks if N-1 can be divided by 2, and if yes, that's my N. BUT, of course, it doesn't work. N-1 is supposed to be an even number (if the correct N is entered) so is there a way to check that somehow, and if it's not right to keep looping the "enter a number" part?
int N, k;
printf("Enter a number: ");
scanf("%d", &N)
k=(N-1);
/* checking */
while (k%2 != 0)
{
printf("Enter a number: ");
scanf("%d", &N);
}
The problem with this code is that when you enter the right number, it works fine, BUT when you input a wrong number, and afterwards the right number, it keeps looping the "Enter a number" part. How to fix this?
Put both the prompt and the check inside the same loop.
#include <stdio.h>
#include <stdlib.h>
int main (int args, char** argv) {
int N, k;
k = 1; // this is here just to get the loop going,
while (k%2 != 0) {
printf("Enter a number: ");
scanf("%d", &N);
k=(N-1);
}
return 0;
}
I'd like to point out, however, that your test is incorrect; half of all numbers that are divisible by 2 will not be correct answers to the task as-stated. I've only fixed the looping; not the logic. (There are several fine comments about fixing the math; take note of them.)
I've added a note about the purpose of the k = 1; line. As noted, it's there to prevent the while() loop from immediately exiting. I think you were hung up on calculating k from N, which is what you want to do in general, but you can supply a "fake" k so that k can serve as the loop condition before any input has been provided.
I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}
I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
I suggest:
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
Usage:
int main() {
int scores[6];
addScores(scores, 6);
}
a+i is not friendly to newcomer.
I suggest
scanf("%d", &a[i]);
Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:
#include <stdio.h>
int addScores(int *a, int *count) {
return scanf("%d", &a[(*count)++]);
}
int main(void) {
int scores[100];
int sCount = 0;
int sumScore = 0;
printf("enter scores followed by <return>. To finish, type Q\n");
while(addScores(scores, &sCount)>0 && sCount < 100);
printf("total number of scores entered: %d\n", --sCount);
while(sCount >= 0) sumScore += scores[sCount--];
printf("The total score is %d\n", sumScore);
}
A few things to note:
The function addScores doesn't keep track of the total count: that variable is kept in the main program
A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks #chux for the suggestion!
I was trying to solve a question on 2-D matrix, but unfortunately the matrix input was giving an error. This is the code:
int arr[4][4];
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int i, j;
fflush(stdin);
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &arr[i][j]);
When I run this, it takes extra input.
For example: if r = 2 and c = 2> then it takes 6 input and then hangs. What to do?
If r=2 and c=2, it executes the first 2 scanf and then the 2x2 scanf of your 2D loop.
This makes 2 + 2x2 = 6.
After the last scanf, if your program is finished, it simply closes, that's normal.
I have copied your code and tried executing it and I observed that it is showing the behaviour told by you if we are taking r and c greater than their limits. So use proper limits.
I think the problem with your code is that you've allocated a fixed amount of space for your array but allowed the user to provide an arbitrary number of inputs by making the bounds of your loop the user-provided r and cvariables. Thus if the user provides r=6 and c=6, at some point your loop will attempt to dereference arr[5][5], which is invalid since you've defined int arr[4][4];. If you want to allow the user to create as many rows and columns as they want, you should initialize arr with the user-provided input, like this:
int r,c;
scanf("%d",&r);
scanf("%d",&c);
int arr[r][c];
In your code you have simply run a loop and how much value will be scan depend on the how many loops has executed.
Suppose you take r=1,c=1.
In this condition for every "r" value c will executed single time.
So When your value will be larger than the array size that time it will give you abnormal behavior.
if you will firstly input the value of "c", and "r"after that it will behave normally.
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int arr[r][c];