This program print a string. String can be printed by using various functions such as printf, puts.
C programming code
#include <stdio.h>
int main()
{
char array[20] = "Hello World";
printf("%s\n",array);
return 0;
}
To input a string we use scanf function.
C programming code
#include <stdio.h>
int main()
{
char array[100];
printf("Enter a string\n");
scanf("%s", array);
printf("You entered the string %s\n",array);
return 0;
}
Input string containing spaces
#include <stdio.h>
int main()
{
char a[80];
gets(a);
printf("%s\n", a);
return 0;
}
Note that scanf can only input single word strings, to receive strings containing spaces use gets function.
C program to print 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);
}
Print string using loop
We print string using for loop by printing individual characters of string.
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
int c, l;
gets(s);
l = strlen(s);
for (c = 0; c < l; c++)
printf("%c", s[c]);
return 0;
}
No comments:
Post a Comment