Newb here.
I'm probably missing something trivial but:
Here's the thing: http://i.imgur.com/8BmPci5.png
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Sort Numbers (zuerst)
int numbers [10];
int i,j;
j = 0;
int read;
printf("Input numbers: \n");
for (i=0;i<10;i++) {
scanf("%d",&read);
if (read == 27) {
break;
} else {
numbers[i] = read;
j++;
}
}
printf("j is: %d, i is: %d\n", j, i);
for (i=0;i<j;i++) {
printf("numbers[%d] is: %d\n", i, numbers[i]);
}
return 0;
}
Output:
Input numbers:
1
2
3
^[
j is: 10, i is: 10
numbers[0] is: 1
numbers[1] is: 2
numbers[2] is: 3
numbers[3] is: 3
numbers[4] is: 3
numbers[5] is: 3
numbers[6] is: 3
numbers[7] is: 3
numbers[8] is: 3
numbers[9] is: 3
I have a for loop (goes from 0 to <10). I also have a scanf inside wich scans for an int. If it ain't ESC (ASCII 27), then it puts it into an array and it increments the value of j. If it's an ESC, it ('s supposed to) break (exit the loop). Later, only j (or j-1) number of array items would be printed.
Issue: j (and i too) increments to 10, even if break is called at ~ i = 3 or 4.
Break supposed to exit the for loop without doing anything after it's called, right? Quote from BeginnersBook.com:
It is used to come out of the loop instantly. When a break statement is encountered inside a loop, the control directly comes out of loop and the loop gets terminated. It is used with if statement, whenever used inside loop.
What's wrong with my code? Thanks in advance.
You're being naughty in that you're not checking the return value of scanf, which will tell you the number of variables that were successfully populated. In your case, you want that to be 1 to signal that something was read into your variable read.
If you try to pass \033 (ASCII encoded ESC), then scanf will fail to parse that to an int. Then the previous value of read will be retained (which could give you undefined effects if it hasn't yet been set to anything), and read == 27 will almost certainly be 0. That behaviour accounts for the output you are observing.
If scanf does fail, you could try reading a char from the stream, and check if that is equal to \033.
Related
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 have been going through some exercises from a recommended book I found on this website. I came across this following basic piece of code, which I could not fully understand.
#include <stdio.h>
int main(void)
{
int i;
for (i = 10; i >= 1; i /= 2)
printf("%d ", i++);
return 0;
}
This is my reasoning behind this program fragment:
Variable i is initialised to 10.
i is tested to see if greater or equal to 1, (which is always the case).
The third expression reads: i = i / 2, thus i is divided by 2 and its value stored in i.
In the printf statement i is incremented after each printf statement.
I simply cannot understand why the output of this program is:
1 1 1 1 1 1 1 1 ...
I get that the condition statement is always true, however shouldn't the first values be:
5 3 2 1 1 1 1 1?
Basically I cannot seem to understand why the value of i is straight away being stored as 1. Any corrections regarding my reasoning and/or insight on the matter will be appreciated. Please do excuse the basic nature of this question.
As #abelenky pointed out, the correct output is 10 5 3 2 1 1 1 .... The only mistake you made in your reasoning is that the statement i /= 2 gets evaluated after the body of the for loop, before testing the condition again. Another way to write the same loop would therefore be
for(i = 10; i >= 1; i = (i + 1) / 2)
printf ("%d ", i);
If you are running on Windows, try paging the output through more: myprog | more. This should allow you to see the beginning of the output of this infinite loop. On a linux machine, you could acheive the same result using more or less: myprog | less. Thanks to #EugeneSh for making the suggestion that this could be the issue.
Another way that I have found to view the initial output for programs like this is to hit Ctrl+C immediately after starting the program with Enter. This is not a "standard" method and may require very quick reflexes to get any results for a quick loop like yours.
A final suggestion is to limit the output you produce from the program directly:
int i, count;
for(i = 10, count = 0; i >= 1 && count < 100; i /= 2, count++)
printf("%d ", i++);
This will add a counter that will stop your output after 100 numbers have been printed and allow you to see the first numbers.
On the second line, you have 'i++'.
Thus at each iteration of the loop, it will also increment i by 1.
So supposing i = 1 when you start the loop. First it will be divided by 2 (i /= 2). Since i is an integer, it will become 0. Then, on the second line, you have 'i++', thus incrementing i.
So by the end of the loop iteration, i will be back to being equal to 1 (thus making this loop infinite).
In this program:
#include<stdio.h>
int a[5],c=0;
int main()
{
printf("Enter no\n");
scanf("%d",&a);
for(int i=0;a[i];i=+2) {
printf("%d ",a[i]);
}
return 0;
}
I want to input 12345 and get the output 1 3 5, but the program never terminates. How can i do this?
Honestly, your code is just all over the place, it looks as if you're just wildly guessing:
You can't pass an int array to scanf(), ask it to read one int, and expect it to put all the digits of a multi-digit number into the individual elements all by itself like that. You either need to read in a string, or read in a single int and extract the digits yourself.
The variable c is unused.
Your for loop makes no sense at all. Even if you had filled all the elements of your array a, it still wouldn't make sense, and you haven't.
Here's a sensible version of your code, reading into a string:
#include<stdio.h>
int main(void) {
char a[6];
printf("Enter no\n");
fgets(a, 6, stdin);
for (int i = 0; i < 5; i += 2) {
printf("%c ", a[i]);
}
putchar('\n');
return 0;
}
with output:
paul#local:~/Documents/src/sandbox$ ./num
Enter no
12345
1 3 5
paul#local:~/Documents/src/sandbox$
Note that this does nothing to check whether the user actually did enter five characters, which your program should do.
the for loop is defined in this way
for(initialization ; condition check ; variable update)
in your code
for(int i=0;a[i];i+2)
{
printf("%d ",a[i]);
}
the condition part of the for loop is set to a[i], which is probably never false. so the loop runs infinitely. the variable update is also incorrect. i value should be updated.
try
for(int i=0; i<5; i+=2)
{
printf("%d ",a[i]);
}
The code is running infinitely because nothing changes inside the loop that would cause the loop to terminate. No variable's value is changed anywhere inside the loop. If a[i] is true for the first iteration, it will remain true forever since i's value never changes.
Output of the program:
#include <stdio.h>
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int b[size],i = 0;
printf("Enter %d integers to be printed: ",size);
while(i++ < size)
{
scanf("%d",&b[i]);
printf("%d %d\n", i, b[i]);
}
return 0;
}
for size = 5 and input numbers :
0 1 2 3 4
is
1 0
2 1
3 2
4 3
5 4
where first column is for i and second for elements of array b.
It is clear that i in the loop while(i++ < size) { incremented to 1 before entering the loop. This loop should have to store/print the value at/of b[1], b[2], b[3], b[4] but not b[5] as loop will terminate at i = 5.
How this code is printing the value of b[5]?
I have tested it for different array size and it is not printing any garbage value.
By reading and writing past the array, your program invokes undefined behavior. It doesn't mean that it has to crash or print garbage values, it can pretend working fine. Apparently, that's what is happening in this case.
In your loop, the condition i < size is checked before i is incremented. But, i is incremented before entering the body of the loop and not after it, so it is possible to access b[5] in this case, as i would be incremented after checking i < size with i=4. You do not want that, as this causes undefined program behavior.
If you try to access an element in the array which does not exist, e.g. array[size], you are accessing the next spot in the memory right after the array. In this case you are lucky, but if this meant you were accessing a part of the memory where your program isn't allowed to do so, you'd get a segmentation fault.
you could use a for cycle instead of a while so instead of while(i++<size)you could use for(i = 0; i < size; i++) that should solve your problem my friend :)
I wrote a C program that is behaving in a way I don't understand. I am posting this in the hope that I will learn a bit more about C. The code seems to be writing variable names into other variables using fscanf when that was not asked of it at all...
#include <stdio.h>
#include <stdlib.h>
int main() {
float BCL[6];
float varsRA[23],varsLA[23],varsBB[23],varsPV[23];
FILE *inputfil;
int i;
inputfil = fopen ("file.txt", "rt");
for(i=0;i<24;i++) {
fscanf(inputfil,"%f %f %f %f\n", &(varsRA[i]), &(varsLA[i]), &(varsBB[i]), &(varsPV[i]));
}
i=23;
printf("vars%d:%f %f %f %f\n",i,varsRA[i], varsLA[i], varsBB[i], varsPV[i]);
i=0;
while(!feof(inputfil)) {
fscanf(inputfil,"%f ",&(BCL[i]));
i++;
}
i=23;
printf("vars%d:%f %f %f %f\n",i,varsRA[i], varsLA[i], varsBB[i], varsPV[i]);
fclose(inputfil);
return 0;
}
The outcome is:
vars23:-66.336823 -68.164223 -57.850136 -60.762585
vars23:-66.336823 -68.164223 -57.850136 177.000000
Why was the last value of varsPV changed to 177, which is the first value of BCL, when I read the rest of the file?!
Many thanks for your help,
Marta
The program has undefined behaviour as it is accessing beyond the bounds of the arrays:
for(i=0;i<24;i++) {
fscanf(inputfil,"%f %f %f %f\n", &(varsRA[i]), &(varsLA[i]), &(varsBB[i]), &(varsPV[i]));
}
Array indexes run from 0 to N - 1, where N is the number of elements in the array.
The arrays are defined with 23 elements, meaning valid indexes are from 0 to 22. Change the loop terminating condition to i < 23 or use a compile time constant to define the array size and the terminating condition to avoid duplicating that piece of information.
There are other out of bounds accesses in the program and this loop needs protection from going out of bounds:
i=0;
while(!feof(inputfil)) { /* i < 6 required */
fscanf(inputfil,"%f ",&(BCL[i]));
i++;
}
Always check the return value of fscanf() to ensure assignments were actually made. fscanf() returns the number of assignments made:
for (i = 0; i < 6 && 1 == fscanf(input, "%f", &BCL[i]); i++);
Your arrays aren't being defined big enough. The array varsRA[23] only contains 23 elements numbered 0 through 22. You're reading in 24 elements numbered 0 through 23. Change your array definitions to the following and you should be good to go.
float varsRA[24],varsLA[24],varsBB[24],varsPV[24];
Array indices in C are zero-based.
float varsRA[23],varsLA[23],varsBB[23],varsPV[23]
Those arrays have 22 as their last valid index, which makes 23 elements. That's why
for(i=0;i<24;i++)
writes one extra element to each of them. What you get is undefined behavior (so there is nothing reasonable to expect), but your particual kind of undefined behavior is overwriting a piece of another array (and probably some random memory location).