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 5 years ago.
Improve this question
So basically I was creating a program to ask the user how many times they wanted to test the program.But I couldnt figure out the problem with my for loop. So:
If the user wants to test the program 3 times, it should ask for the value of a 3 times only and it should quit after.
This is my code as follows:
#include <stdio.h>
int main()
{
int test;
printf("How many times do you want to test the program?");
scanf("%d", &test);
test = 0; // Reinitializing the test from 0
for (test=0; test=>1; test++) //I cant figure out whats going on with the for loop.
{
printf("Enter the value of a: \n");
scanf("%d", &test);
;
}
return 0;
}
The output should be:
"How many times do you want to test the program": 3
Enter the value of a : any numerical value
Enter the value of a: any numerical value
Enter the value of a: any numerical value
(exit)
In this section of your code:
scanf("%d", &test);
test = 0; // Reinitializing the test from 0
for (test=0; test=>1; test++)
First, memory owned by test is populated with a value entered by user. (this is OK)
Next, you nullify that new value in memory by setting test to zero. (this is not OK)
finally the construction of your loop statement is incorrect.
In a correct version of your for loop, test should be a value used as a limit against which an index is tested as that index is incremented across a range of values, for example, from 0 to some positive value.
You probably intended:
scanf("%d", &test);
//test = 0; // Reinitializing the test from 0 (leave this out)
for(int i = 0; i <= test; i++)
{
...
Where a separate index value (i) is incremented and tested against the limit test.
Related
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 10 months ago.
Improve this question
I am writing a CRUD program in C and at one point the user is asked to input an employee's code, which was previously stored in an array called "codes" in an employee registration section of the program, in order to register an employee's vehicle. The program should only continue if the user input is identical to an element of the codes array. Both user input and elements of the array are properly formatted, so there should be no differences other than the actual code.
I debugged by trying the value 1234 for the employee's code, which is successfully stored in the codes array, then I tried registering a vehicle by typing 1234, but the function I wrote that does the checking always return 0, so I'm thinking there is a flaw in the logic.
Variables:
char codes[100][256];
char owner[256];
Function to check if user input is indeed in any element of the array codes, returns 1 if it finds a match, or 0 at the end.
int checkOwner(char t_code[])
{
for (int i = 0; i < indice; ++i)
{
if(!strcmp(t_code, codes[i])) {
return 1;
}
}
return 0;
}
Input processing:
do {
printf("Type owner's code: ");
fgets(owner, sizeof(owner), stdin);
owner[strcspn(owner, "\n")] = '\0';
if(!checkOwner(owner))
printf("No employee with that code, try again.\n");
} while(!checkOwner(owner));
I think the "logic flaw" stands in the for statement:
for (int i = 0; i < indice; ++i)
From the logic I see you want to go through all the codes you actually registered. However, at each iteration you would like to go to the next "line", but you only update i by one.
for (int i = 0; i < indice; i+=256)
should solve the problem hopefully, though I think at this point the condition i < indice will cause problems (you could then use a second variable to count the "line number")
for (int i = 0, j = 0; j < indice; i+=256, ++j)
I would also explicitly say:
if(strcmp(t_code, codes[i]) == 0)
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 1 year ago.
Improve this question
In below given program if I put n=0, then the program is giving right answer but if I write n instead of n=0, the program is giving me wrong answer. If I put k=10 then output is 94 but the correct answer is 55. Why it is adding additional 39?
int main(){
// program to calculate the sum of 'n' numbers
int i=1,k,n;
printf("Enter number: ");
scanf("%d",&k);
do{
n+=i;
i++;
}while(i<=k);
printf("The sum is: %d",n);
return 0;
}
Your loop is adding a value to the current value of n, but you never set the initial value of n. That means its value is indeterminate, and reading an indeterminate value (in this case when you add to it), when the variable in question never had its address taken triggers undefined behavior.
Initialize n to 0 so you have a valid starting point.
int i=1, k, n=0;
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 2 years ago.
Improve this question
The following C code takes so long to compile and execute.
#include <stdio.h>
int main()
{
int max;
printf("Enter a value for max: ");
scanf("%d", &max);
for (int i=0; i<max; i++)
{
printf("%d\t", i);
}
return 0;
}
But, If I initialize the max variable with some number like
int max = 0;
The Compilation and execution is almost instantaneous. Can someone explain why?
Edit:
When I printed the value of the variable max before my input, it showed 2203648 (some garbage value). Instead of "int max = 0", if i assign
int max = 2203648;
the compilation and execution takes the same long time. But, as mentioned earlier, if i assign max say
int max = 200;
the compilation and execution is instantaneous. Does it have to do anything with the pre-assigned garbage value?
Also, this problem occurs only in windows computers, I tested with ubuntu, and the compilation and execution is instantaneous in both version of the code.
In Windows 10:
compilation and execution, as of "Enter a value for max: " appears on screen:
without variable initialization = around 8 seconds
with variable initialization = instantaneous
compiler - gcc
The scanf is failing. Check the return value.
i.e.
if (scanf("%d", &max) != 1) {
fprintf(stderr, "Unable to read max");
exit(1);
}
max is probably some large value hence the large amount of time
EDIT
The delay to see the prompt is that the printf is in a buffer and will not be displayed until the loop completes
I think variable initialization of max=0 doesn't make that great deal of a difference, but god knows why in ypur case its taking 8seconds. I think you should reinstall your GCC Compiler set your path variables correctly once more, and try the above code on a different IDE.
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).
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?