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?
Related
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 1 year ago.
Improve this question
Can someone please show or tell how to fix my code so that it can determine even numbers. Am new to for loops and C.
EDIT: please paste code here instead of image.
You could have just posted the code along with your question but man I could hardly understand your code so I'll make some silly assumptions about what you were trying to do.
1)
printf("even number is %d",);
Firstly I am doubly sure that this did not compile because of the hanging comma, number two removing the comma will either print rubbish or cause the entire program to crash because that %d is supposed to be accompanied by an integer argument for example:
printf("even number is %d", a);
It has to do with the way C handles variadic arguments.
2)
Instead of handling the input gotten from scanf you went on to check if i is an even number which makes no sense, of course the if statement there checks if it is an even number but then there's no need for asking for input.
3)
I suggest changing your code to this:
#include <stdio.h>
int main()
{
int a, i = 0; //remove one of the variables
printf("Enter 10 positive values\n");
while (i < 10)
{
printf("Enter a number:");
if(scanf("%d", &a) != 1) //ask for input first and check if scanf failed
{
printf("An error occured\n"); /*now scanf will push back the string or whatever it read back in the stdin stream
if it encounters a non integer value ('d' for example) and return 0 if this happens ther's something you can do about that but I'm not going to bother going into that
now such an error can happen because of other reasons do this research on your own*/
return 1;
}
if (a < 0) //check if a is positive
{
printf("%d is not positive please enter an even number\n", a); //print an error message if a is not positive
continue; //go back to the beginning of the loop
}
else
{
if ((a % 2) == 0)
{
printf("%d is an even number\n", a);
}
else
{
printf("%d is not an even number\n", a);
}
i++;
}
}
printf("Done!\n");
return 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 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.
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.