I am writing code of records and non-recursive binary searches. I have problems when using the binary search since when I try to do it, the printing of the values does not receive me correctly (the array is already ordered) and I do not know what error I may have there
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void registro();
void consultaprestamo();
struct datos {
int numprestamo;
char nombre[10];
char direccion[10];
int telefono;
int importesoli;
}
datos[10];
int x = 0;
char busqueda;
char auxn[10];
int j, k, aux;
int inf, sup, mit, dato, n = 20;
int nucontrol;
int main(void) {
char opcion;
do {
printf("A) people registration\n");
printf("D) Specific consultation for loans\n");
printf("F)exit\n");
printf("Opcion: ");
scanf("%s", &opcion);
switch (opcion) {
case 'A':
registro();
break;
case 'D':
consultaprestamo();
break;
}
} while (opcion != 'F');
}
record data
void registro() {
char continuar;
do {
printf("\n*****************\n");
printf("Loan number: ");
scanf("%d", & datos[x].numprestamo);
printf("Name: ");
scanf("%s", datos[x].nombre);
printf("adress: ");
scanf("%s", datos[x].direccion);
printf("number phone: ");
scanf("%d", & datos[x].telefono);
printf("Amount requested: ");
scanf("%d", & datos[x].importesoli);
x++;
printf("Enter another record? y/n: ");
scanf("%s", &continuar);
} while (continuar != 'n');
}
binary search
void consultaprestamo() {
for (k = 1; k < x; k++) {
for (j = 0; j < x - 1; j++) {
if (datos[j].numprestamo > datos[j + 1].numprestamo) {
aux = datos[j].numprestamo;
datos[j].numprestamo = datos[j + 1].numprestamo;
datos[j + 1].numprestamo = aux;
aux = datos[j].telefono;
datos[j].telefono = datos[j + 1].telefono;
datos[j + 1].telefono = aux;
aux = datos[j].importesoli;
datos[j].importesoli = datos[j + 1].importesoli;
datos[j + 1].importesoli = aux;
strcpy(auxn, datos[j].nombre);
strcpy(datos[j].nombre, datos[j + 1].nombre);
strcpy(datos[j + 1].nombre, auxn);
strcpy(auxn, datos[j].direccion);
strcpy(datos[j].direccion, datos[j + 1].direccion);
strcpy(datos[j + 1].direccion, auxn);
}
}
}
for (j = 0; j < x; j++) {
printf("loan number: %d\n", datos[j].numprestamo);
printf("phone number: %d\n", datos[j].telefono);
printf("Import requested: %d\n", datos[j].importesoli);
printf("\nName: %s\n", datos[j].nombre);
printf("adress: %s\n", datos[j].direccion);
}
inf = 0;
sup = j;
printf("write the number control");
scanf("%d", & nucontrol);
while (inf <= sup) {
mit = (inf + sup) / 2;
if (datos[mit].numprestamo == nucontrol) {
printf("dato %d encontrado posicion %d\n", nucontrol, mit);
printf("loan number: %d\n", datos[j].numprestamo);
printf("phone number: %d\n", datos[j].telefono);
printf("Import requested: %d\n", datos[j].importesoli);
printf("\nName: %s\n", datos[j].nombre);
printf("adress: %s\n", datos[j].direccion);
break;
}
if (datos[mit].numprestamo > nucontrol) {
sup = mit;
mit = (inf + sup) / 2;
}
if (datos[mit].numprestamo < nucontrol) {
inf = mit;
mit = (inf + sup) / 2;
}
}
}
I tried to nest the while with the for of the ordered array but I couldn't, I also tried to make several changes of variables.
Your code will cause an infinite loop when try to find an element that does not eixst. Try this:
// Always let inf indexs to first element and sup to last element after each loop
inf = 0;
sup = x - 1;
while (inf <= sup) {
mit = (inf + sup) / 2;
if (datos[mit].numprestamo == nucontrol) {
// printf ...
break;
} else if (datos[mit].numprestamo > nucontrol) {
sup = mit - 1;
} else {
inf = mit + 1;
}
}
*/
Related
How can I display all of the elements stored in the array? I just only want to display all the inputted elements.
This is my code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct studinfo{
char remarks, name[100];
float first, second, finalave;
};
int main()
{
struct studinfo stud;
int i, n;
char temp;
printf("Enter Number of Student/s to be Stored: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\nEnter Student Name: ");
scanf("%c", &temp);
scanf("%[^\n]", stud.name);
printf("Enter 1st Sem Average: ");
scanf("%f", &stud.first);
printf("Enter 2nd Sem Average: ");
scanf("%f", &stud.second);
stud.finalave = (stud.first + stud.second) /2 ;
printf("\nThe Final Average: %f", stud.finalave);
printf("\n");
}
for (i = 0; i < n; i++)
{
if (stud.finalave > 1.0 && stud.finalave <= 1.25 )
{
stud.remarks = 'S';
}
else if (stud.finalave > 1.5 && stud.finalave <= 1.75)
{
stud.remarks = 'A';
}
else if (stud.finalave > 2.0 && stud.finalave <= 2.5)
{
stud.remarks = 'B';
}
else if (stud.finalave > 2.75 && stud.finalave <= 3.0)
{
stud.remarks = 'C';
}
else if (stud.finalave >= 3.00)
{
stud.remarks = 'F';
}
}
This is where the error in displaying:
printf("\n");
printf("Name\t\tAverage\t\tRemarks\t\tScholarship");
for (i = 0; i < n; i++)
{
printf("\n%s\t%f\t%c", stud.name, stud.finalave, stud.remarks);
}
}
My expected output for this code is that all the inputted elements will be displayed but it turns out that only the last inputted are detected. What should I do?
First, define an array of structures like struct studinfo stud[n] in replace of 'n' you can use any variable. Then when taking the input use stud[i].name here i represents the index of the array.
And for displaying you can use stud[i].name similar to getting input.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct studinfo{
char remarks, name[100];
float first, second, finalave;
};
int main()
{
int i, n;
char temp;
printf("Enter Number of Student/s to be Stored: ");
scanf("%d", &n);
struct studinfo stud[n];
for (i = 0; i < n; i++)
{
printf("\nEnter Student Name: ");
scanf("%c", &temp);
scanf("%[^\n]", stud[i].name);
printf("Enter 1st Sem Average: ");
scanf("%f", &stud[i].first);
printf("Enter 2nd Sem Average: ");
scanf("%f", &stud[i].second);
stud[i].finalave = (stud[i].first + stud[i].second) /2 ;
printf("\nThe Final Average: %f", stud[i].finalave);
printf("\n");
}
for (i = 0; i < n; i++)
{
if (stud[i].finalave > 1.0 && stud[i].finalave <= 1.25 )
{
stud[i].remarks = 'S';
}
else if (stud[i].finalave > 1.5 && stud[i].finalave <= 1.75)
{
stud[i].remarks = 'A';
}
else if (stud[i].finalave > 2.0 && stud[i].finalave <= 2.5)
{
stud[i].remarks = 'B';
}
else if (stud[i].finalave > 2.75 && stud[i].finalave <= 3.0)
{
stud[i].remarks = 'C';
}
else if (stud[i].finalave >= 3.00)
{
stud[i].remarks = 'F';
}
}
printf("\n");
printf("Name\t\tAverage\t\tRemarks\t\tScholarship");
for (i = 0; i < n; i++)
{
printf("\n%s\t%f\t%c", stud[i].name, stud[i].finalave, stud[i].remarks);
}
}
I have followed everything in the book, yet my average score fails me, every single time. I have debugged my program multiple times, in vain.
My minimal executable code:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
if (choice == 'S' || choice == 's') {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Hope that fulfilled the definition of an MRE.
So I have snipped off some bombastic lines, and the ones left are the important ones, I think.
The problem is in your function quiz, and in particular in the while (unsure) loop. In this loop, you add the most recent score to the running total:
allScore += g; //add current round's score to total
This should happen once per round played. But if the user inputs "S" or something invalid, your program sets
unsure = true;
which means the loop will run again, before the next round is played. It then adds the most recent score a second time to the grand total.
The most logical solution would be to move all the calculations of totals, maximum, minimum, average out of the while-loop. The loop serves a different purpose: it is for user interaction and reporting, not for processing results.
possible chance of multiple avg calculation for same round again. Keep flag to track accounting of score, so we will not do the same more than once till the game is not played again.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
bool acct = false;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
if (false == acct) {
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
acct = true;
}
if (showS &&(choice == 'S' || choice == 's')) {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Output:
Enter 'S' to show results
Enter 'P' to play another round
Enter 'R' to return to main menu
s
Round 2 score: 47/100
Highest score: 50/100
Lowest score : 47/100
Average score: 48.500000/100
****** Player: ******
I am suppoused not to use globals just functions. I don't know where to have int measurements[LENGTH], x, i; to work as it does. I also need a function to calculate de number of measurements(nrOfMeasurements) that user typed in in getMeasurements. for example if they typed in 4 instead f 10. This is needed for ex. to calculate the average.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <limits.h>
#define LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PRGRAM!\n",
*MenuMsg = "\n\t Menu \n\t v (View) \n\t e (Enter) \n\t c (Compute) \n\t r (Reset) \n\t q (Quit) \n\n";
int measurements[LENGTH],//not here
x, i;//not here
void getMeasurements(){
for(x=0; x<LENGTH; x++){
printf("Enter number #%d: ", x+1);
scanf("%d", &measurements[x]);
if(measurements[x]==0){
break;
}
}
return;
}
void getView(){
printf("\t\n");
printf("Your measurements:\n");
if(x>0){
for (i = 0; i < x; i++){
printf("\b %d ", measurements[i]);
}
}
else if(x==0){
printf(" [NO MEASUREMENTS]");
}
printf("\n");
}
void getCompute(){
int min = INT_MAX;
int max = INT_MIN;
int calculus;
float sum;
for(x=0; x<LENGTH; x++){
if (measurements[x]<min) min=measurements[x];
if (measurements[x]>max) max=measurements[x];
sum=sum+measurements[x];
calculus= measurements[x] - (sum/LENGTH);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum/LENGTH);
printf("\n\n");
}
int main(){
while(1){
char choice;
puts (MenuMsg);
scanf(" %c", &choice);
if(choice=='e')
getMeasurements();
else if(choice=='v'){
getView();
}
else if(choice=='c'){
getCompute();
}
else if(choice=='q'){
break;
}
}
return 0;
}
You can do something like this:
#include <stdio.h>
#define MAX_LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PROGRAM!\n";
const char *MenuMsg = "\n\t Menu \n"
"\t v (View)\n"
"\t e (Enter)\n"
"\t c (Compute)\n"
"\t r (Reset)\n"
"\t q (Quit)\n\n";
int getMeasurements(int *measurements, int length) {
int i;
for (i = 0; i < length; i++) {
printf("Enter number #%d: ", i+1);
scanf("%d", &measurements[i]);
if(measurements[i] == 0) {
break;
}
}
return i;
}
void getView(const int *measurements, int length){
int i;
printf("\t\nYour measurements:\n");
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
for (i = 0; i < length; i++) {
printf("\b %d ", measurements[i]);
}
printf("\n");
}
void getCompute(const int *measurements, int length) {
int min, max, calculus, i;
float sum = 0;
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
min = max = measurements[0];
for (i = 0; i < length; i++){
if (measurements[i] < min) min = measurements[i];
if (measurements[i] > max) max = measurements[i];
sum += measurements[i];
calculus = measurements[i] - (sum / length);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum / length);
printf("\n\n");
}
int main() {
int measurements[MAX_LENGTH];
int measurements_count = 0;
int run = 1;
while (run) {
char choice;
puts(MenuMsg);
scanf(" %c", &choice);
switch (choice) {
case 'e':
measurements_count = getMeasurements(measurements, MAX_LENGTH);
break;
case 'v':
getView(measurements, measurements_count);
break;
case 'c':
getCompute(measurements, measurements_count);
break;
case 'q':
run = 0;
break;
default:
printf("Wrong input\n");
break;
}
}
return 0;
}
I am having trouble doing my homework.
I am doing an RSA application which can encrypt and decrypt.
The problem is that after I Input things to encrypt the results are weird and I can't decrypt anything. This is because when I copied the results of encryption which are symbols, I got more weird stuffs.
I'm guessing it has something to do with my formula getting negative ASCIIs as results.
Below is what I tried, and, in order to understand what I meant by weird, just compile and try it out(I have some unused stuffs which I haven't removed yet):
Output:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define boolean int
#define true 1
#define false 0
//===================================================//
int p = 0;
int q = 0;
int n = 0;
int m = 0;
int divider = 2;
int tempdivider = 2;
int initial = 0;
int x = 0;
int y = 0;
char msg[100];
char alphabet[27];
//===================================================//
void cls();
void menu();
void init();
void reinit();
void inputencrypt();
//int encrypt(int num);
void encrypt();
char decrypt(char text[]);
int fpb(int num);
int d(int num);
int primecheck(int a);
boolean checkdigit(char text[]);
//===================================================//
int main() {
frontpage();
init();
menu();
getchar();
return 0;
}
//===================================================//
void cls() {
for (int i = 0;i < 25;i++) {
printf("\n");
}
}
//===================================================//
boolean checkdigit(char text[]) {
int len = strlen(text);
for (int i = 0;i < len;++i) {
if (text[i]<'0' || text[i]>'9') {
return false;
}
}
return true;
}
int primecheck(int a) {
if (a == 1) {
return false;
}
for (int i = 2;i < a;i++) {
if (a%i == 0) {
return false;
}
}
return true;
}
//===================================================//
void reinit() {
for (int i = 1;i < 27;i++) {
alphabet[i] = 'a' + i - 1;
}
p = 0;
q = 0;
n = 0;
m = 0;
divider = 2;
tempdivider = 2;
initial = 120;
x = 0;
y = 0;
}
void init() {
reinit();
do {
printf("p = ");
scanf("%d", &p);fflush(stdin);
if (!primecheck(p)) {
printf("must be prime number! \n");
}
} while (!primecheck(p));
do {
printf("q = ");
scanf("%d", &q);fflush(stdin);
if (!primecheck(q)) {
printf("must be prime number! \n");
}
} while (!primecheck(q));
n = p*q;
m = (p - 1)*(q - 1);
initial = m;
x = fpb(m);
y = d(m);
printf("n = %d\n", n);
printf("m = %d\n", m);
printf("e = %d\n", x);
printf("d = %d\n", y);
system("pause");
}
//===================================================//
void menu() {
char input[2];
int input1 = 0;
do {
do {
cls();
printf("main menu\n");
printf("================\n");
printf("1. encrypt\n");
printf("2. decrypt\n");
printf("3. exit\n");
printf(">> ");
scanf("%s", input);fflush(stdin);
if (checkdigit(input)) {
input1 = atoi(input);
}
} while (!checkdigit(input));
switch (input1) {
case 1:
int c;
char encrypted[100];
char word[100];
printf("input word to encrypt : ");
scanf(" %[^\n]", word);fflush(stdin);
for (int i = 0;i < strlen(word);i++) {
if (word[i] == ' ') {
encrypted[i] = ' ';
//i++;
}
else {
for (int j = 1;j < 27;j++) {
if (word[i] == alphabet[j]) {
c = 0;
c = pow(j, x);
c = c%n;
encrypted[i] = c;
break;
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", word[i]);
}
printf(" ]\n");
printf("\n\nEncrypted ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", encrypted[i]);
}
printf(" ]\n");
printf("\n\nEncrypted [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%c", encrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
case 2:
int temp[100];
char decrypted[100];
char wordx[100];
int h;
printf("input word to decrypt : ");
scanf(" %[^\n]", wordx);fflush(stdin);
for (int i = 0;i < strlen(wordx);i++) {
temp[i] = wordx[i];
//temp[i] -= 97;
//printf("%d ::: %c\n", temp[i], temp[i]);
}
for (int i = 0;i < strlen(wordx);i++) {
if (wordx[i] == ' ') {
decrypted[i] = ' ';
}
else {
h = 0;
h = pow(temp[i], y);
h = h%n;
decrypted[i] = h;
for (int j = 1;j < 27;j++) {
if (decrypted[i] == j) {
decrypted[i] = alphabet[j];
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", wordx[i]);
}
printf(" ]\n");
printf("\n\nDecrypted ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", decrypted[i]);
}
printf(" ]\n");
printf("\n\nDecrypted [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", decrypted[i]);
printf("%c", decrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
}
} while (input1 != 3);
}
//===================================================//
int fpb(int num) {
if (!primecheck(num)) {
if (num%divider == 0) {
num = num / divider;
divider = 2;
}
else {
divider++;
}
fpb(num);
}
else if (primecheck(num)) {
if (!primecheck(num + divider)) {
tempdivider++;
divider = tempdivider;
num = initial;
fpb(num);
}
else {
return num + divider;
}
}
}
int d(int num) {
for (int i = 1;i < num;i++) {
if ((x*i) % num == 1) {
return i;
}
}
}
You have a general comprehension problem. Your console is only able to represent 96 characters correctly (known as printable 7bit-ASCII characters, 0x20 to 0x7F), but a byte can hold 255 different values. Your encryption algorithm does not care about this limited range, it will encrypt any value in the range [0..255] into another value in the range [0..255]. So your ASCII input characters will most likely be encrypted into values that cannot be represented by your console correctly. Copy&Past will not work correctly for non-printable characters (like 0x0B, which is a tab).
But now you will wonder: Why does that work for e.g. E-Mails? Simply: Because those characters are converted into an ASCII representation. Please google a bit for Base64 encoding.
As an alternative, you can always stream your encrypted characters into a file and later read back from that. This way you will bypass the limitations of your console.
Btw: Please have a look at the documentation of printf() and you will know, why you get those negative values.
The encrypt option has these three statements consecutively
c = 0;
c = pow(j, x);
c = c%n;
and the last of those will leave c in the range 0..(n-1).
Apart from that, there is no else clause and int c; can remain uninitialised.
So all in all it is inevitable that when you print c values as characters you will get "weird" results.
As for negative values, char encrypted[100]; is probably signed char so any integer value in the range 128..255 assigned to that, although undefined behaviour, may possibly show up as a negative number because the signed char is promoted back to int when passed as format %d to printf.
No matter how I edit my program there seems to be overflow errors and mismatching type errors. Can someone help me to make this run without errors.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int choice;
int i;
int j;
char type;
int amount;
int don_count = 0;
int req_count = 0;
int flag;
char donations_inv_type[100][20];
int donations_amount[100];
char requests_inv_type[100][20];
int req_amount[100];
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
scanf("%d", &choice);
while (choice != 5) {
if (choice == 1) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
printf("\nDonation Added!\n\n");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], type) == 0)
flag = i;
}
if (flag == -99) {
strcpy(donations_inv_type[i], type);
donations_amount[i] = amount;
don_count++;
}
else
donations_amount[flag] += amount;
printf("Donation Added!\n");
printf("Press any key to continue . . .\n\n");
}
else if (choice == 2) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
strcpy(requests_inv_type[req_count], type);
req_amount[req_count] = amount;
req_count++;
}
else if (choice == 3) {
printf("\n\n-------- Fulfilling Requests--------");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], requests_inv_type[0]) == 0)
flag = i;
}
if (flag == -99)
printf("Cannot be Fulfilled\n\n");
else if (donations_amount[flag] > req_amount[0]) {
donations_amount[flag] -= req_amount[0];
printf("Request Fulfilled");
req_amount[0] = 0;
}
else if (donations_amount[flag] == req_amount[0]) {
printf("Request Fulfilled");
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
}
don_count--;
for (i = flag; i < req_count; i++) {
strcpy(requests_inv_type[i], requests_inv_type[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
}
req_count--;
}
else if (donations_amount[flag] < req_amount[0]) {
printf("Partially Fulfilled");
req_amount[0] -= donations_amount[flag];
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
don_count--;
}
}
}
else if (choice == 4) {
printf("Printing the Donations Table\n\n");
for (i = 0; i < don_count; i++) {
printf("%s %d", donations_inv_type[i], donations_amount[i]);
}
printf("Printing the Requests Table\n\n");
for (i = 0; i < req_count; i++) {
printf("%s %d", requests_inv_type[i], req_amount[i]);
}
}
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
}
}
Any help is greatly appreciated and I would love an explanation as to what I did wrong so that I can learn and not make the same mistakes next time.
Declare type as character array.
char type[50];
Remove & in scanf(). You should not use & while reading string.
scanf("%s", &type); ==> scanf("%s", type);
^
Here you want to copy integers not strings
strcpy(donations_amount[i], donations_amount[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
Modify like this
donations_amount[i]=donations_amount[i + 1];
req_amount[i]= req_amount[i + 1];
Instead of char type you need char type[100]
Error in your code:
if (strcmp(donations_inv_type[i], type) == 0)
// ^^^^ should be char*
Note: Functions strcmp() and strcpy() should be passed \0 nul-terminated array of char (or say string).
Your scanf should look like scanf("%s", type);