Reputation: 4940
Im new to C language , been doing in it for hour but i found strange behavior of loop iterations this code
int main(int argc, char** argv)
{
int c;
int big;
int small;
while(c=getchar())
{
if(c>='A' && c<='Z');
big++;
printf("%d",big);
}
printf("end");
}
should increment int big whenever there is a upper case character. But it always print big numbers like 5452 and so on , did i miss something about iteration in c language or there is a bug in my simple code?
Upvotes: 1
Views: 267
Reputation: 22224
You need to initialize big
and the other variables to 0 in your case :
int c = 0;
int big = 0;
int small = 0;
Otherwise these variables will contain "random" values. This is a form of undefined behaviour that you will encounter a lot in C/C++.
Also these lines in your code are probably not doing what you expect
if(c>='A' && c<='Z');
big++;
There is an empty statement at the end of the if. Remove the semicolon :
if(c>='A' && c<='Z')
big++;
An extra problem is printing big in the while loop. getchar()
will return any character you type including space. printf("%d",big);
will be executed every time you type a character not every time you type an upper case or non white space char. So if you type "A A" you will get "112" There are a few ways to sort this. One solution :
if (!isspace(c)) {
printf("%d", big);
}
Upvotes: 4
Reputation: 75062
You have junk semicolon and big++
is executed regardless of c>='A' && c<='Z'
.
You also have to initialize big
.
Moreover, this code depends on the character code, so you should use isupper
if it is not banned.
#include <stdio.h>
#include <ctype.h>
int main(int argc, char** argv) {
int c;
int big = 0;
int small;
while(c=getchar()){ /* this loop should go infinitely in most case : compare with EOF to detect the end of input */
if(isupper(c))
big++;
printf("%d",big); /* maybe you want to print newline after this */
}
printf("end");
return 0;
}
Upvotes: 5
Reputation: 16607
int big;
big
is just declared not intialized , thus giving garbage value.
int big=0; // also initialize small
Would work.
And
if(c>='A' && c<='Z');
^ will terminate if statement then and there
Due to ;
big
will be incrementated even if the if
condition is false
.Remove ;
after if
.
Upvotes: 4