Write a C program that asks the user to enter a positive integer (the integer co
ID: 3670189 • Letter: W
Question
Write a C program that asks the user to enter a positive integer (the integer could be of any number of digits in the range of the integer type) and replace each digit by the sum of that digit plus 6 modulus 10. The program then should swap the first digit with the last digit before it displays the output.
A sample input/output:
Enter the number of digits of the number: 5
Enter the number: 92828
Output: 48485
1)Name your program replace2.c.
2) The user will enter the total number of digits before entering the number.
3) You can use format specifier "%1d" in scanf to read in a single digit into a variable (or an array element). For example, for input 101011, scanf("%1d", &num) will read in 1 to num.
4) As part of the solution, write and call the function replace() with the following prototype. The replace() function assumes that the digits are stored in the array a and computes the replaced digits and store them in the array b. c represents the size of the arrays. void replace(int *a, int *b, int n); The replace() function should use pointer arithmetic – not subscripting – to visit array elements. In other words, eliminate the loop index variables and all use of the [] operator in the function.
5) As part of the solution, write and call the function swap() with the following prototype. void swap(int *p, int *q); When passed the addresses of two variables, the swap() function should exchange the values of the variables: swap(&i, &j); /* exchange values of i and j */
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void replace(int *a, int *b, int n){
int i;
for (i=0;i<n;i++){
*b++= (*a++ + 6)%10;
}
}
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
int main() {
int num, number,i;
printf("Enter the number of digits of the number: ");
scanf("%d",&num);
printf("Enter the number: ");
scanf("%d",&number);
int a[num],b[num];
i = num-1;
do {
a[i] = number % 10;
number /= 10;
i--;
} while (number != 0);
replace(a, b,num);
swap(&b[0],&b[num-1]);
for (i=0;i<num;i++){
printf("%d",b[i]);
}
printf(" ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.