c++ - I am getting different output while solving this program manually -


as assignment, have speculate output of program:

#include <iostream> #include <ctype.h> #include <string.h>  void change (char* state, int &s) {     int b = s;     (int x = 0; s>=0; x++, s--)     if ((x+s)%2)         *(state+x) = toupper(*(state+b-x)); }  int main ( ) {     char s[] = "punjab";     int b = strlen(s) - 1;     change (s, b);     std::cout<<s<<"#"<<b; } 

according book, when compiled , executed, program should output:

bajjab#-1

the problem guess, executing code in mind, be

bajnup#-1

instead.

i making mistake somewhere, where?

while running code on paper, it's idea keep track of values variables take.

this int b = strlen(s) - 1; gives 5.

inside change() now,

b holds value of s, 5.

now focus here:

for (int x = 0; s>=0; x++, s--)   if ((x+s)%2)     *(state+x) = toupper(*(state+b-x)); 

x == 0, s == 5, sum not even, %2 not result in 0, resulting in body of if statement execute , write state[5] state[0].

now x increased 1, , s decreased 1, since s >= 0 evaluates true.

and on...after done paper-run, may want print variables @ every step of program (when run on computer), , compare them every step made on paper.

example:

#include <iostream> #include <ctype.h> #include <string.h>  void change (char* state, int &s) {     int b = s;     (int x = 0; s>=0; x++, s--)     {         std::cout << "x = " << x << ", s = " << s << ", x + s = " << x + s << ", (x + s) % 2 = " << (x + s) % 2 << "\n";         if ((x+s)%2)         {             std::cout << "state[" << x << "] = state[" << b - x << "]\n";             *(state+x) = toupper(*(state+b-x));         }         std::cout << "state = \"" << state << "\"\n";     } }  int main ( ) {     char s[] = "punjab";     int b = strlen(s) - 1;     change (s, b);     std::cout<<s<<"#"<<b; } 

output:

x = 0, s = 5, x + s = 5, (x + s) % 2 = 1 state[0] = state[5] state = "bunjab" x = 1, s = 4, x + s = 5, (x + s) % 2 = 1 state[1] = state[4] state = "banjab" x = 2, s = 3, x + s = 5, (x + s) % 2 = 1 state[2] = state[3] state = "bajjab" x = 3, s = 2, x + s = 5, (x + s) % 2 = 1 state[3] = state[2] state = "bajjab" x = 4, s = 1, x + s = 5, (x + s) % 2 = 1 state[4] = state[1] state = "bajjab" x = 5, s = 0, x + s = 5, (x + s) % 2 = 1 state[5] = state[0] state = "bajjab" bajjab#-1 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -