How to Print a String in C

C program to print a string

C program to print a string using various functions such as printf, puts. It terminates with '\0' (NULL character), which is used to mark the end of a string. Consider the following code:
#include<stdio.h>
#include<conio.h>
void main()
{
   char z[100] = "I am learning C programming language.";
   printf("%s", z); // %s is format specifier
   getch();
}

Output:
I am learning C programming language.

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

C programming code


#include<stdio.h>
#include<conio.h>
void main()
{
    char array[100];
 
    printf("Enter a string\n");
    scanf("%s", array);
    printf("Your string: %s\n", array);
    getch();
}
Output:
Enter a string
We love C.
Your string: We
Remember This: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


#include<stdio.h>
#include<conio.h>
void main()
{
  char z[100];
  printf("Enter a string\n");
  gets(z);
  printf("The string: %s\n", z);
  getch();
}
Output:
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.

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

C program to print a string using recursion

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

No comments:

Post a Comment