Arrays of Characters in C || Array of characters in c || How to declare an array of characters in c
Arrays of Characters in C
Here are a few examples of char array problems:
1. Reversing a string: Write a program that takes a string as input and returns the string in reverse order.
For example, if the input is “hello”, the output should be “olleh”.
Solution
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
int len, i;
// Input a string from the user
printf("Enter a string: ");
gets(str); // Read input string
len = strlen(str); // Get length of the string
// Reverse the string
for(i = 0; i < len; i++) {
rev[i] = str[len - i - 1];
}
rev[i] = '\0'; // Null-terminate the reversed string
// Output the reversed string
printf("Reversed string: %s\n", rev);
return 0;
}
2. Counting vowels: Write a program that takes a string as input and returns the number of vowels in the string.
For example, if the input is “hello”, the output should be 2.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, count = 0;
// Input a string from the user
printf("Enter a string: ");
gets(str);
// Iterate through the string and count vowels
for(i = 0; str[i] != '\0'; i++) {
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
count++;
}
}
// Output the number of vowels
printf("Number of vowels: %d\n", count);//Arrays of Characters in C
return 0;
}
3. Finding substrings: Write a program that takes two strings as input and checks if the first string contains the second string as a substring.
For example, if the input is “hello world” and “world”, the output should be true.
4. Converting case: Write a program that takes a string as input and converts all uppercase letters to lowercase letters and vice versa.
For example, if the input is “Hello World”, the output should be “hELLO wORLD”.
5. Counting words: Write a program that takes a string as input and returns the number of words in the string. For example, if the input is “The quick brown fox jumps over the lazy dog”, the output should be 9.
I hope these examples give you some inspiration for working with char arrays!
Arrays of Characters in C Solution
Coming Soon!!!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.