"Why does it output 100?" - c

for(x=0; x<100; x++);
printf(“%d”,x);
why it gives 100
(i) Identify bug/bugs in this program segment
(ii) Write a correct version of this program segment
I tried
for(x=0; x<100; x++){
printf(“%d”,x);}
ı can see all numbers 0 to 100 but
for(x=0; x<100; x++);
printf(“%d”,x);
ı can see only 100 why ? ı dont know the reason

I can see only 100 why? I dont know the reason
Because a semi-colon terminates a statement.
To better understand what's happening, format your code properly. (Better yet, use an IDE which formats the code for you. And do not use a word processor as an IDE. Those fancy quotes in your code are syntax errors.) The original code is this:
for(x=0; x<100; x++);
printf("%d",x);
Two statements, unrelated to one another. The first one is a loop, by itself, with no loop body. It repeats, successfully doing nothing 100 times. The second statement outputs a value. Compare that to your corrected code:
for(x=0; x<100; x++) {
printf("%d",x);
}
Now what you have is a loop, the body of which contains one statement. That statement is executed 100 times, each time outputting a value.
Consistently and meaningfully formatting your code for readability is not there to help the compiler. It's there to help you. Keep your code human-readable and you, as a human, will be better able to read and understand it.

for(x=0; x<100; x++); printf(“%d”,x);
There is a semicolon between the for loop and the print. So the print is not in the loop.
x will be counted from 0 to 100. After the empty loop completes, it will print the last value (100).

Related

Understanding the reason behind a output

I am a beginner is Computer Science and I recently started learning the language C.
I was studying the for loop and in the book it was written that even if we replace the initialization;testing;incrementation statement of a for loop by any valid statement the compiler will not show any syntax error.
So now I run the following program:
#include<stdio.h>
int main()
{
int i;
int j;
for(i<4;j=5;j=0)
printf("%d",i);
return 0;
}
I have got the following output.
OUTPUT:
1616161616161616161616161616161616161616.........indefinitely
I understood why this is an indefinite loop but i am unable to understand why my PC is printing this specific output? Is there any way to understand in these above kind of programs what the system will provide us as output?
This is a case of undefined behaviour.
You have declared i so it has a memory address but haven't set the value so its value is just whatever was already in that memory address (in this case 16)
I'd guess if you ran the code multiple times (maybe with restarts between) the outputs would change.
Some more information on uninitialized variables and undefined behaviour: https://www.learncpp.com/cpp-tutorial/uninitialized-variables-and-undefined-behavior/
Looks like i was never initialized, and happens to contain 16, which the for loop is printing continuously. Note that printf does not add a new line automatically. Probably want to read the manual on how to use for.
To better understand what is going on, you can add additional debugging output to see what other variables are set to (don't forget the \n newline!) but really problem is the for loop doesn't seem right. Unless there's something going on with j that you aren't showing us, it really doesn't belong there at all.
You are defining the variable i but never initializing it, instead, you are defining the value for j but never using it.
On a for loop, first you initialize the control variable, if you haven't already done it. Then you specify the condition you use to know if you should run another iteration or not. And last but not least, change the value of the control variable so you won't have infinite loops.
An example:
#include <stdio.h>
int main()
{
// 1. we declare i as an integer starting from 1
// 2. we will keep iterating as long as i is smaller than 10
// 3. at the end of each iteration, we increment it's value by 1
for (int i = 1; i < 10; i++) {
printf("%d\n", i);
}
return 0;
}

for loop containing all equals statements C

I'm trying to understand a coding example I found in C, and one of the for loops is structured like this:
for(int x=0; int y=0; int z!=0){some code}
I am used to seeing something more like this:
for(int x=0; x < someLimit; x++){some code}
What does the mystery for loop do exactly?
You copied the statement wrong. In the program you cited in your comment there's only one for statement which approximates what you posted above:
for(time=0,count=0;remain!=0;)
In this case the "initialization" portion of the for statement is
time=0,count=0
Note that the character between the initialization of time and count is a comma, not a semicolon. This means
that both time and count are set to zero. The "test" portion of the for statement is
remain != 0
meaning that the loop will continue as long as remain is not equal to zero.
In this for statement the "increment" portion is empty - so nothing is incremented/decremented/whatever at the end of each pass through the loop.
Best of luck.
In for loop you can omit initialization part(provided you initialized your variable before) and increment/decrement part. you can have also multiple initialization like in your example x=0;y=0 and multiple increment/decrement. in your first example for loop have multiple initialization for x and y and no increment/decrement part. and z part is the condition. Please check why you are declaring z there. I am not sure about that. It would be better if you will upload full code of that example.

Understanding the logic of nested for-loops

I wrote a program where the user inputs numbers n times; the program prints out the the numbers removing all duplicates.
On the code you will see that I initialized seen = 0 at the beginning of the code and when I do so without initializing again on my for loop It won't print out the numbers correctly but when I do it will. Can somebody explain why? I would really like to understand this.
I clarified my question on the code itself. Have a look:
#include <stdio.h>
int main()
{
int arr[100];
int i, j, num, seen = 0; // here is where I first initialized it
// but I see that this is not necessary
printf("Enter Number: ");
scanf("%d", &num);
for (i=0; i<num; i++)
{
printf("Arr[%d] ", i);
scanf("%d", &arr[i]);
}
for (i=0; i<num; i++)
{
//seen = 0; If I initialize it here
// it will print out the numbers correctly
for (j=0; j<i; j++)
{
if (arr[i]==arr[j])
{
seen = 1;
break;
}
}
if (!seen)
printf("%d", arr[i]);
}
printf("\n");
}
If you don't reset seen=0 in the outer loop, the program thinks that it has seen every one after the first one that it finds.
Googling gdb tutorial yielded this that looks promising.
Think about what the value of your seen variable means.
You iterate over the array of numbers. For each number, you do the following:
Loop over the previous numbers in the array, and check whether the current number has already been seen.
Print the current number only if it hasn't already been seen.
seen should be true only if you've already seen the current number. The way your program is currently written, it remains true as long as the program continues to run, though the old value becomes irrelevant as soon as the outer loop advances to a new number.
In fact, it would be even better to move the declaration of seen (along with its initialization to 0 inside the outer loop. Since its value is not meaningful outside one iteration of the outer loop, it might as well only exist within each iteration of the outer loop.
(Running your program under a source level debugger such as gdb is one way to find errors like this, but not the only one. Re-reading your code and reasoning about what it does vs. what it should do is another useful approach. Adding printf calls to show the values of variables as the program runs is another.)
Please learn about debugger programs.
In an IDE like Visual Studio or Eclipse it is built in.
Using GCC on Linux command line it is called gdb. You compile your program with the -g flag to make GCC include debug information. Then you run gdb program-name and start and n, then hit return as it steps through the program. There are also many other commands.
With that you should be able to solve this problem and many others.

Printing in Devc

I wrote a simple code with dev but it does not return any thing.but with code block answer shows.what is the problem?
#include <stdio.h>
int main() {
int x,y,z;
scanf("%d%d",&x,&y);
while(z!=0){
z=x%y;
printf("%d",z);
}
return 0;
}
Two problems I can see:
1. Value to z is un-assigned. So garbage.
2. Value of z will not change, so it's infinite loop.
It invokes undefined behavior because z is used uninitialized.
while( z!= 0)
^
|
z is uninitialized
You may get any thing either expected or unexpected result. Program may crash also. On different compilers you may get different results, which is the case here.
in Your Code you was Assigned z but not initialized z and you are checking while(z!=0) so your code does not return value , fist assigned z to any value for example from scanf.
You are not able to see the output because it is closing the terminal / output window as soon as the program exits.
In code::block, they run a script to hold the output window until you press enter.
you can have same effect by using a getch() call at the end, before returning. this will wait for your input and give you a scope to see the result.
Besides, your program has several issues as other answers pointed out. fix them accordingly.

C program seems to skip while loop

Code seems to skip the while loop:
int i,j;
i= floor((Lx-23.61)/0.1);
j=0;
while(Nh - modSED[i][j] > 0.0){
j++;
}
if(j>0 && modSED[i][j]-Nh > Nh-modSED[i][j-1]){
fileNH=modSED[i][j-1];
}else{
fileNH=modSED[i][j];
}
It's more or less a crude linear search through an array of doubles (the i-index is preset by another part of the code and shouldn't be a problem). The code seems to misbehave when I look at GDB:
Breakpoint 1, mag (filter=4, Lx=23.930108812418158, z=0.57071772467724535, Nh=0.011911981460606383) at infopt.c:45
45 while(Nh-modSED[i][j]>0.0){
(gdb) print Nh-modSED[i][j]
$1 = 0.001911981460606383
(gdb) n
48 if(j>0 && modSED[i][j]-Nh > Nh-modSED[i][j-1]){
(gdb)
and it has just skipped the j++ segment, even though the while loop should evaluate to true.
Thanks,
Josh
Seems like a error creeping up due to floating point comparisons. It is well known that floating point comparisons are not very safe. Refer to these for more info:
http://floating-point-gui.de/errors/comparison/
How dangerous is it to compare floating point values?
The second link has a very detailed explanation on Floating Point Operations
The external 2D array modSED was declared with the wrong dimensions (different from the c file in which it was initialized), so either the program, gdb, or both were confused. Fixing the dimensions of the declaration fixed the problem. (Here the problem refers to the larger issue that I wasn't getting the correct value returned from modSED.) Since GDB seemed to give the wrong output, though, I was getting hung up on the wrong part of the code.
Perhaps this in turn led to GDB seeming to defy logic and skip the while loop? (Running the program now, GDB has no trouble incrementing j and showing that it has done so.)

Resources