Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.
Example(s):1575, 1632, 1539 (Only one at a time)
Login
[lwa]
Solved Problem
#CPP#2964
Problem Statement - Output writing using strcpy for structure string variables
Write the output of the following program. Assume that required header files are present.
struct Game {
char Magic[20];int Score;
};
int main()
{
Game M={"Tiger",500};
char a[20];
cout<<M.Magic<<", "<<M.Score<<endl;
strcpy(a,M.Magic);
a[0]='L'; a[2]='o'; a[3]='n'; a[4]='';
strcpy(M.Magic,a);
M.Score++;
cout<<M.Magic<<", "<<M.Score<<endl;
return 0;
}
Solution
TC++ #2964
Run Output
Tiger, 500
Lion, 501
Notes
struct Game { char Magic[20];int Score; }; //Structure declared
Game M={“Tiger”,500};
Structure initialised with M.Magic containing “Tiger” and M.Score containing 500.
char a[20]; //Another character array declared
cout<<M.Magic<<“, “<<M.Score<<endl;
Content of structure will be printed here
strcpy(a,M.Magic); //The variable M.Magic will be copied to char array a.
a[0]=’L’; a[2]=’o’; a[3]=’n’; a[4]=”;
Selective character in the array a will be modified and the string will be shortened by early placement of null character.
strcpy(M.Magic,a);
modified char array a will be copied as updated value in the structure variable M.Magic
M.Score++; New value of score be updated in the structure instance M
cout<<M.Magic<<“, “<<M.Score<<endl;
Updated values of structure instance M will be printed
A character array is read by the string functions till the first null character, whether it has many null characters later or any other content up to size of the array. So a new placement of null character earlier can shorten the string as done in this example.