C print string program

C program to print string using different functions like printf(), puts() as well as other will be discussed here. The most common way to print a string is using printf() function. printf() function prints the string which is passed in it. Consider the following example.

Print string using printf() function

#include <stdio.h>
int main(){

  printf("I am learning how to print string in C\n");
  
  return 0;
}

This will print the string inside it which is “I am learning how to print string using C”. But we can also print string using character array and printf() function. %s is used as the format specifier for printing a string.

#include <stdio.h>
int main(){
  char char_array[50] = "I am learning to print string here.";

  printf("%s\n", char_array);

  return 0;
}

Output of this print string program:

print-string-program-in-c

Taking sting input and print it

We can take sting input from the user using scanf() and gets() function. These two functions are defined inside stdio.h header file.

#include <stdio.h>
int main(){
    char my_string[50];

    printf("Enter any string here to print it : \n");
    scanf("%s", my_string);   // not use &my_string in case of string

    printf("\nYou have entered '%s'.\n", my_string);

    return 0;
}

The problem here is that we can not take space separated string as input in case of using scanf() function. See the output bellow.

Enter any string here to print it :
competitive programmer

You have entered 'competitive'.

To overcome this problem we can use gets() function to take string input. It will read the whole string with space.

#include <stdio.h>
int main(){
  char given_string[50];

  printf("Enter any space separated string here : \n");
  gets(given_string);

  printf("\nYou have entered the following string : \n%s\n", given_string);
  
  return 0;
}

Output :

Enter any space separated string here :
competitive programmer is best for C

You have entered the following string :
competitive programmer is best for C

Print string using loop

We can also print a string using any loop in C although we will use while loop here. The logic will same for every loop. We will determine the end of the string by NULL character.

// print string using while loop

#include <stdio.h>

int main(){
   char char_str[50];
   int r = 0;

   printf("Enter any string here : \n");
   gets(char_str);

   printf("\nYou have entered : \n");
   
   while (char_str[r] != '\0'){
      printf("%c", char_str[r]);
      r++;
   }

   return 0;
}
Enter any string here :
I can print string with C now.

You have entered :
I can print string with C now.

Previous pageTranspose matrix

Next pageReverse string