# Write a program to swap the alternate digits of the given number.

1 vote
518 views

## Problem :

I am very new to programming. I need to write a program called swapAdj that must accept the array of integers and after that swap those elements at the adjacent indexes. For example consider the elements 0 and 1 are swapped by the program and after that elements 2 and 3 are also swapped by the program and after that so on. Also please note if your array has the odd length then the program must keep final element unmodified.

1 vote

## Solution :

I also wanted to write similar program and after doing the lot of trial and errors I was able to finally write the error free program. Please find below the program for your help.

``````public static void swapAdj(int[] a){

int swaplen=a.length;

if(swaplen %2 ==0){

for(int i=0; i<swaplen; i=i+2){

int swapc=a[i]+a[i+1];

a[i]= swapc -a[i];

a[i+1]= swapc -a[i+1];

}

}

if(swaplen %2 !=0){

for(int j=0; j<swaplen -1; j=j+2){

int swapc=a[j]+a[j+1];

a[j]= swapc-a[j];

a[j+1]= swapc-a[j+1];

}

a[swaplen-1]=a[swaplen-1];

}

}

public static void printSwapArray(int[] a){

int swaparrlen=a.length;

for(int i=0;i<swaparrlen;i++)

System.out.print(a[i]+" ");

}``````

I hope you have read the entire swapAdj  program and also you are able to understand the logic of the above written program.

## Related questions

3 views
Problem: Anyone here who know nested loops to print a rectangle. sample output for given program? If yes, then please answer me.
6 views
1.3K views
Problem : I am getting bellow error can only iterate over an array or an instance of java.lang.iterable
24 views
Problem: How can I find the values in an array whose sum equals some given value?
1 vote
11 views
Problem: I want to make a Java program to find the repeated digits in an integer without the use of string or array method . Can somebody do this so I can understand how to make this program? Thank you !!
13 views
Problem: Please assist me in resolving this issue: find a pair of elements from an array whose sum equals a given number in java
14 views
Problem: Hello! I am trying to write a program that takes input from the user and determines whether the user entered a number, alphabet, or a special character. I am a beginner so, facing some difficulty in understanding the logic. Can somebody from here help me find out the solution? Thanks!