An Interest In:
Web News this Week
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
- April 10, 2024
- April 9, 2024
- April 8, 2024
October 29, 2022 01:11 pm GMT
Original Link: https://dev.to/mavensingh/carbon-program-to-swap-digits-37fh
Carbon Program to swap digits
In this were going to learn about two ways to swap two numbers in Carbon, and those are mentioned below:
- Using a temp variable.
- Without using a temp variable.
1. Using a temp variable
The idea is simple for this approach for swapping two numbers:
- Assign x variable to a temp variable: temp = x
- Assign y variable to x variable: x = y
- Assign temp variable to y variable: y = temp
Below is the Carbon program to implement the Swapping with temp variable approach:
package sample api;fn Main() -> i32 { // using temp variable var x: i32 = 1; var y: i32 = 2; var temp: i32 = x; x = y; y = temp; Print("SWAPPING"); Print("x: {0}", x); Print("y: {0}", y); return 0;}
Output:
SWAPPINGx: 2y: 1
2. Without using temp variable
The idea is simple for this approach for swapping two numbers:
- Assign to y the sum of x and b i.e. y = x + y.
- Assign to x difference of y and x i.e. x = y x.
- Assign to y the difference of y and x i.e. y = y x.
Below is the Carbon program to implement the Swapping without temp variable approach:
package sample api;fn Main() -> i32 { // without temporary variable var x: i32 = 10; var y: i32 = 2; y = x + y; x = y - x; y = y - x; Print("SWAPPING"); Print("x: {0}", x); Print("y: {0}", y); return 0;}
Output:
SWAPPINGx: 2y: 10
You can find more content like this on programmingeeksclub.com
Original Link: https://dev.to/mavensingh/carbon-program-to-swap-digits-37fh
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To