C program to print the ASCII values in a string.


An array of characters is called a string.

Given below is the declaration of a string −

char stringname [size];

For example, char string[50]; string of length 50 characters.

Initialization

  • Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants.
char string[10] = “Hello”:;

Accessing

There is a control string “%s” used for accessing the string till it encounters ‘\0’.

The logic we used to print the ASCII values of a given string at runtime is as follows −

while(str[i]!='\0'){
   printf("
ASCII Value of %c = %d", str[i], str[i]);    i++; }

Example

Following is the C program to print the ASCII values of a given string −

#include<stdio.h>
int main() {
   char string[50];
   int i=0;
   printf("Enter the Sentenc: ");
   gets(string);
   while(string[i]!='\0') {
      printf("
ASCII Value of %c=%d", string[i], string[i]);       i++;    }    getch();    return 0; }

Output

When the above program is executed, it produces the following output −

Enter the Sentence: Tutorials Point

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   = 32
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

Updated on: 25-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements