2

I'm gonna crazy everything is looking good where is the problem?

void main(){
    int num1 = 10;
    int num2 = 11;
    
    print("First : $num1, $num2");
    
   swap(num1,num2);
    
    print("Last : $num1, $num2");
}
void swap(int num1,int num2){
    int temp;
    
    temp = num1;
    num1 = num2;
    num2 = temp;

}

MY OUTPUT: First: 10,11 Last: 10,11

3 Answers3

1

You should try removing the swapping from the swap function and place it directly inside the main function. When calling functions, references to the variables' values are passed and not the variable itself.

ufe
  • 81
  • 2
  • 1
    I want to work with a function so this problem should solve swap function. I don't want to swapping in the main. my problem is wrong printing –  Nov 25 '20 at 18:56
0

@Ketan Ramteke is right. Or you can return a list and use that value like this:

void main(){
    int num1 = 10;
    int num2 = 11;
    
    print("First : $num1, $num2");
    
    List arr = swap(num1,num2);
    
    print("Last : ${arr[0]}, ${arr[1]}");
}

List swap(int num1,int num2){
    int temp;
    
    temp = num1;
    num1 = num2;
    num2 = temp;
    return [num1, num2];
}
Akif
  • 7,098
  • 7
  • 27
  • 53
-1

// Dart 2.6.
void main(){
    int num1 = 10;
    int num2 = 11;
    
    print("First : $num1, $num2");
    
    // get returned swapped values
    List result = swap(num1,num2);
    // assign them to original variables
    num1 = result[0];
    num2 = result[1];
    //print the mutated num1 and num2
    print("Last : $num1, $num2");
    
    
}
List swap(int num1,int num2){
    int temp;
    
    temp = num1;
    num1 = num2;
    num2 = temp;
   // print("Last : $num1, $num2");
    return [num1, num2];

}
Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41
  • 1
    Dart is a pass-by-value language; your `swap` function cannot work. You can't tell this from your `print` statements since they're inconsistent; one prints from the caller while the other prints from the callee. If you moved the `print("Last...")` line into `main`, you would see that `swap` does not affect `main`'s `num1` and `num2` at all. – jamesdlin Nov 25 '20 at 21:02
  • Thank you for clarifying and adding the value to the answer, updated the code. – Ketan Ramteke Nov 25 '20 at 21:28