Monday, February 17, 2020

C program to print a string

#include <stdio.h>
int main()
{
   char z[100] = "I am learning C programming language.";
   printf("%s", z); // %s is format specifier
   return 0;
}
Output:
I am learning C programming language.


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

C programming code

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

#include <stdio.h>
int main()
{
  char z[100];
  printf("Enter a string\n");
  gets(z);
  printf("The string: %s\n", z);
  return 0;
}
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>
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 (= 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 (*== '\0')
      return;
   printf("%c", *t);
   print(++t);
}

No comments:

Post a Comment