user7081818 user7081818 - 1 month ago 6
C Question

C- While loop not working

#include <stdio.h>
#include <string.h>

int main(void)
{
char str1[1000];
int i, letter, space = 0;
char ch = str1[i];

printf("Enter a sentence: ");
scanf("%[^\n]s", str1);
printf("you enter %s\n", str1);

while (i != strlen(str1)) {
if (ch != ' ') {
letter++;
} else if (ch = ' ') {
space++;
}
i++;
}
printf("%d %d", letter, space);
}


My
while
loop isn't working and I can't seem to locate the problem. I am using the terminal in ubuntu and after printing the user string, I get a blank line. I have to use Ctrl-Z to stop the script.

Answer

Mistakes I see: using uninitialised variables - local variables do not get initialised automatically.

Another is you do not read a character from the string within the loop.

The third is the unecessary and syntactically incorrect if (ch=' ') which should have been if (ch==' ')

#include<stdio.h>
#include<string.h>

int main(void){
    char str1[1000];
    int i = 0, letter = 0, space = 0;       // initialise all to 0;

    printf("Enter a sentence: ");
    scanf("%[^\n]s",str1);
    printf("you enter %s\n",str1);

    while (i!=strlen(str1)){
        char ch = str1[i];                  // move this inside the loop
        if (ch!= ' '){
            letter++;
        }else {                  // unnecessary - you already checked space
            space++;
        }
        i++;
    }
    printf("%d %d\n", letter, space);
}

Program session:

Enter a sentence: hallo my friend
you enter hallo my friend
13 2
Comments