In: Computer Science
I have this program in C that takes three char arrays that each have a first and last name. I have two functions that reverese the name and change it to all upper case. I have the program completeed but need to change both functions to use pointers instead of arrays. I will bold the functions I need to use pointers.
#include <stdio.h>
void upper_string(char []);
int main()
{
char name1[100]="John Smith";
char name2[100]="Mary Cohen";
char name3[100]="Carl Williams";
upper_string(name1);// calling upper case function
upper_string(name2);
upper_string(name3);
printf("Names are in upper case \n\"%s\"\n""%s\"\n""%s\"\n",
name1,name2,name3);
reverse(name1);// calling reverse string function
reverse(name2);
reverse(name3);
getch();
}
void upper_string(char s[]) {
int c = 0;
while (s[c] != '\0') {
if (s[c] >= 'a' && s[c] <= 'z') {
s[c] = s[c] - 32;
}
c++;
}
}
// function to reverse the string
void reverse(char string[]){
char temp;
int i, j = 0;
i = 0;
j = strlen(string) - 1;
while (i < j) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", string);
}
Hi,
I have modified the code and highlighted the code changes below.
#include <stdio.h>
#include <string.h>
void upper_string(char *);
void reverse(char *string);
int main()
{
char name1[100]="John Smith";
char name2[100]="Mary Cohen";
char name3[100]="Carl Williams";
upper_string(name1);// calling upper case function
upper_string(name2);
upper_string(name3);
printf("Names are in upper case \n\"%s\"\n""%s\"\n""%s\"\n",
name1,name2,name3);
reverse(name1);// calling reverse string function
reverse(name2);
reverse(name3);
}
void upper_string(char *s) {
int c = 0;
while (*(s + c) != '\0') {
if (*(s + c) >= 'a' && *(s + c) <= 'z') {
*(s + c) = *(s + c) - 32;
}
c++;
}
}
// function to reverse the string
void reverse(char *string){
char temp;
int i, j = 0;
i = 0;
j = strlen(string) - 1;
while (i < j) {
temp = *(string + i);
*(string + i) = *(string + j);
*(string + j) = temp;
i++;
j--;
}
printf("Reverse string is :%s\n", string);
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Names are in upper case
"JOHN SMITH"
MARY COHEN"
CARL WILLIAMS"
Reverse string is :HTIMS NHOJ
Reverse string is :NEHOC YRAM
Reverse string is :SMAILLIW LRAC