Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to print the ASCII values in a string.
In C programming, we can print the ASCII values of characters in a string by iterating through each character and using the %d format specifier to display its numeric ASCII value.
Syntax
while(str[i] != '\0') {
printf("ASCII Value of %c = %d
", str[i], str[i]);
i++;
}
String Declaration and Initialization
A string in C is an array of characters terminated by a null character '\0'.
Declaration:
char stringname[size];
Initialization methods:
- Using character constants:
char string[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
- Using string literals:
char string[10] = "Hello";
Example: Print ASCII Values of String Characters
The following program reads a string and prints the ASCII value of each character −
#include <stdio.h>
int main() {
char string[100] = "TutorialsPoint";
int i = 0;
printf("String: %s
", string);
while(string[i] != '\0') {
printf("ASCII Value of '%c' = %d
", string[i], string[i]);
i++;
}
return 0;
}
String: TutorialsPoint ASCII Value of 'T' = 84 ASCII Value of 'u' = 117 ASCII Value of 't' = 116 ASCII Value of 'o' = 111 ASCII Value of 'r' = 114 ASCII Value of 'i' = 105 ASCII Value of 'a' = 97 ASCII Value of 'l' = 108 ASCII Value of 's' = 115 ASCII Value of 'P' = 80 ASCII Value of 'o' = 111 ASCII Value of 'i' = 105 ASCII Value of 'n' = 110 ASCII Value of 't' = 116
How It Works
- The
whileloop continues until it encounters the null character'\0' - Inside the loop,
printfdisplays each character using%cand its ASCII value using%d - The same variable
string[i]produces different outputs based on the format specifier used - The counter
iincrements to move to the next character
Conclusion
Printing ASCII values of string characters in C is straightforward using a loop and format specifiers. The key is using %c for character display and %d for ASCII value conversion.
Advertisements
