C program to print a string using various functions such as printf, puts. Consider the following code:
Output:
Hi there! How are you doing?
The printf function prints the argument passed to it (a string). Next, we will see how to print it if it's stored in a character array.
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 program
int main()
{
char array[100];
printf("Enter a string\n");
scanf("%s", array);
printf("Your string: %s\n", array);
return 0;
}
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
int main()
{
char z[100];
printf("Enter a string\n");
gets(z);
printf("The string: %s\n", z);
return 0;
}
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 loop by printing its characters one at a time. It terminates with '\0' (NULL character), which marks its end.
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:
printf("%c", s[c]);
Using a do-while loop:
int main()
{
char s[100];
int c = 0;
gets(s);
if (s[c] != '\0') { // Used to check empty string
do {
printf("%c", s[c]);
c++;
} while (s[c] != '\0');
}
return 0;
}
C program to print a string using recursion
void print(char*);
int main() {
char s[100];
gets(s);
print(s);
return 0;
}
void print(char *t) {
if (*t == '\0') // Base case
return;
printf("%c", *t);
print(++t);
}