In the section array in C I have discussed about array. This program is based on the concept of array.In this program I am going to discuss how to count blank spaces in character array can determined or found.By looking in the character array or sentence one can easily count the blank spaces.Now think how it could be done by using C program.Before going to code given below think of your way to find and match it with the code below.
“Here’s the code snippets to count blank spaces in character array:”
/*This program counts the number of blank spaces present in the character array:*/
char ar;//variable for storing character array
int i,c=0;//c holds count of spaces
printf("Enter a sentence:\n");
scanf("%[^\n]",ar); //input of character array
for(i=0;ar[i]!='\0';i++) //loop to count blank spaces
if(ar[i]==32) //comparing each element with ASCII of blank space
/*instead of above if statement you can use
if(ar[i]==' ') */
printf("Total spaces in the entered sentence=%d",c);//displaying result
Note:Program compiled in Dev C++ compiler.
Enter a sentence:
Quick Solution is the best site for learning C programming
Total spaces in the entered sentence=9
If you want to suggest other solution regarding this question you can reply or send your solution to leave reply space provided below so that user can get multiple solutions.
- In the program array “ar” of character type is taken for storing the character array or sentence entered by the user. Variable “c” is used to hold the count of blank spaces in the sentence.
- Initially “c” is assigned to 0 to avoid garbage value in the variable.
- In the for loop each character is compared with the ASCII value of blank space i.e. 32 ,If matched then count of blank space is incremented by 1.
- Instead of ASCII value of blank space you can use blank space symbol as shown in the code in comment line.
- This for loop will continue until getting the last character i.e. Null character(‘\0’).
- Finally outside the for loop result is displayed.