You are here

C program to print a string

C program to print a string: it can be printed by using various functions such as printf, puts. A string ends with '\0', it is a character used to mark end of a string. See the following code:

  1. printf("Hi there! How are you doing?");

Output:
Hi there! How are you doing?

The string which is passed as an argument to the printf function is printed. Next we will learn how to print a string which is stored in a character array.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    char z[100] = "I am learning C programming language.";
  6.  
  7.    printf("%s", z); // %s is format specifier
  8.  
  9.    return 0;
  10. }

Output:
I am learning C programming language.

To input a string we can use scanf and gets functions.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.     char array[100];
  6.    
  7.     printf("Enter a string\n");
  8.     scanf("%s", array);
  9.  
  10.     printf("Your string: %s\n", array);
  11.     return 0;
  12. }

Output:
Enter a string
We love C.
Your string: We

Only "We" is printed because function scanf can only be used to input strings without any spaces, to input strings containing spaces use gets function.

Input string containing spaces

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   char z[100];
  6.  
  7.   printf("Enter a string\n");
  8.   gets(z);
  9.  
  10.   printf("The string: %s\n", z);
  11.   return 0;
  12. }

Enter a string
Practice makes a person perfect.
The string: Practice makes a person perfect.

Print a string using a loop: We can print a string using a while loop by printing individual characters of the string.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    char s[100];
  6.    int c = 0;
  7.  
  8.    gets(s);
  9.  
  10.    while (s[c] != '\0') {
  11.       printf("%c", s[c]);
  12.       c++;
  13.    }
  14.  
  15.    return 0;
  16. }

You can also use a for loop:

  1. for (c = 0; s[c] != '\0'; c++)
  2.    printf("%c", s[c]);

C program to print a string using recursion

  1. #include <stdio.h>
  2.  
  3. void print(char*);
  4.  
  5. int main() {
  6.    char s[100];
  7.    gets(s);
  8.    print(s);
  9.    return 0;
  10. }
  11.  
  12. void print(char *t) {
  13.    if (*t == '\0')
  14.       return;
  15.    printf("%c", *t);
  16.    print(++t);
  17. }