C Homework Assignment Assume the following declarations char
C++ Homework Assignment:
Assume the following declarations:
char name[21];
char yourName[21];
char studentName[31];
Mark the following statements as valid or invalid. If a statement is invalid, explain why.
a. cin >> name;
b. cout << studentName;
c. yourName[ 0] = \'\\0\';
d. yourName = studentName;
e. if (yourName == name) studentName = name;
f. int x = strcmp(yourName, studentName);
g. strcpy(studentName, name);
h. for(intj=0;j<21;j++) cout << name[j];
Solution
a. cin>>name
This is valid statement. cin is the input stream which takes character array as input. Input is read till user presses enter and at the end of character array \'\\0\' will be stored.
b. cout << studentName;
above statement valid ,it wont either give compile time error nor run time error.. But it displays some garbage value
since studentName is not initialized ..
c. yourName[ 0] = \'\\0\';
no compile time or run time error , but character array if used in taking input after than statement yourName will not be updated with read value as \'\\0\' no characters written after \'\\0\' ..Logical point of view not valid.
d. yourName = studentName;
Not valid as studentName is of size 31 and yourName is of 21 , there size mis match.
e. if (yourName == name) studentName = name;
not valid ,comile time error as there is size miss match
f. int x = strcmp(yourName, studentName);
this is valid as it it is comparing two character array which can be of different size
g . strcpy(studentName, name);
valid as it\'s copying from one char array to another
h. for(intj=0;j<21;j++) cout << name[j];
valid, but displaying all the characters is not good as after the string length other characters are some junk characters. Suppose you entered \"John\" as input for name , then after displaying 4 characters as John , others characters are not valid.. instead we can display till strlen of name , which looks good.
![C++ Homework Assignment: Assume the following declarations: char name[21]; char yourName[21]; char studentName[31]; Mark the following statements as valid or in C++ Homework Assignment: Assume the following declarations: char name[21]; char yourName[21]; char studentName[31]; Mark the following statements as valid or in](/WebImages/33/c-homework-assignment-assume-the-following-declarations-char-1096796-1761578551-0.webp)