2. Array is the simplest data structure where each data element can be randomly accessed by using its index number. Write a complete C program to create an array and perform the following, using functions.
a. Create an array to store some characters.
b. Get a word (which contains lower case letters only) from the user and store the letters in the array according to the order of letters.
(Ex: If the user Input = campus; Array = ‘c’ ‘a’ ‘m’ ‘p’ ‘u’ ‘s’)
c. Display the elements of the array.
d. Add uppercase letters (A, B, C, …) in between each letter in the array. Then your array length become double. Display the elements of the array.
(Ex: If the Array = ‘c’ ‘a’ ‘m’ ‘p’ ‘u’ ‘s’; After inserting numbers, the array = A c B a C m D p
E u F s)
e. Remove all the lower case letters from the array. Then your array will shrink back to the half size. Display the elements of the array.
(Ex: If the array = A c B a C m D p E u F s; then array = A B C D E F)
f. Display the array again in reverse order.
#include <stdio.h>
#include <string.h>
int main() {
char arr[100]; // a
char word[100];
int i, n;
printf("Enter a word (lower case): ");
// b
scanf("%s", word);
n = strlen(word);
for (i=0; i<n; i++) {
arr[i] = word[i];
}
// c
for (i=0; i<n; i++) {
printf("\'%c\' ", arr[i]);
}
printf("\n");
// d
for (i=n-1; i>=0; i--) {
arr[2*i+1] = arr[i];
arr[2*i] = 'A' + i;
}
for (i=0; i<2*n; i++) {
printf("\'%c\' ", arr[i]);
}
printf("\n");
// e
for (i=0; i<n; i++) {
arr[i] = arr[2*i];
}
for (i=0; i<n; i++) {
printf("\'%c\' ", arr[i]);
}
printf("\n");
// f
for (i=n-1; i>=0; i--) {
printf("\'%c\' ", arr[i]);
}
printf("\n");
return 0;
}
Comments
Leave a comment