Question
--> Rewrite checkSorted() and replace() using good coding style. --> Updated the main() function if/as needed. --> Write comments to briefly explain your improvements. Written
--> Rewrite checkSorted() and replace() using good coding style.
--> Updated the main() function if/as needed.
--> Write comments to briefly explain your improvements.
Written by:
*/
#include
#include
#include
struct stu{
long id;
char name[32];
};
int checkSorted(char password[]);
int replace(struct stu list[], int *length, const struct stu *ptrData, int *location);
int main( )
{
// Test checkSorted()
char myPassword[] = "abcdefg";
char oldPassword[] = "bcdeabc";
printf("%s %d ", myPassword, checkSorted(myPassword));
printf("%s %d ", oldPassword, checkSorted(oldPassword));
// Test replace()
struct stu list[10] =
{
{88219017, "Ron House"},
{34951406, "John W. Perry"},
{31103628, "Dennis M. Ritchie"}
};
int length = 3;
int status;
int location = 2;
struct stu newData = {11223344, "Brian W. Kernighan"};
for (int i = 0; i < length; i++){
printf("%ld %s ", list[i].id, list[i].name);
}
status = replace(list, &length, &newData, &location);
printf("status: %d ", status);
for (int i = 0; i < length; i++){
printf("%ld %s ", list[i].id, list[i].name);
}
return 0;
}
/*
This function checks if the characters in pasword are sorted in ascending order
Rewrite the following code to:
--> eliminate the call for strlen()
--> replace index k with a pointer
--> make other changes to improve the code
--> write comments to briefly explain your improvements
*/
int checkSorted(char password[])
{
int k;
int sorted = 1;
k = 1;
while (sorted == 1 && k < strlen(password))
{
if (password[k] < password[k - 1])
sorted = 0;
k++;
}
if (sorted == 1)
return 1;
else if (sorted == 0)
return 0;
else return 2;
}
/*
This function replaces the element at a given location in list[]
with data pointed to by its third parameter.
What are the changes that would improve this function?
Make it:
--> simpler
--> shorter
--> easier to read
Write comments to briefly explain your improvements.
*/
int replace(struct stu list[], int *length, const struct stu *ptrData, int *location)
{
if (*location < 0 || *location >= *length){
return 0; // location is out of range
}
list[*location].id = ptrData->id;
strcpy(list[*location].name, ptrData->name);
return 1;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started