i need help writing this program in c. please include steps and explainations if
ID: 3548662 • Letter: I
Question
i need help writing this program in c. please include steps and explainations if possible.
create a program that accepts a user entered nine digit number as an array, like a social security number. elements cannot be negative or greater than 9. as an example, the user enetered: 123-45-6789. program should:
-swap the two numbers in the middle as well as the ends. (becomes932-54-6781)
-add five to each element. if number is greater than 10, keep the units digit. (becomes 478-09-1236)
-generate a single digit randon number from 1-9 that is called key.and add it to every element with an even index. (key=3, becomes 771-02-1539)
-uses the same key to subtract from every element with an odd index. (add 10 to make the difference non negative if negative after subtraction) (becomes 741-72-8509)
-write the original number, key, and new encrypted number to a file called "output.txt".
output: SSN =123-45-6789, key=3, SSE = 741-72-8509
Explanation / Answer
#include<stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
char num[9],input[9],swap;
int i,r;
FILE *f;
printf("SSN = ");
//input given by user
for(i=0;i<9;i++){
if(i==3||i==5)
scanf("%*c");
scanf("%c",&input[i]);
num[i]=input[i];
}
//swapping middle numbers
swap = num[3];
num[3] =num[4];
num[4]=swap;
//swapping corner numbers
swap = num[0];
num[0] =num[8];
num[8]=swap;
for(i=0;i<9;i++){
//adding 5 to each number
num[i] = num[i] + 5;
//store unit digit if numbers is greater than 1
if(num[i]>57)
num[i] = num[i] -10;
}
//generating random numbers
srand(time(NULL));
r = rand()%9 + 1;
for(i=0;i<9;i++){
//odd
if(i%2!=0){
//substracting r from digit
num[i] = num[i] - r;
//adding 10 if r is greater than number
if(num[i]<48)
num[i] = num[i] + 10;
}else{
//even
//adding r to digit
num[i] = num[i] + r;
//store unit digit if numbers is greater than 1
if(num[i]>57)
num[i] = num[i] - 10;
}
}
//open a file
f =fopen("data.txt","w");
fprintf(f,"SSN =");
for(i=0;i<9;i++){
if(i==3||i==5)
fprintf(f,"-");
fprintf(f,"%c",input[i]);
}
fprintf(f,",key =%d,SSE=",r);
for(i=0;i<9;i++){
if(i==3||i==5)
fprintf(f,"-");
fprintf(f,"%c",num[i]);
}
return 0;
}
-----------------------------------------------------------------------------------------------------------------------------------------------
input------------
SSN =123-45-6789
output in file----------------------
SSN =123-45-6789,key =3,SSE=741-72-8509
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.