For loop scans one less time in c -
the user enters string of characters, before enter size of string. have read , count how many times each letter entered.
here code:
#include <stdio.h> char ab[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; //size = 26 int main(void) { int i, j, size, counter[26]; char temp; for(i=0; i<26; i++) { counter[i]=0; } scanf("%d",&size); for(i=0; i<size; i++) { scanf("%c",&temp); for(j=0; j<26; j++) { if(ab[j]==temp) { counter[j]++; break; } } } for(i=0; i<26; i++) { printf("we have %d %c\n",counter[i],ab[i]); } return 0; } and here problem:
in given code loop reads executes 1 last time. example if enter 7 execute 6 times instead of 7 if starts 0. know problem is?
for(i=0; i<size; i++){ will loop 7 times when size 7.
your problem follows:
you enter number for
scanf("%d",&size); and press enter. above scanf scans number , leaves newline character('\n') in standard input stream. in first iteration of first loop,
scanf("%c",&temp); sees newline character , consumes thus, making think loop executes 1 less time. can verify adding
printf("got '%c'", temp); after scanf in loop.
fix using
scanf(" %c",&temp); the space before %c discards whitespace characters including none until first non-whitespace character.
Comments
Post a Comment