Understanding Simple For Loop Code in C [closed] - c

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 6 years ago.
Improve this question
I'm beginner in C programming (just started) and i need help from you to understand the output of this very simple code:
int main()
{
int x=1;
for (;x<=10;x++);
printf("%d\n",x);
return 0;
}
output is:
11
the same output if x value is <=11
and if x value is 12 or more, it prints the exact value of x (ex: if int x=12; the output is 12).
how did the computer understand this code?

So,
int main()
{
int x=1; // line 1
for (;x<=10;x++); // line 2
printf("%d\n",x); // line 3
return 0; // line 4
}
Line 1 initializes x to 1.
Line 2 keeps increasing x by 1 until it reaches 11. The first semicolon indicates "don't do anything before starting the loop", x<=10 indicates keep going until x > 10 (so when x = 11) and x++ means increase x by 1 each time. If x >= 11, this line gets basically skipped because x is already greater than 10.
Line 3 prints out x to the command line (in this case, x = 11 if x started out less than 11 or just x if x started at >= 11 due to the previous line)
Line 4 means the program was successful, exit the program.

for is this:
for(*init-expr*; *test-expr*; *update-expr*)
*body-statement*
Or rather, commonly, it can be decribed like this:
*init-expr*;
while(*test-expr*){
*body-statement*
*update-expr*;
}
and, your for statement is followed by a semicolon, where body-statement is.So, it is a "null statement", just loop and update x, when finishes the loop, just print the x after loop, so, the output is 11.

Related

Trouble starting an algorithm [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm having trouble on thinking of away to attack this problem.
X is defined below. For n=1,x=0.5,n=2,x=0.833.As you add more terms, X increases. Calculate n for which X becomes larger than 4. First write the algorithm and then implement the code in C.
x= 1/2+1/3+...1/n+1 answer: n = 83
The only thing I'm sure of is that it uses a for loop.At first I was thinking something like
For(int i = 0; i <= n.....
That doesn't seem close though.I dunno..Can I get a hint on where to start?
You will obviously compute the partial sums X.n and stop when X.n<4 and X.n+1>4.
To compute the partial sums, keep an accumulator variable and add the fractions one after the other
n= 0
S= 0
// Repeat the following instructions
n+= 1
S+= 1/(n+1) // Now, S = X.n
Remains to find the stopping condition. As the value of S goes increasing from 0, we will stop as soon as S exceeds 4. In other words, continue as long as S remains below 4.
n= 0
S= 0
while S < 4
n+= 1
S+= 1/(n+1) // Now, S = X.n
Translate that to C syntax.
Remains to look closer at the possibility that X.n = 4.

C-preprocessor #define SQR(x) ( x * x ) [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 years ago.
Improve this question
I think I'm going crazy. I'm learning C-preprocessor and I can't figure this problem out, I defined SQR(x) (X*X) purposely without brackets
#include <stdio.h>
#define SQR(x) (x * x)
int main()
{
int counter; /* counter for loop */
for(counter = 0; counter < 5; ++counter)
{
printf("x %d, x squared %d\n",counter+1, SQR(counter+1))
}
return (0);
}
In one moment in loop counter = 3. Then it should be 3 + 1 * 3 + 1 and that is equal to 7, but the output says 5.
Here is output of the code above:
x 1, x squared 1
x 2, x squared 3
x 3, x squared 5
x 4, x squared 7
x 5, x squared 9
Process returned 0 (0x0) execution time : 0.020 s
Press any key to continue.
I'm clearly missing something but I can't figure it out.
When counter=3, it prints as 4 because you print counter+1. Use:
printf("x %d, x squared %d\n",counter, SQR(counter+1));
to see what the actual value of counter is.
Aside from the most obvious error pointed out in Ignaus' answer, you have a second, more insidious and more dangerous error here. Do the substitution that the preprocessor will do on SQR:
SQR(counter+1)
becomes:
counter+1 * counter+1
which will be executed as if it were written like this:
counter + (1 * counter) + 1
That is obviously incorrect and not what you intended. With macros, you should always enclose the arguments in parentheses. So your macro should look like this:
#define SQR(x) ((x) * (x))
Now do the substitution again and you get:
((counter+1) * (counter+1))
which is correct. Make it a habit to always include macro arguments in parentheses to avoid these sorts of errors.

Trouble with mod C [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 7 years ago.
Improve this question
I just started doing codeforces problems, I started with problem 4-A (Watermelon), in which given an int x number of kilos the program will print "YES" if when you split the watermelon in two halves, each one has an even number of kilos, if not "NO".
My problem here is that I get "YES" when the input is 5, and it should be "NO"
Here is my code:
#include <stdio.h>
int main (int x) {
if((x/2) % 2 == 0) {
printf("YES");
}else {
printf("NO");
}
return 0;
}
The problem has nothing to do with mod, but with parameter passing.
The typical prototype for main is
int main(int argument_count, char *arg_list[], ...);
Calling my_exe 5 will set the first parameter x (argument_count) as 2, and the next unused parameter
arg_list[0] = "my_exe", // the first (0th) argument is the executable name
arg_list[1] = "5" // rest of parameters as arrays of chars
Calling my_exe without parameters sets x = 1 giving YES
Also if the argument x is a character '5' with the decimal value of 53 (0x35), the result is YES. This would be rather unconventional behavior, but definitely possible within some undisclosed IDE or coding framework.
Since the argument is an int then the division the remainder will be left. That is: 5 / 2 will result in a 2. Then that 2 mod 2 will give you a zero. What you should dp is to just put x % 2 inside the 'if' statement. So, with that 5 % 2 will give you a '1' which is thenn different to zero
if((x/2) % 2 == 0)
This condition is why you get yes for 5 as 5/2 is 2(as it is int) and 2%2 is 0.
just this will work -
if(x%2==0)
Since you are performing operation with integers, (5/2)=2, Hence you are getting "YES" as the output.Try this codeint main (int x) {
if(x % 4 == 0) {
printf("YES");
}else {
printf("NO");
}
return 0;
} If the condition is true, it will mean that the halves are even as well.

C - sscanf() %d picking up zero and causing destination &curritem.stock to be NULL [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 7 years ago.
Improve this question
sscanf() is great for the problem i'm facing, but it's doing something unexpected.
tmp is a line read in from a file, i need to parse out parts of the line into separate pieces of data. curritem is a struct with int dollar, int cent, cat[], int stock, and int history[].
The odd issue i'm having is that when %d picks up a double zero (00), it appropriately inserts integer zero into destination, but upon confronting a single zero (0), the integer is not added appropriately to the destination; for example, while collecting data pertaining to history[], all is well, adding 1, 4, 8, 2, 13, etc. to the array, but a single zero cuts everything off there, as if NULL terminated at that point, which i presume is related.
The code:
sscanf(tmp, "%d.%d%s %d %d %d", &curritem.dollar, &curritem.cent,
curritem.cat, &curritem.stock, &curritem.history[0],
&curritem.history[1]);
I have left out some indices of curritem.history[], as it clutters the necessary information.
Example of what i should get, if all integers were added correctly:
curritem.history[0...11] = 5 2 6 1 0 11 9 0 15 0 7 10
What actually results as of right now:
curritem.history[0...11] = 5 2 6 1
Something dies when sscanf() sees a single '0' via %d and adds that to &struct.intarray[n]
Any ideas?
Try not to recommend an entirely different solution to my general program function, sscanf() is working wonders in every other aspect.
Thank you for your time!
EDIT:
A snippet of exact input:
WL162343Fleece-Lined Double L Jeans 49.95PANTS 3 8 1 0 1 0 7 1 5 2 10 2 6
All information is acquired successfully until after the category- in this case, 'PANTS'.
With this example, my int array called history should hold the values
3 8 1 0 1 0 7 1 5 2 10 2 6
But upon printing every item in the array:
int n = 0;
for (n = 0; curritem.history[n]; n++) {
printf("%i ", curritem.history[n]);
}
The following output results:
3 8 1
EDIT:
The 'for' loop used for printing is incapable of distinguishing between an integer '0' and a null-termination of the array. Annoying.
What do you think that curritem.history[n] will return in the for's condition when it contains zero?

using goto keyword in C [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 9 years ago.
Improve this question
# include <stdio.h>
int main()
{
int a=5;
begin:
if(a)
printf("%d\n",a);
a--;
goto begin;
return 0;
}
When a becomes 0 then if condition will not execute then why the output is going to be infinty in this code means
output -
5
4
3
2
1
0
-1
-2
and so on endless
If the program really does print 0 for you then there might be a serious problem with your compiler (or even your machine...). My suspicion is that it doesn't print 0, but your question is really why the program loops infinitely.
This is because the if-body only contains the print statement. So when a reaches 0 it isn't printed but the lines
a--;
goto begin;
are still executed. The machine will obey, go back to begin and the loop continues. The quickest fix is to put braces around all the statements you want executed when a != 0:
if(a){
printf("%d\n",a);
a--;
goto begin;
}
return 0;
This will make the program only loop until a is 0, after which it returns.
But the real problem is: don't use goto (for this)! This is a perfect situation to use a while loop:
while(a--){
printf("%d\n", a);
}
return 0;
(The braces around the while-body are not even strictly necessary here, but just good practice)
Its because after the if the goto statement is again executed and then the value of a has already become other than 0 . Now, again you get the goto statement and therefore if goes on executing and printing negative values.
Look at it this way :-
The statement
printf("%d\n",a);
is executed only when condition in if is true. TRUE here refers to anything not equal to 0 so, the printf is not executed when a is 0, while it executes for any other value. Now, a-- and goto are executed outside if so they are executed again and again making the condition in if true always and negative values are printed infinitely.
Nevertheless,
My question is , why are you using goto?
if a==1 -> Evaluates to TRUE
if a==0 -> Evaluates to FALSE
if a==-1 -> Evaluates to TRUE
etc.
Therefore it will display numbers in descending order, except 0 which will not display.

Resources