Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

syntax problem 3

Status
Not open for further replies.

chopstick

Programmer
Apr 9, 2006
8
SG
this is part of the code:

while((ch=getchar())!='#')
{
if(ch=='.')
{
putchar('!');
count++;
}
if(ch=='!')
{
printf("!!");
count++;
}
else
putchar(ch);
}
I thought the "else" is associated with the second "if", but when it encounters "." it replaces it with "!", and it also prints ".", that means it goes to the last "putchar(ch); ". why is this?
 
If ch == '.' then the first if block gets executed. Since the next if statement isn't an else if, it always gets evaluated. Since (ch == '!') is false, the else block gets executed instead.
 
Alternatively, put a continue; after the count++ in the first if statement.
 
1. Please use [code][/code] tags when posting code.

2. if(ch=='!')
Change this to
else if(ch=='!')

It should do what you want then
Code:
while((ch=getchar())!='#')
{                          
  if(ch=='.')
  {
    putchar('!');
    count++;
  }
  else if(ch=='!')
  {
    printf("!!");
    count++;
  }
  else
  {
    putchar(ch);                     
  }
}

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top