0

hello coders, i hope you all are going well, one thing blows my mind today in c i can't explain it this is why title is akward, so the thing is i have an array called tab[n] i wanted to invert it elements from tab[0] to tab[n-1] and and the tab[midle] would remain the same so i used intermediate variable x, max, half, what i get in resutl is just unexpected because before the entering the loop for the value of max is equal to 14 once once in the for loop max is equal to 0 i don't understand why; sec time it is equal to 13 normal cause i have max--; then again max=1 i don't get why, then max=13 normal

#include <stdio.h>
#define DIM 15
int main(void){
  int x ;
  int i=0;
  int max=14;
  int tab[DIM]={1,5,3,0,4,0,5,8,3,0,5,3,0,7};
  int half;
  if(DIM%2==0){
    half = DIM/2;
  }
  else{
    half = (DIM-1)/2;
  }
    printf("max initial =%d\n", max);
    printf("half initial =%d\n", half);
  for (i=0; i<=half; i++) {
    x=tab[i];
    tab[i]=tab[max];
    tab[max]=tab[i];
    max--;
    printf("max=%d\n", i);
    printf("max=%d\n", max);
  }
  for (i=0; i<DIM; i++) {
    printf("tab[%d]=%d\n", i, tab[i]);
  }
  return 0;
}
5
Contributors
5
Replies
27
Views
3 Months
Discussion Span
Last Post by christos_1
0

Why do you reference tab[14] in line 19?
I see you initialized the array tab[] in line 7 with 14 values but that only filled the tab[] array from tab[0] to tab[13].

Since tab[14] is not initialized, you can't be sure what will happen.

Edited by rproffitt: Grammar

0

A couple additional comments.

You should check that the calculation of half is really what you want.
The upper limit for the iteration might be DIM/2 - 1.

Also, I'd recommend using a different variable name for max.
max is a predefined function in C++. It takes in two operators and returns the maximum of the two. For example,

dummyVar = max(2, 5); // should return 5

Using it as a variable name might cause issues.

1

Your problem is one of perception. You have 2 statements printing that max =. One is reporting the value of i and the other is reporting the value of max. Change the first one to i = and you should start seeing things right.

Edited by tinstaafl

1

Take a close look at your swap. There's an error there!

Your loop condition should be < instead of <=.
And you can just say half = DIM / 2;

0

i really thanks you all i really preciate your time and your help don't how to mention your username in reply, but i would like to tell all your reply helped a lot !

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.