Write a program whose input is two integers and whose output is the two integers swapped. Place the values in an array, where x is position

12 answers
Question:

Write a program whose input is two integers and whose output is the two integers swapped. Place the values in an array, where x is position 0 and y is position 1.Ex: If the input is: 3 8 then the output is: 83 Your program must define and call a method: public static void swapValues (int[] "values) LabProgram. java 1 import java. util. Scanner; 23 public class LabProgram 4 5 /* Define your method here 6 7 public static void main(String[args) { 8 /* Type your code here. / 9 } 10 } 11

Answers

import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

{ public static void swapValues(int[] values)

{int temp= values[0];

values[0]=values[1];

values[1]=temp;

System.out.print(values[0]+" "+values[1]);}

public static void main (String[] args) throws java.lang.Exception

{

Scanner sc= new Scanner(System.in);

int A[] = new int[2];

A[0] = sc.nextInt();

A[1]= sc.nextInt();

swapValues(A);

}

}

Input:-

3   8

Output:-

8   3

Input:-

1    2

Output:-

2   1

#include <iostream>

using namespace std;

int main() {  

 int start, end;

 cout << "Enter start number: ";

 cin >> start;

 cout << "Enter end number: ";

 cin >> end;

 for(int n=start; n<=end; n+=5) {

   cout << n << " ";

 }

}

Explanation:

I output the numbers space separated.

#include <stdio.h>

void SwapValues(int* userVal1, int* userVal2)

{

int temp = *userVal1;

*userVal1 = *userVal2;

*userVal2 = temp;

}

int main(void)

{

int a = 3;

int b = 8;

printf("Before swap: a=%d, b=%d\n", a, b);

SwapValues(&a, &b);

printf("After swap:  a=%d, b=%d\n", a, b);

return 0;

}

Explanation:

For swapping variables efficiently, you need a helper variable in C or C++.


[tex]In C!! 12.12 LAB: Swapping variables Write a program whose input is two integers and whose output i[/tex]

// Program is implemented using Coral Programming Language

int X

int Y

int Sum

Put "Enter any two numbers" to output

x = Get next input

Y = Get next input

if Y < X

Put "Second integer can't be less than the first" to output

else

for Sum = X; Sum <= Y; Sum = Sum + 10

Put Sum to output

Explanation:

The above program is written using Coral Programming Language

The first line is a comment

The next 3 lines declares 3 integer variables

Which are X, Y and Sum

X and Y represent the two input numbers as seen on line 6 and 7

X, being the first and Y being the second

Line 8 tests the larger of the two numbers

If Y is less than X, the output is "Second integer can't be less than the first" without the quotes

Else

The last two lines perform iterative operations that assigns the addition of 10 and X to Sum

It continues printing sum as long as sum is less than the value of Y.

Following are the program in the C++ Programming Language.

#include <iostream>

using namespace std;

//define function for swapping

void SwapValues(int* userVal1,int* userVal2){  

//set integer variable to store the value

int z = *userVal1;

//interchange their value

*userVal1 = *userVal2;  

//interchange their value

*userVal2 = z;

}

//define main method

int main()

{    

//declare variables

int x,y;

//get input from the user

cin>>x>>y;

//Call the method to swap the values

SwapValues(&x,&y);

//print their values

cout<<x<<" "<<y;

return 0;

}

Output:

3 8

8 3

Explanation:

Following are the description of the program.

Firstly, we define required header file and function 'SwapValues()', pass two pointer type integer variables in argument that is 'userVal1' and 'userVal2'.Set integer data type variable 'z' and initialize the value of 'userVal1' in it, then initialize the value of 'userVal2' in 'userVal1' and then initialize the value of 'z' in 'userVal2'.Finally, define the main method in which we set two integer type variables and get input from the user in it then, call and pass those variables and print it.

Here is the C++ and Python programs:

C++ program:

#include<iostream>  //to use input output functions

using namespace std;  //to identify objects like cin cout

void swapvalues(int&  userVal1, int& userVal2); //function to swap values

int main() {  //start of main function

  int integer1,integer2;  //declare two integers

  cout<<"Enter first integer: ";  //prompts user to enter the first number

  cin>>integer1;  //reads first number from user

     cout<<"Enter second integer: "; //prompts user to enter the second number

  cin>>integer2;  //reads second number from user

 cout<<"Integers before swapping:\n";  //displays two numbers before swapping

 cout<<integer1<<endl<<integer2;  

  swapvalues(integer1, integer2);  //calls swapvalues method passing two integers to it

  cout << "\nIntegers after swapping:\n"; //displays two numbers after swapping

 cout<<integer1<<endl<<integer2; }

void swapvalues(int&  userVal1, int& userVal2){  //method that takes two int type numbers and swaps these numbers

  int temp;  //temporary variable

  temp = userVal1;  //temp holds the original value of userVal1

  userVal1 = userVal2;  //the value in userVal2 is assigned to userVal1

  userVal2 = temp; } //assigns value of temp(original value of userVal1) to userVal2

The program prompts the user to enter two integers and then calls swapvalues() method by passing the integers by reference. The swapvalues() method modifies the passed parameters by swapping them. The method uses a temp variable to hold the original value of first integer variable and then assigns the value of second integer variable to first. For example if userVal1 = 1 and userVal2 =2. Then these swapping statements work as follows:

temp = userVal1;  

temp = 1

userVal1 = userVal2;  

userVal1 = 2

userVal2 = temp;

userVal2 = 1

Now because of these statements the values of userVal1 and userVal2 are swapped as:

userVal1 = 2

userVal2 = 1

Explanation:

Python program:

def swap_values(user_val1, user_val2):  #method to swap two numbers

   return user_val2,user_val1   #returns the swapped numbers

integer1 = int(input('Enter first integer :')) #prompts user to enter first number

integer2 = int(input('Enter second integer :'))  #prompts user to enter second number

print("Numbers before swapping") #displays numbers before swapping

print(integer1,integer2)

print("Numbers after swapping") #displays numbers after swapping

integer1,integer2 = swap_values(integer1,integer2) #calls method passing integer1 and integer2 to swap their values

print(integer1,integer2) #displays the swapped numbers

The screenshot of programs and outputs is attached.


[tex]6.21 LAB: Swapping variables Write a program whose input is two integers and whose output is the two[/tex]
[tex]6.21 LAB: Swapping variables Write a program whose input is two integers and whose output is the two[/tex]

leave a reply cancel reply I was wondering

public class num3 {

   public static String swapValues(int userVal1, int userVal2){

       int temp = userVal2;

       userVal2 = userVal1;

       userVal1 = temp;

       return(userVal1+", "+userVal2);

   }

   public static void main(String[] args) {

       int val1 = 5;

       int val2 = 8;

       System.out.println("Original values");

       System.out.println(val1+", "+val2);

       System.out.println("Swapped Values");

       System.out.println(swapValues(val1,val2));

   }

}

Explanation:

The problem is solved with Java programming languageDefine the method swapValues() to accept two ints and return a StringWithin the method body, create a temp variable to hold the value of userVal2 temporaryDo the following re-assignment of values userVal2 = userVal1; userVal1 = temp;Return the concatenated String userVal1+", "+userVal2Create two variables and initialize them in the main methodOutput their valuesCall swapValues() aand output the swapped values

The program in Python is as follows:

num1 = int(input())

num2 = int(input())

if num2 < num1:

   print("Second integer can't be less than the first.")

else:

   for i in range(num1,num2+1,5):

       print(i,end=" ")

Explanation:

This gets the first integer from the user

num1 = int(input())

This gets the second integer from the user

num2 = int(input())

If the second is less than the first, the following prompt is printed

if num2 < num1:

   print("Second integer can't be less than the first.")

If otherwise, the number between the intervals is printed with an increment of 5

else:

   for i in range(num1,num2+1,5):

       print(i,end=" ")

The program to this question can be given as:

Program:

#include <iostream>  //header file

using namespace std;   //using namespace.

void SwapValues(int* userVal1, int* userVal2); //function declaration.

void SwapValues(int* userVal1, int* userVal2) //function definition.

{ //function body.

//perform swapping

   int t = *userVal1;  

   *userVal1 = *userVal2;

   *userVal2 = t;

}

int main() //main method  

{

int n1, n2; //define variable

cout<<"Enter first number :"; //message

cin>>n1; //input by user.

cout<<"Enter second number :"; //message  

cin>>n2; //input by user.

SwapValues(&n1,&n2); //calling function.

cout<<"Swapped values"<<endl;

cout<<"first number is :"<<n1<<endl; //print value

cout<<"second number is:"<<n2<<endl; //print value

return 0;

}

Output:

Enter first number :3

Enter second number :8

Swapped values

first number is :8

second number is :3

Explanation:

The description of the above C++ language program can be given as:

In the program, firstly we include the header file. Then we declare and define a function that is "SwapValues()" function in the function we pass two integer variable that is "userVal1 and userVal2" inside a function, we define an integer variable that is "t" and perform swapping.  Then we define the main function in the main function we define two variables that is "n1 and n2" this variable is used to take value-form user. then we pass this value to function and print the function values.

8 track im pretty sure came first

answerpixels;

Similar Solved Works

3 answers

What actionsWhat do you think the Turkish government should take to minimize the damage caused by future earthquakes?

What actions What do you think the Turkish government should take to minimize the damage caused by future earthquakes?...
3 answers

What prohibits lipids from being a readily available energy source? fat must be broken down into fatty acids before being

What prohibits lipids from being a readily available energy source? fat must be broken down into fatty acids before being converted to glucose. lipids are structural components, so they are a last-resort energy source. lipids are only used to create enzymes, hormones, and antibodies. the conversion...
4 answers

How did geography play a role in the reaction to the tax on distilled spirits?

How did geography play a role in the reaction to the tax on distilled spirits?...
5 answers

Summaries, paraphrases, and quotations are especially useful for taking notes during the research process

Summaries, paraphrases, and quotations are especially useful for taking notes during the research process confusing your friends and family drawing pictures in your notebook regulating a country s laws...
5 answers

How did regents affect the rise to power of military leaders in japan

How did regents affect the rise to power of military leaders in japan...
4 answers

Do the points -4,6 and 6,-4 describe the same location

Do the points -4,6 and 6,-4 describe the same location...
4 answers

¿Cuál será la velocidad de salida y la Rv de un sistema de tornillo sin fin- rueda dentada si se coloca un motor de 1000rpm

¿Cuál será la velocidad de salida y la Rv de un sistema de tornillo sin fin- rueda dentada si se coloca un motor de 1000rpm al tornillo sin fin y la rueda dentada tiene 10 dientes? ¿Y si se coloca el motor en la rueda dentada?...
3 answers

How many one-ounce slices of cheese are in a pound

How many one-ounce slices of cheese are in a pound...
3 answers

As the temperature of one of the four liquids increases, the vapor pressure will a) increase exponentially

As the temperature of one of the four liquids increases, the vapor pressure will a) increase exponentially b) decrease exponentially c) both increase and decrease exponentially d) remain the same...
4 answers

Maxene Raices says that managers must be involved and set expectations of the employee, making sure

Maxene Raices says that managers must be involved and set expectations of the employee, making sure to explain why training is important. Which of the following would help managers explain in measurable terms what the employee should be able to do once the training has been successfully completed? a...
4 answers

Answer correctly please

Answer correctly please [tex]Answer correctly please[/tex]...
7 answers

In east germany, back before the berlin wall fell, there was one manufacturer of cars (veb sachsenring

In east germany, back before the berlin wall fell, there was one manufacturer of cars (veb sachsenring automobilwerke zwickau). they produced one type of car, the trabant, with a maximum speed of 55 mph (26 horsepower lawnmower type engine). anyone who wished to buy a car put their name on a list an...
3 answers

Match the average rate of change of National Defense Spending with the correct time interval.​

Match the average rate of change of National Defense Spending with the correct time interval.​ [tex]Match the average rate of change of National Defense Spending with the correct time interval.​[/tex]...
6 answers

Which of the following shows an equilateral triangle inscribed in a circle

Which of the following shows an equilateral triangle inscribed in a circle...
4 answers

Can someone please help me?

Can someone please help me? [tex]Can someone please help me?[/tex]...
4 answers

When meiosis and fertilization occur, genes from both parents are combined, producing unique offspring. How does this benefit a species?

When meiosis and fertilization occur, genes from both parents are combined, producing unique offspring. How does this benefit a species?...
4 answers

Can someone help me please

Can someone help me please [tex]Can someone help me please[/tex]...
4 answers

The totals from the first payroll of the year are shown below. total earnings fica oasdi fica hi fit w/h state tax union

The totals from the first payroll of the year are shown below. total earnings fica oasdi fica hi fit w/h state tax union dues net pay $36,195.10 $2,244.10 $524.83 $6,515.00 $361.95 $500.00 $26,049.22 journalize the entry to deposit the fica and fit taxes. for a compound transaction, if an amount box...
5 answers

Use inductive reasoning to determine the next two terms in the sequence. 12, 17, 23, 30, ,

Use inductive reasoning to determine the next two terms in the sequence. 12, 17, 23, 30, ,...
4 answers

'it his karam his destiny ' that made his grandfather go blind . In what matter did Mukesh defy this belief which existed

'it his karam his destiny ' that made his grandfather go blind . In what matter did Mukesh defy this belief which existed among his community...

-- 0.026001--