Remove the ampersand from
printf("Those integers sum to %1d.\n", &sum);
it should be
printf("Those integers sum to %ld.\n", sum);
Edit As others pointed out, the one in %1d is a typo, and it causes your scanf to read a one-digit int value. Replace it with %ld ('ell' for 'long'). Similary in printf the 'l' modifier tells the function what size of int it got to print.
While loop in C exited even when the condition is not true - Stack Overflow
c - Is using a while block to do nothing a bad thing? - Stack Overflow
c - While loop using a variable with no condition - Stack Overflow
I really don't get while, do-while, and for loops in C.
Videos
Remove the ampersand from
printf("Those integers sum to %1d.\n", &sum);
it should be
printf("Those integers sum to %ld.\n", sum);
Edit As others pointed out, the one in %1d is a typo, and it causes your scanf to read a one-digit int value. Replace it with %ld ('ell' for 'long'). Similary in printf the 'l' modifier tells the function what size of int it got to print.
But the problem is I cannot find a confirmation or explanation for this anywhere, of why isn't the check for the while loop checking if status is that exact integer "1".
It is. And status is the return value from scanf, which is the number of fields read. That will be one if and only if one valid field was read.
Not at all - I believe you'll find do-nothing loops like these in K&R, so that's about as official as it gets.
It's a matter of personal preference, but I prefer my do-nothing loops like this:
while(something());
Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:
while(something())
;
Still others prefer to use the brackets with nothing inside, as you have done:
while(something())
{
}
It's all valid - you'll just have to pick the style you like and stick with it.
I think it is perfectly acceptable.
I would either write it:
//skip all spaces
while ((c = getchar()) == ' ') {}
to make it obvious that this one line of code does one thing.
Or I would write it like this:
while ((c = getchar()) == ' ') {
//no processing required for spaces
}
so that it matches the rest of your code's format.
Personally, I am not a fan of the
while ((c = getchar()) == ' ');
format. I think it is to easy to overlook the semi-colon.
The condition in a while loop can be any expression of scalar (numeric or pointer) type. The condition is treated as false if the result of evaluating the expression is equal to zero, true if it's non-zero. (For a pointer expression, a null pointer is equal to zero).
So while (number) means while (number != 0).
As a matter of style, I prefer to use an explicit comparison unless the variable is logically a Boolean condition (either something of type bool or _Bool, or something of some integer type whose only meaning values are true and false) -- but not everyone shares my opinion, and while (foo) is a very common way to write while (foo != 0).
The same applies to the condition in an if, a do-while, or a for statement.
Note that in your example:
int number = 0;
while(number) {
// a bunch of code
}
the body of the loop will never execute, because number is equal to zero when the loop is entered. More realistically, you might have:
int number = some_value;
while (number) {
// a bunch of code *that can change the value of number*
}
Any place in C where a Boolean value is required, any number will be evaluated like this:
- zero โ false
- not zero โ true
I can't seem to understand how can people come up what number they specifically need in the condition part. I have watched a couple of yt tutorials but they include topics that we have yet to discuss, they kept mentioning arrays but we haven't discussed that yet.
For context: I'm a freshman in college majoring in computer science. I have a major subject called "Fundamentals of Programming," where we're using the C language. We've discussed basic input and output, variables, data types, if statements, switch statements, etc. Currently, we're covering loop statements, and our next topics will be arrays and functions.
Do programmers follow a pattern in determining what equation to put in the condition part in for loops? How do they easily come up with it? How do they know what to put?
If I have a while (true) statement that has an if function in it like this:
while (true)
{
if (n > 8)
{
printf("hi");
}
}
When the if statement is false (n is smaller than 8), the code just does nothing, it seems like the code stays in the while true statement and keeps asking if the if statement is true or false. How do you make the while true command stop and go to the next line of code when it's finished?
Thank you.
There's no iteration where both of your conditions become evaluated to false at a certain point, hence the loop doesn't stop.
You can easily investigate that behavior by stepping through your code using a debugger, and watch how the variable values change.
Loop iterations
x=1,y=2,z=0, condition:truex=2,y=2,z=1, condition:truex=3,y=2,z=2, condition:true
. . . and so on
The condition never evaluates to false, and leads to infinite loop. Consider changing to and operator to make the loop finite, or maybe change some values.
while (x != y && z != y) {
Output
x: 1
z: 0
From K&R chapter 1
#include <stdio.h>
int main (void)
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
} I run the program from Windows command line and I can enter:
Input: 5
5
Input: god help me
god help me
intput: djkslf4o3
djkslf4o3
and so on.
The program does not terminate unless I press ctrl-z(followed by /n) or ctrl-c (using windows command line). I also read from another source that ctrl-z is actually "signalling EOF", causing getchar() to return -1 which is EOF's value (please fact check me).
I see this in the terminal and it contradicts my (obviously wrong) understanding of what exactly EOF is doing and what its purpose is.
In the case I type 45 and hit enter: I assume that after putchar(c) is called twice in the loop, EOF is returned by getchar(). The while loop's condition is now false. I cannot reconcile, my conceptualization of the necessity of EOF acting as the brakes in a senseโ I type 45 into the terminal and I get only 45 back and not 45 followed by an ongoing stream of random bytes
with
my understanding of the program as a whole where I would like to assert that after the while loop's condition evaluates to false, the program would terminate. But it doesn't terminate. Does this suggest that we haven't exited the loop and EOF is not being returned by getchar(), after reading my input 45? But then how does the putchar() know when to stop?
Is windows thinking ahead for me and running the program over again with every successive input into the terminal? Am I misunderstanding the while loop?
Also, if it is indeed the case "that '^z\n' (windows) is actually signalling EOF, causing getchar() to return -1", considering my observation that this terminates the program, this confuses me again when considering the former logic. If this does indeed terminate the loop by causing getchar() to return -1, is it not so that the loop also needs to be terminated for every successive input in order for the input x into the terminal, to only be output as x and not x followed by random garbage in memory?
Would greatly appreciate any help thanks.
As beginner in C .i feel like its underrated since it guarantees running at least once , or is just a leftover from textbooks ??
while (condition);
is the same as
while (condition)
{
}
It can be used for waiting loops, e.g.:
while (!isLightGreen()); // waits until isLightGreen() returns true
go();
It means the body of the loop is empty. Typically this pattern is used when the condition itself does some work.
For example, this loop can copy bytes within the condition:
while ( '\0' != (*pt++ = *ps++))
;
If you're using a semicolon, it's a good idea to put it on a separate line so that it looks less like a mistake. I personally tend to use empty braces -- {}, and sometimes a comment that the empty block is intentional.
Edit:
In the second comment, Tom Anderson notes an improvement over a lone semicolon. Google's C++ style guide recommends either this or {}.
while ( '\0' != (*pt++ = *ps++))
continue;
I'm making a link list to rearrange some letters to point to each other in alphabetical order. When I run the code in Command prompt it does not show any errors however no output is given. I tested my code with some print statements to see where the error is and I saw that everything before the while condition gets executed. I also think I made mistakes in inserting strings into the nodes as well so that might also be a factor. Anyways can someone help me out, please?
#include <stdio.h>
#include <stdlib.h>
struct studentname
{
char letter;
struct studentname *next;
};
typedef struct studentname STUDENTName;
typedef STUDENTName *STUDENTNamePtr;
int main()
{
//creating 5 empty nodes STUDENTNamePtr node1 = (STUDENTName\*)malloc(sizeof(STUDENTName)); STUDENTNamePtr node2 = (STUDENTName\*)malloc(sizeof(STUDENTName)); STUDENTNamePtr node3 = (STUDENTName\*)malloc(sizeof(STUDENTName)); STUDENTNamePtr node4 = (STUDENTName\*)malloc(sizeof(STUDENTName)); STUDENTNamePtr node5 = (STUDENTName\*)malloc(sizeof(STUDENTName)); //fill the values ----> s,e,n,a,d node1->letter = 's'; node1->next = NULL; node2->letter = 'e'; node2->next = NULL; node3->letter = 'n'; node3->next = NULL; node4->letter = 'a'; node4->next = NULL; node5->letter = 'd'; node5->next = NULL; //linking ----> a,d,e,n,s node4->next = node5; // a -> d node5->next = node2; // d -> e node2->next = node3; // e -> n node3->next = node1; // n -> s
//printing
STUDENTNamePtr current;
current = node4;
while(current != NULL)
{
printf("%s--->", current->letter);
current = current->next;
}
printf("NULL\\n");
return 0;}