Last value in loop always incremented by one [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
Apologies if this has already been answered, but I couldn't find a good way to describe it or search it, which is why the title is a bit... odd.
int aGrade[4];
do {
printf("\nType the student %ds grade: ", (i + 1));
scanf("%d", &aGrade[i]);
i++;
} while (i <= 4);
For some reason, the last value input is always incremented by one. If, in the loop, aGrade[4]'s value is set to 5, and I print its value to the console, it returns as 6.
I have seen this happen with for, do and while loops and I can't figure out what's happening. Thanks in advance! :)

Your program has a buffer overflow bug due to the do-while loop condition while (i <= 4).
The array aGrade[4] can store up to 4 elements, these can be accessed by aGrade[0], aGrade[1], aGrade[2] and aGrade[3].
Note how aGrade[4] isn't an option.
int aGrade[4];
do{
printf("\nType the student %d grade: ", (i+1));
scanf("%d", &aGrade[i]); i++;
}
while (i < 4);
You could also use a for loop which in most cases looks more clear and readable:
int aGrade[4];
for (int i = 0; i < 4; i++)
{
printf("\nType the student %d grade: ", (i+1));
scanf("%d", &aGrade[i]);
}

When you allocate aGrade[4] your program creates a memory block 4 x (size of an int in your system). These can be accessed using aGrade[0], aGrade[1], aGrade[2] and aGrade[3].
You can also access aGrade[4] or aGrade[100]. It is an option but not what you are trying to do here.
aGrade[0] points to a memory location where first element of your array is stored. That location can also be dereferenced as *(aGrade + 0). When you try to access *(aGrade + 4), program tries to reach the memory address next to your array.
useful link!
*(aGrade + 4) is a random memory location. You can access&modify it. It is not what you want here or anywhere if you do not want to try it expilicitly (In cases like when you want to bypass a password check which might be an advanced topic at this point for you) .

Related

C programming - Finding the necessary number in the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).

Issues in for loop for finding Prime number in C, Visual Studio [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I wrote a simple for loop in C to find if entered number is a prime number. Upon running, even when entering simple values like 7, 13, etc. the programme just sits on it and seems to be processing something huge. I have an i53340M so processing power really isnt an issue. CPU usage shoots up to 25% on all cores and I see no result even after few minutes of waiting. Of course, modern processors are not slow and C is very fast, much faster than Python, which itself is cabale of checking for prime very swiftly.
It seems to me that I have done something stupid and left the code unoptimised or bloated. Please take a look and tell me where I went wrong :
int num,i,chk = 0 ;
printf("\nEnter positive integer to check : ");
scanf("%d", &num);
for (i = 2; i = num / 2; i++)
{
if (num%i == 0)
{
break;
chk = 1;
}
}
if(num == 1)
printf("\n\n1 is neither prime not composite.\n");
else if(chk == 1)
printf("\n\nThe number %d is indeed prime.\n", num);
else
("\n\nThe number %d is not actually prime.\n", num);
i = num / 2 assigns num / 2 to i and evaluates as “true” to continue the for loop. (when n is greater than 1). You may have intended i <= num / 2.

How to dynamically allocate memory in 2D array and store values? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to allocate memory in a 2D array dynamically, but I don't know what is wrong.
Error
let input is
2 2
1 2 3 4 5 6 7 8 9 ........
then program crashes
#include<stdio.h>
#include<stdlib.h>
int main()
{
int N,M;
int i,j;
scanf("%d %d",&N,&N);
int **A = (int **)malloc(N*sizeof(int *));
for(i=0;i<N;i++)
{
A[i] = (int *)malloc(M*sizeof(int));
}
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
scanf("%d",&A[i][j]);
}
}
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%d",A[i][j]);
}
}
return 0;
}
Here's your problem:
scanf("%d %d",&N,&N);
When you read in the array dimensions, you read into N twice and never read into M. As a result, the contents of M are indeterminate, and attempting to read that value invokes undefined behavior.
Fix this to input a value for M:
scanf("%d %d",&N,&M);
As i said problem is in scanning N and M variables.
Change
scanf("%d %d",&N,&N);
to
scanf("%d",&N);
scanf("%d",&M);
and you are fine.
Problem was you were reading N twice while didnt read an M which was used uninitialized.
Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.
You should free all your allocated memory
for(i=0;i<N;i++)
{
free(A[i]);
}
free(A);
and dont cast malloc()'s return value becouse
Its reduntand
Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found
If the type of the pointer is changed, one must fix all code lines where malloc() was called and cast
Next time if you cannot find a bug, try to use debugger and look what exactly is happening, you can see variable values, where would you clearly see that M is uninitialized and didnt change after scanf().

Repeating a task/block of code X times (introduced by user) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I recently started coding in c. I was wondering how you can repeat/loop a task as many times as the user wants (by input).
int a,i;
scanf("%d", a);
for(i=0; i<a; i++){...}
This is the code I came up with, but it doesn't work. It's an infinite loop.
You need a & to scan into.
int a,i;
scanf("%d", &a);
for(i=0; i<a; i++){...}
Read a bit more about scanning integers here.
How to scanf only integer?
Change scanf("%d", a) to scanf("%d", &a)
The code didn't work for you because you failed to store the value entered by the user.
Before modifying your code as my suggestion try to print the value of a in your code, you'll get it, why it's not working..
The problem is in line:
scanf("%d", a);
You have to use:
scanf("%d", &a);
& sign represents address, you want to store input value on the address of variable a.
Read more about ampersand here:
When should I use ampersand with scanf()

Can't get a number guessing game to work in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Tried to write a program in C to say the amount of times you guessed the right number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, searchNumber, Number, rightGuess;
rightGuess = 0;
printf("Give your number: ");
scanf("%d",&searchNumber);
printf("\n\n Give 10 numbers: ");
for(i=1;i<=9;i++){
scanf("%d \n",&Number);
if(Number == searchNumber){
rightGuess++;
}
}
printf("You guessed the number %d times",&rightGuess);
return 0;
}
However every time I run it, it says I guessed the number 6356736 times. Even though I only entered a number 0 times. Any help?
Maybe you made a mistake in printf().
If there is a variable named var, &var means the memory address where variable var is. Maybe the number 6356736 you saw in your program is the memory address, not the value in variable var.
You will have to change this line in order to print the value of variable rightGuess
printf("You guessed the number %d times", &rightGuess);
To this line.
printf("You guessed the number %d times", rightGuess);
Your call to printf ought to be
printf("You guessed the number %d times", rightGuess);
i.e. don't pass a pointer to rightGuess in correspondence to the %d format specifier. Currently the program behaviour is undefined! (It could well be outputting the address of rightGuess which accounts for the large number - but don't ever rely on that; you need to use %p to output pointer addresses.)

Resources