C Programs Using Character Arrays
Here are some C programs that use character arrays for various purposes:
1. Program to Input and Print a String:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
return 0;
}
2. Program to Find the Length of a String:
#include <stdio.h>
int main() {
char str[100];
int length = 0;
printf("Enter a string: ");
gets(str);
while (str[length] != '\0') {
length++;
}
printf("Length of the string: %d\n", length);
return 0;
}
3. Program to Reverse a String:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
int length = strlen(str);
printf("Reversed string: ");
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}
4. Program to Check if a String is a Palindrome:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
int length = strlen(str);
int isPalindrome = 1; // Assume it's a palindrome
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - 1 - i]) {
isPalindrome = 0; // Not a palindrome
break;
}
}
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
5. Program to Count Vowels and Consonants in a String:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
gets(str);
int length = strlen(str);
for (int i = 0; i < length; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
These C programs demonstrate various operations and tasks that can be performed using character arrays and strings. You can use these as examples and modify them according to your specific requirements.