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.

C programming code

#include <stdio.h>
 
int main()
{
   char array[25] = "C programming language";
 
   printf("%s\n", array);
 
   return 0;
}

To input a string we use scanf function.

C programming code

#include <stdio.h>
 
int main()
{
    char array[100];
 
    printf("Enter a string\n");
    scanf("%s", array);
 
    printf("Your entered string: %s\n", array);
    return 0;
}

Input string containing spaces

Note that scanf can only be used to receive strings without any spaces as input from a user, to receive strings containing spaces use gets function.

#include <stdio.h>
 
int main()
{
   char a[80];
 
   gets(a);
 
   printf("%s\n", a);
 
   return 0;
}

Print a string using a loop

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

#include <stdio.h>
 
int main()
{
   char s[100];
   int c = 0;
 
   gets(s);
 
   while (s[c] != '\0') {
      printf("%c", s[c]);
      c++;
   }
 
   return 0;
}

You can also use a for loop:

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

C program to print a string using recursion

#include <stdio.h>
 
void print(char*);
 
int main() {
   char s[100];
   gets(s);
   print(s);
   return 0;
}
 
void print(char *t) {
   if (*t == '\0')
      return;
   printf("%c", *t);
   print(++t);
}