Is it possible to run 2 while loops in the same function?
Only one of the while loops works. If I remove the first the one, the second one will work and if I remove the second one, the first one will work.
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "results.txt"
void analyseText(int character[], int i, FILE *fptr, int *sum, int a)
{
while ((i = fgetc(fptr)) != EOF)
{
if (i >= 'a' && i <= 'z')
character[(i - 'a')]++;
if (i >= 'A' && i <= 'Z')
character[(i - 'A')]++;
for (int i = 0; i < 26; i++)
{
printf("%c: %d\n", i + 'a', character[i]);
}
while (1)
{
int result = fscanf(fptr, "%d", &a);
if (result == EOF) {
break;
}
else if (result == 1) {
*sum += a;
}
else {
fscanf(fptr, "%*c");
}
}
}
}
I've ran your program and it seems the second while loop terminates the function. The second while loop will read the characters from the file and will do so until it reach the end, then will exit. Both while loop executes, but the first one executes only once and the second executes till will reach the end of the file. Maybe it is a logic bug there?
Also, are you trying to read some numbers in the second loop, the result will never pe 1 if there are only characters in the file.
You have an (almost) infinite loop inside an (almost) infinite loop, with just about the same stop condition for both.
One of them will run "forever" and when it triggers the stop condition the other will also stop, giving the appearance of just one of the loops running.
2 loops
enter infinite loop1
do some stuff one once
enter infinite loop2
do some stuff two "forever"
when you remove the inner loop
enter infinite loop1
do some stuff one "forever"
when you remove the outer loop
enter infinite loop2
do some stuff two "forever"
Related
#include<stdio.h>
int main(void)
{
int i=2,number;
printf("Enter another number greater than 5\':");
scanf("%d",number);
while (number>5);
for (; i<=3; i++)
{
printf("Hi\n");
++i;
}
printf("Enter another number greater than 5\' to continue the cycle:");
scanf("%d",number);
printf("finish");
return 0;
}
First, within the two scanf functions you need to add & to the number parameter. It is because &number gets the address of number, and the value entered by the user is stored in that address. Also, your code never leaves the loop. Try like this:
#include <stdio.h>
int main(void){
int number;
printf("Enter a number greater than 5: ");
scanf("%d",&number);
while (number>5){
for (int i = 0; i<1; i++){
printf("Hi\n");
}
printf("Enter another number to continue the cycle: ");
scanf("%d", &number);
}
printf("finish");
return 0;
}
Remember that for loop already increments the counter i by itself, so the i++ statement inside loop is unnecessary if you wanted to print "Hi!" only once (even the for loop is useless if you only wanted to print it once, but I guess you did it because you are learning).
There are several problems:
1 Incorrect usage of scanf
scanf takes format string and then addresses to variables, so it could write to memory, where the variables are located.
So correct usage is
scanf("%d",&number);
Best would be to check also return value of scanf. scanf returns count of successfully loaded arguments. So in you case
if (scanf("%d", &number) != 1) {
// print error message, or something else
}
If there were more arguments, then the condition would be different
if (scanf("%d %f %c %d", &a, &b, &c, &d) != 4) {
// ...
}
2 Infinite while loop
while (number>5); is infinite loop if number is greater then 5.
number is not changed within the loop, so the condition for while loop would be always truthy.
3 Possibly wrong incrementation of i variable in for loop
// int i = 2;
for (; i<=3; i++)
{
printf("Hi\n");
++i;
}
There is suspicious ++i; in the for loops body. This does not change the for loops behaviour, but I assume you are a beginner, so I will explain it anyway.
It will work like this:
for loop starts with no initialization (i is initialized to 2 outside of the loop)
condition i <= 3 gets evaluated to 1 (C does not have boolean [true,false], so there are used numbers instead [0 == false, anything else == true])
printf("Hi\n"); gets evaluated -> "Hi\n" gets printed
++i; gets evaluated -> i gets incremented to 3
update of for loop gets called (which is i++) -> i gets incremented to 4
condition i <= 3 gets evaluated as 0, because 4 (value of i) is greater then 3
for loop gets finished
My point here is that the i is incremented twice every loop.
So it's the same like
for(; i <= 3; i += 2) {
scanf("%d", &number);
}
I have the following code in C:
#include <stdio.h>
int main()
{
int i = 1;
while(i)
{
int index = 0;
printf("while begin\n");
for(index = 0; index < 10; index++)
{
if(index == 2)
{
continue;
}
printf("within for\n");
}
printf("while end\n");
}
printf("returned from while");
}
does the continue effect the for loop or the while loop directly? looks like once the continue is called, for loop will start to run from the beginning, should not the while loop start to run from the beginning?
continue will cause the remaining portion of the enclosing for or while loop body to be skipped. In your case, the for is the "enclosing" loop of continue and the while loop is the "enclosing" scope of the for loop.
According to (unofficial) documentation
The continue statement causes a jump, as if by goto to the end of the
loop body (it may only appear within the loop body of for, range-for,
while, and do-while loops).
To understand what continue is you should know what break does too.
So the following peace of code shows you how break and continue works:
#include <stdio.h>
int main(void){
int hours = 10;
int i=0;
for(i=0;i<hours;i++){
if(i==5){
break;
}
printf("%d ",i);
}
return 0;
}
Output:
0 1 2 3 4
As you can see, when i reaches 5 (i==5) the loop breaks.
Now let's take a look of what does continue if we replace break using the same code:
#include <stdio.h>
int main(void){
int hours = 10;
int i=0;
for(i=0;i<hours;i++){
if(i==5){
continue;
}
printf("%d ",i);
}
return 0;
}
Output:
0 1 2 3 4 6 7 8 9
As you can see it doesn't leave the loop (like when using break), instead when i reach 5 (i==5) ignore the rest of the body making the loop to start over from the point where i was last time seen.
The number 5 *is missing.
The simplest way to think about it is to say : "it goes back to the top of the loop" anything AFTER the continue won't be processed.
I am new to C as of yesterday and I am trying to create a loop that will take ten characters, then print out how many "a"s are in it. no matter how many "a"s are in the string, it prints out 0. any help would be much appreciated.
#include <stdio.h>
#include <string.h>
int main()
{
char string[10];
int c = 0;
int loop = 0;
printf("Enter a string\n");
gets(string);
for (loop = 0; loop >10; ++loop)
{
if (string[c] = 'a')
{
++c;
}
}
printf("A occurs %d times in the entered string.\n",c);
return 0;
}
I think you should read again how for loop works,
for (loop = 0; loop >10; ++loop)
^^^^^^^^
This condition of yours is false from the beginning, as loop = 0, which is not >10. Hence the for loop is never executed.
Plus, when you are comparing inside the for loop, you are using loop variable to iterate over the characters of string. And, to compare == is used, = is assignment operator. So,
if (string[c] = 'a')
this should be
if (string[loop] == 'a')
In one very good book I read, it is written that to avoid such errors, always use the comparison in the other way, for instance,
if ('a' == string[loop])
Even if you mistype and put = instead of ==, you will get an error.
As a side note, don't use gets() function. It has been deprecated. You can read about the Morris Worm to understand what effects gets() can have.
Very quickly few reviews on your code
/* Change */
for (loop = 0; loop >10; ++loop)
/* To */
for (loop = 0; loop < 10; ++loop)
/* Change */
if (string[c] = 'a')
/* To */
if (string[loop] == 'a')
/* Change */
gets(string);
/* To */
fgets(string, 10, stdin);
So I have this little while loop which seems to print out my text twice during one run.
So here is the code:
int main(void){
char cont;
int check = 1;
while(check == 1){
printf("Something");
cont = getchar();
if(cont == 'j')
check = 1;
}
}
Now the output of this is:
Something, now it waits for input
Something, Something and waits for input.
After the first print, it will print twice when I press j.
Why is that?
You press 'j' and the 'newline', so you typed two chars and loop executes twice before starting to read next line.
Your code is stuck in loop because you test check==1 and check is always 1
you can make else part
if(cont == 'j')
check = 1;
else
check =0;
It is an infinite loop. Always recheck your program.
Maybe you wanted
if(cont == 'j')
check = 0;
I have a very simple problem in C. I am trying to write a simple program that outputs multiples of 10 between 10 and 100, inclusive (ie: on the closed interval [10,100]) that skips 30 and 70 and outputs the values vertically.
Here is my code:
#include<stdio.h>
main()
{
int i=10;
do {
if(i==30||i==70)
continue;
printf("\n %d",i);
i++;
} while(i<100);
return 0;
}
The program stops at 29 skips 30 and continues into a never ending loop. What is wrong?
The problem is that when you hit the if statement, you are now skipping the increment of i. So you never reach 100!
#include<stdio.h>
main()
{
int i=10;
do {
if(i==30||i==70)
continue; //!!!! This will skip the i increment
printf("\n %d",i);
i++;
} while(i<100);
return 0;
}
I recommend a for loop:
main()
{
for (i = 10; i < 100; i++) {
if(i==30||i==70)
continue; // The for loop will do the i++ on the "continue"
printf("\n %d",i);
}
return 0;
}
mbratch correctly pointed out your problem, but you might want to consider a for loop for this sort of thing. It would have prevented this particular problem, since the increment is automatic.
I won't do the whole thing for you, since you're obviously trying to learn, but this ought to get you started:
for (i=0; i<100; i+= 1)
You'll have to change some of the numbers in that line, but hopefully you'll understand what they mean when you change them.
When i reaches 30 the continue statements moves back to the start of the loop.
And so the loop continues endlessly as i is not incremented from this point.
Your code's doing exactly what it's written to do. The continue skips the increment instruction, so the value hits 30 and gets stuck there. Move the increment to the start of the loop body, or better yet, use a for instead of a while.
Don't use continue. Instead print out the value as long as != to 30 and 70. Also iterate by 10 instead of 1 to output multiples 10.
#include<stdio.h>
main()
{
int i = 10;
do
{
if (i != 30 && i != 70)
printf("\n %d", i);
i += 10;
}
while (i <= 100); // if you want to print 100
return 0;
}
Output:
10
20
40
50
60
80
90
100
Use while (i <= 100); if you need to also print 100.
It loops forever because you continue but don't increment i.
if(i==30||i==70) {
i++;
continue;
}
or you could use a for loop like so,
#include<stdio.h>
int main()
{
int i=10;
for (; i < 100; i++)
{
if(i==30 || i==70) {
continue;
}
printf("\n %d",i);
}
return 0;
}
The reason is that i is never incremented after 30 inside the body of do..while. You'd need to increment it.
if (i == 30 || i == 70){
i++;
continue;
}