C program to print a string

Created with Sketch.

 

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:

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 that is stored in a character array.

#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 (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);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *