C programming - Finding the necessary number in the array [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 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).

Related

Last value in loop always incremented by one [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 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) .

Program with array to find a sum 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 4 years ago.
Improve this question
I was thinking of a code to find the sum of numbers.
So i wrote bellow code :
#include <stdio.h>
#include <math.h>
int main()
{
int n,i,s=0,a[100];
printf("enter number of numbers");
scanf("%d",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
s=0;
for (i=1;i<=n;i++)
{s=s+a[i];}
printf("sum is%d\n",s);
}
But in the output it shows segmentation error . I.e.
So whats the mistake?
So this line:
scanf("%d",n);
should be replaced by
scanf("%d",&n);
Explanation:
scanf() reads data from stdin according to format and store data in the location pointed by next additional argument. this case, format is %d means we want to read an integer number and this integer number will be stored in the location of n. The & operator is to get the location of a variable in C.
Use this :
scanf("%d",&n);
The reason :
You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.
Examples :
scanf("%d %d", &a, &b);
printf("%d %d", a, b);
As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.
But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.

Cannot change number in array into one I want [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 4 years ago.
Improve this question
I have little problem here. Ever since I used srand command I no longer get output I want.
I have to create program that will create array not matter how long.. I chose 5. Then it has to create random numbers into it and 5th number in it has to be 0 and then it has to count all five numbers together. I was sucessful and I did even use some printfs to check if arr[5] is zero. It is. In output I receieve this: 5random numbers (that ones that were created into array) 0 (to check if command where i set arr[5] really set it to zero and result which only count all 5random numbers together but without changing 5th arr into 0. Any ideas why? Thanks!
Code looks like this:
#include <stdio.h>
#include <time.h>
main()
{
srand(time(NULL));
int result,i;
int arr[5];
for (i=0;i<5;i++)
{
arr[i] = rand() % 10+1;
printf("%d ",arr[i]);
}
arr[5]=0;
printf("\n");
printf("%d\n",arr[5]);
i=0;
for(;i<5;i++)
{
result +=arr[i];
}
printf("%d\n",result);
printf("%d\n",arr[5]);
}
The declaration int arr[5] gives an array with five elements numbered from 0 to 4 inclusive. Accessing the 6th element, arr[5], is undefined.
If you want five elements and a "sentinel" (the zero marker), you could define arr as
int arr[6];
You should probably also initialize result to 0 otherwise its value is undefined since it's a local variable (in fact, the meaning of the whole program is, strictly speaking, undefined in this case).

Segmentaion fault in c while displaying array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
I have to take 'n' lines of character array(size m), which will have numbers only, and i have to put the numbers in a 2-d integer array.
I am getting segmentation fault while displaying the integer array for second time.
int t,m,n,i,j,pix[182][182];
char ch,pixel[183];
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&m); //take n and m
for(i=0;i<n;i++){
printf("\n");
scanf("%s",pixel); //take character array
for(j=0;j<m;j++){
pix[i][j]=pixel[j]-48; //put numbers in integer array
dis[i][j]=0;
printf("%d ",pix[i][j]); //no error here
}
}
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<m;j++)
printf("%d",pix[i][j]); //segmentation fault after n-1 lines are displayed
What is the problem?
Your code makes no effort to check for array boundaries. You need to check that m and n are less than 182 before proceeding. You should also use a method that protects against a buffer overrun when reading the pixel array - e.g fgets(pixel, sizeof(pixel), stdin). Otherwise, depending on the values on m and n you could have a buffer overrun with unpredictable results.
Your example also did not show the definition of the dis array, but you need to do a boundary check there as well.
Aside from that, I am guessing that your input is not laid out quite like your program expects. Performing array boundary checks and asserting as soon as they fail will help you find the discrepancy much quicker.

print the changed variable before the calculation is done [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Resources