How to write a C Program to find ASCII Value of Total Characters in a String using For loop and while loop with a practical example.
C Program to find ASCII Value of Total Characters in a String Example
This program uses For Loop to iterate each character inside a string. Inside this, we used the printf statement to print characters and their ASCII values. Please refer to the ASCII table to understand ASCII values in C Programming.
/* C Program to find ASCII Value of Total Characters in a String */ #include <stdio.h> int main() { char str[100]; printf("\n Please Enter any String : "); scanf("%s", str); for( int i = 0; str[i] != ‘\0’; i++) { printf(" The ASCII Value of Character %c = %d \n", str[i], str[i]); } return 0; }
OUTPUT
ANALYSIS
str[] = python
For Loop First Iteration: for( int i = 0; str[i] != ‘\0’; i++)
The condition is True because str[0] = p. So, the compiler will execute the printf statement.
Do the same for the remaining For Loop iterations.
Program to find ASCII Value of Total Characters in a String using While loop
In this ASCII values C program, We replaced the For Loop with While Loop.
/* C Program to find ASCII Values of Total Characters in a String */ #include <stdio.h> int main() { char str[100]; int i = 0; printf("\n Please Enter any String : "); scanf("%s", str); while( str[i] != '\0') { printf(" The ASCII Value of Character %c = %d \n", str[i], str[i]); i++; } return 0; }
OUTPUT