C: printing for loop [closed] - c

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 4 years ago.
Improve this question
Trying to complete a larger task in C, but for some reason this one small simple (or so I thought) piece of the puzzle isn't working.
I want to print 0 to 9, each on individual lines:
#include <stdio.h>
#include <stdlib.h>
#define MAX 9
int main()
{
for (int counter = 0; counter == MAX; counter++)
printf("%d \n", counter);
return 0;
}
However, nothing* happens when I build & run. I've been staring it for over an hour...
*Nothing = Process returned 0 (0x0)...

My guess is that you think the statement after the first semicolon in the for loop is the condition that stops the loop when it is true. Actually, that statement has to be true/non-zero to the loop to execute.
Try for(int counter = 0; counter <= MAX; counter++) instead.

The for loop will keep on running so long as the checking expression counter == MAX remains true. Which is never the case in this code snippet. You probably meant counter != MAX.
This would print 0 - 8 and not 0 -9. For that you would need to make MAX 10 or change the loop condition to counter <= MAX.

Change counter == MAX to counter <= MAX. So in this case your loop will run until counter is less than or equal to MAX

The idea behind the middle area in the for is the condition for the loop to continue, and not to stop if it is true. While the condition returning true value, the loop will continue. In your case the condition have to look like this one: counter <= MAX. And in the whole loop:
for (int counter = 0; counter <= MAX; counter++)
printf("%d \n", counter);

There are two things that might prevent this code from running.
First thing is what everyone else have pointed. The condition is forever false in the conditional part of the for loop in
for(initialization; condition; increment/decrement)
{
//code here
}
the correct condition seems to be
counter <= MAX
Second thing might be that you are using an old compiler in which case you need to initialize the counter at the beginning of the code before performing any other action. Initialization is not allowed within for in many old compilers. The place where it would be most suited would be right after the opening braces { of the main() function block.
Thus the best approach would be
#include <stdio.h>
#include <stdlib.h>
#define MAX 9
int main()
{
int counter;
for (counter = 0; counter <= MAX; counter++)
printf("%d \n", counter);
return 0;
}

Related

The logic of nested loops in C [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 2 years ago.
Improve this question
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n, j++)
{
printf("#");
}
printf("\n");
}
The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.
The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.
The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).
The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.
Is that correct? Thank you very much in advance!
Yes, your explanation is spot on.
With a minor mistake:
It will run until the condition is false (i > n).
The condition is false when i >= n.
And what I assume it's a typo:
for (int j = 0; j < n, j++);
// ^
// |
remove the ;

Which loop is better? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Am a beginner at C here; Would like to ask which of the following 2 code is better for printing odd integers between 1 and given number?
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i+=2)
printf("%d ", i);
printf("\n");
}
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i++)
if (i%2 != 0)
printf("%d ", i);
printf("\n");
}
If neither can be said to be clearly "better", what are the different trade-offs between the versions?
Use the First Loop if n is not the extreme case like INT_MAX and also when i starts from an odd integer, Since it already skips half the number iterations.
Else use the Second Loop because the first will become infinite loop if n = INT_MAX.
Absolutely the first one.
Reasons:
- less lines of code
- branching statements (if, if else, switch cases, ...) are mainly avoided if there is other ways of handling the situation.
- time complexity of both algorithms are the same O(n). So this is mainly a matter of which code is more beatifull. And always remember, a code that is more readable is prettier.
EDIT
the fact that on the edge the first solution has undefined behavior is obvious. but these input validations must be checked outside the algorithm part. and it's much recommended that you DO NOT mix validation codes with your logic. easily you can check for i at first of the function and print INT_MAX if i==INT_MAX-1 or i==INT_MAX
Functionally, they are the same, so it really doesn't matter all that much unless you really need max performance.
However, the solution where you skip the if statement would be a lot efficient. You're skipping half the numbers and don't need to check a condition with modulus.
Both loops have undefined behavior if n == INT_MAX because of arithmetic overflow.
The first loop will potentially give you better performance
The second loop is potentially more readable (for a beginner) and less error prone if you later change the code to start from an arbitrary value.
I would use braces around the for body as it is not a simple one line statement and spaces around binary operators to improve readability:
void print_odd_integers(int n) {
int i;
for (i = 1; i <= n; i++) {
if (i % 2 != 0)
printf("%d ", i);
}
printf("\n");
}
Note also that both loops will output a space after the last number before the newline, which may be incorrect.
You can address both issues with one extra test:
void print_odd_integers(int n) {
for (int i = 1; i <= n; i += 2) {
printf("%d", i);
if (i == n)
break;
}
printf("\n");
}
The second solution is the "professional" way.
One thing you could change would be the Layout:
void print_odd_integers(int n)
{
int i;
for (i=1; i<=n; i++)
{
if (i%2 != 0)
{
printf("%d\n", i);
}
}
printf("End.\n");
system("Pause"); //So you can see what you did :)
}
Have fun :)!

Why the value of i is showing at the out of the loop is 5, but in the loop the last value of i is 4? [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 5 years ago.
Improve this question
#include<stdio.h>
int main()
{
int i,n=5;
for(i=0;i<n;i++)
{
printf("in of loop the value of i is %d\n",i);
}
printf("out of loop the value of i is %d",i);
}
I can not understand why the value of i is showing at the out of the loop is 5, but in the loop the last value of i is 4.
The for loop increments the value of i at the end of the instruction block. Therefore, when i = 4, the loop runs but at the end, i = 4+1 = 5. At this point, the condition in the loop is no longer satisfied because i now equals to 5.
in the loop the last value of i is 4,then i++, i is 5, i
You can see the for loop as a disguised while loop:
for(i=0;i<5;i++)
{
do stuff;
}
is equivalent to
i=0
while(i<5){
do stuff;
i++;
}
So at the end, i=5
If you wish to execute the body of the for cycle 5
times you should simply consider to do the following correction:
for(i=0; i<=n; i++){
/*
The code here will be executed 5 times.
Subsequently the last printed value will be 5.
*/
printf("in of loop the value of i is %d\n",i);
}
What you are observing is due to a mismatch between the value of n and the condition that is evaluated to enter the for cycle. To execute five times the for
cycle n should be less or equal to 5.
In this case:
for(i=0; i<n; i++) {
printf("in of loop the value of i is %d\n",i);
}
When n is equal to 5 it doesn't fulfill the requirement to enter the for loop. The condition here is "Enter the loop if n is less than 5" but it is not considered the case if n is less or equal to 5.
So just use the relational operator "<=" if you wish to execute the cycle 5 times.

for loop in c not outputting full array [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
this is a simple question as i'm a new-comer to C. I am trying to write a script for outputting an array of the tangents of radians, of multiples of 5 from 0-60. but for some reason the for loop i have written only does this for the first element, and all other elements in the resulting array are 0.00, and it wont print them for each loop. i'm sure i've done something simple wrong with my loop, but i just can't see it.
#include <stdio.h>
#include <math.h>
float rad(float degree){
return degree*M_PI/180;
}
int main(void){
int i, j, dim=13;
float Tan[dim];
for(i=0; i<13; i++);{
j+=5;
Tan[i]=tan(rad(j));
printf("%f\n", Tan[i]);
}
return 0;
}
First of all, in your code
j+=5;
is undefined behavior, as the intial value of j is indeterminate. To elaborate, j is an automatic local variable and not initialized explicitly, so the content is indeterminate.
Then, the for loop is also buggy.
for(i=0; i<13; i++);
should be
for(i=0; i<13; i++) // no ; here
to have a meaningful loop body to be executed.
1. You have inserted a semi-colon which you shouldn't have. Change your loop to :
for(i = 0; i < 13; i++){ //erase the ; after the parenthesis
j+=5;
Tan[i] = tan(rad(j));
printf("%f\n", Tan[i]);
}
2. Initialize variable j before trying to increase it with the statement j+=5, as this will lead to undefined behaviour.
There are two problems in your code :-
1) You haven't initialized j here int i, j, dim=13;
2) The way you used for loop is as per your requirement.Remove semicolon from the for loop statement.

Why doesn't my program print the right value after a for loop? [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 7 years ago.
Improve this question
I am trying the below C code:
#include <stdio.h>
int main()
{
int i=10;
int start=25;
int end = 30;
for(i = start; i < end; i++);
{
printf("%d\n", i);
}
}
I know there is a semicolon at the end of for loop which stops the for loop iterating more than once. But I get the output '30', instead of '25'. Why am I getting this result? Variable i should retain its start value, right?
for(i = start; i < end; i++);
That code means that i is 25. The loop continues while i<30.
Then after the loop, i will be, as you wrote, 30.
Putting a semicolon at the end of loop does not stop the loop: it is executed.
In your case {} only open a different scope inside the main function.
The snippet
for(i = start; i < end; i++);
{
printf("%d\n", i);
}
is equivalent to
for(i = start; i < end; i++);
printf("%d\n", i);
Expanding further
for(i = start; i < end;)
{
i++; // This statement will execute till i < 30
}
printf("%d\n", i);
The condition i < end will evaluate to false when i will be incremented to 30 by the execution of the statement i++ inside the loop body.
Now, the statement printf("%d\n", i); will be executed and will print the value of i which is 30.
I know there is a semicolon at the end of for loop which stops the for loop iterating more than once.
That is not exactly right: semicolon after for loop becomes loop's empty body. The loop iterates five times, incrementing i in each iteration. The statement in curly braces gets executed only when the loop is over.
At that point i becomes 30, because that is your loop's post-condition (i.e. the condition that must be true in order for the loop to finish). That's what gets printed by the printf.
for(i = start; i < end; i++);
This loop will iterate for 5 times , until i becomes equal to end i.e 30. It will not stop after 1st iteration .
Due to ; the following printf is not part of loop body , but ; doesn't mean that loop will iterate for 1 time . It will iterate til condition is true but loop's body does not contain anything other than ;.
Because of the colon your program is now equivalent to:
#include <stdio.h>
int main()
{
int i=10;
int start=25;
int end = 30;
for(i = start; i < end; i++)
{
//do nothing
}
printf("%d\n", i);
}
Your loop moves i to 30 and then prints it.
The code within the braces (below for) is not part of your for loop.
In other words your loop does not have a body due to the inclusion of the semicolon at the end of the for statement.

Resources