You are here:

C++/Exchange code

Advertisement


Question
Hi, I'm having some problems understanding code like this:

t = nums [b-1];
nums [b-1] = nums [b];
nums[b] = t;


and the following program that contain such code:

char str[] = "this is a test";
  char *start, *end;
  int len;
  char t;

  cout << "Original message: " << str << "\n";

  len = strlen(str);
  start = str;
  end =& str[len-1];

  while(start<end) {
     t =* start;
     *start = *end;
     *end = t;
     start++;
     end--; }

  cout << "Inverted message: " << str << "\n";


and:

for(a=1; a<size; a++)
     for(b=size-1; b>=a; b--) {
        if(nums[b-1] > nums[b]) { // if out of order exchange element
         t=nums[b-1];
         nums[b-1]=nums[b];
         nums[b] = t; }


and here is another piece of code that I can't understand, can you explain:

void power (int base, int exp) {
int i;
if(exp < 0) return;
i=1;
for ( ; exp; exp--) i = base * i;
  cout << "The answer is: " << i;
}

what does this:
for ( ; exp; exp--) i = base * i;
  cout << "The answer is: " << i;
do?  

Answer
Hi Angela,

This code is part of a bubble sort. For the exchange code, assume nums is 1,6,4,8,3,2 and b = 4.

nums[b-1] is 8 and nums[b] is 3.  8 is of course > 3.

so t = nums[b-1] is 8
nums[b-1]=nums[b] makes nums[b-1] 3 and we have

1,6,4,3,3,2

nums[b]=t makes nums[b] 8 and we have

1.6.4.3.8.2

And you see it has ordered the 2 elements I chose at index 3 and 4.

=========================

The next piece of code take x raised to the y.  The for loop counts down from exp to 0. If base is 3 and exp is 4 you have the loop running 4 times (4, 3, 2, 1)

Loop exp = 4: i = base * i -> i =  1 * 3 -> i = 3
Loop exp = 3: i = base * i -> i =  3 * 3 -> i = 9
Loop exp = 2: i = base * i -> i =  9 * 3 -> i = 27
Loop exp = 1: i = base * i -> i = 27 * 3 -> i = 81

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.