0

Why for loop is not functioning correctly?

#include<stdio.h> main() { int i,inner,outer,tempRating,didSwap,ctr=0; char *movieName[5]={"Iron man","Iron man2","Thor","Hulk","Ant-man"}; int *movieRating[5]; char ans; char *tempMovie="This will use to sort movies"; for(i=0;i<5;i++) { printf("Did yo watched %s\n",movieName[i]); scanf("%c",&ans); if((toupper(ans))=='Y') { printf("How much do you rate it\n"); scanf("%d",&movieRating[i]); ctr++; continue; } else { movieRating[i]=-1; } } for(outer=0;outer<4;outer++) { for(inner=outer;inner<5;inner++) { if(movieRating[inner]>movieRating[outer]) { tempRating=movieRating[inner]; tempMovie=movieName[inner]; movieRating[inner]=movieRating[outer]; movieName[inner]=movieName[outer]; movieRating[outer]=tempRating; movieName[outer]=tempMovie; didSwap=1; } } if(didSwap==0) { break; } } for(i=0;i<5;i++) { printf("%s rated %d\n",movieName[i],movieRating[i]); } return 0; }

22nd Jul 2020, 9:49 AM
Pankaj Kumar
Pankaj Kumar - avatar
1 Resposta
+ 1
Add a space before %c specifier as you read the value for variable <ans>. This is needed because there's this '\n' character left in the input stream after previous input. scanf(" %c", &ans); // notice a space before %c
22nd Jul 2020, 10:25 AM
Ipang