How to use research in C with struct? - c

Can someone help me? the error is in the research which is "pesquisar" in portuguese. I just wanna know why it doesn't work. The code is not printing the search result. Any help is good. The code is in portuguese but I think it won't be a problem. Thank u all.
struct fichacarro {
char fabricante[15];
char modelo[15];
char combustivel[10];
char cor[10];
char placa[10];
int ano;
int km;
float preco;
};
int inserir(struct fichacarro carro[], int *x, int *f) {
printf("\nModelo: ");
fflush(stdin);
fgets(carro[*x].modelo, 15, stdin);
printf("Fabricante: ");
fflush(stdin);
fgets(carro[*x].fabricante, 15, stdin);
printf("Combustivel (alcool, gasolina ou diesel): ");
fflush(stdin);
fgets(carro[*x].combustivel, 10, stdin);
printf("Cor (branco, preto ou prata): ");
fflush(stdin);
fgets(carro[*x].cor, 10, stdin);
printf("Placa: ");
fflush(stdin);
fgets(carro[*x].placa, 10, stdin);
printf("Ano: ");
scanf("%d", &carro[*x].ano);
printf("Kilometros: ");
scanf("%d", &carro[*x].km);
printf("Preco: ");
scanf("%f", &carro[*x].preco);
*x = *x + 1;
*f = *f + 1;
system("cls");
}
int excluir(struct fichacarro carro[], int *x, int *f) {
int k, j;
printf("Digite o indice do carro que quer excluir: ");
scanf("%d", &k);
k = k - 1;
if (k>*x || k < 0)
printf("Indice nao existe");
else {
j = k;
while (j<*x) {
strcpy(carro[j].modelo, carro[j + 1].modelo);
strcpy(carro[j].fabricante, carro[j + 1].fabricante);
strcpy(carro[j].combustivel, carro[j + 1].combustivel);
strcpy(carro[j].cor, carro[j + 1].cor);
strcpy(carro[j].placa, carro[j + 1].placa);
carro[j].ano = carro[j + 1].ano;
carro[j].km = carro[j + 1].km;
carro[j].preco = carro[j + 1].preco;
j = j + 1;
}
*x = *x - 1;
*f = *f - 1;
}
}
int pesquisar(struct fichacarro carro[], int *x, int f) {
int y, j;
char cor[10];
float preco;
char fabricante[15];
printf("\n----OPCOES DE PESQUISA----\n");
printf("1 - Ler o nome do fabricante e informar todos os veiculos deste fabricante.\n");
printf("2 - Pesquisar os dados de veículos com o preço dentro de um limite fornecido.\n");
printf("3 - Informar todos os veículos de determinada cor pesquisada\n\n");
printf("Opcao escolhida: ");
scanf("%d", &y);
switch (y) {
case 1:
printf("\nDigite o nome do fabricante: ");
fflush(stdin);
fgets(fabricante, 15, stdin);
j = *x;
while (j < f) {
if (strcmp(fabricante, carro[j].fabricante) == 0);
{
printf("\nCarro: %d", j); // <---it doesn't work
printf("\nModelo: %s\n", carro[j].modelo);// <---it doesn't work
}
j = j + 1;
}
system("pause");
system("cls");
break;
case 2:
printf("Preco limite: ");
scanf("%f", &preco);
j = *x;
while (j < f) {
if (carro[j].preco <= preco);
{
printf("\nCarro: %d", j); // <---it doesn't work
printf("\nModelo: %s", carro[j].modelo); // <---it doesn't work
printf("\nFabricante: %s", carro[j].fabricante);// <---it doesn't work
printf("\nCombustivel: %s", carro[j].combustivel); // <---it doesn't work
printf("\nCor: %s", carro[j].cor); // <---it doesn't work
printf("\nPlaca: %s", carro[j].placa); // <---it doesn't work
printf("\nAno: %d", carro[j].ano); // <---it doesn't work
printf("\nKm: %d", carro[j].km); // <---it doesn't work
printf("\nPreco: %f\n", carro[j].preco); // <---it doesn't work
}
j = j + 1;
}
system("pause");
system("cls");
break;
case 3:
printf("Cor: ");
fflush(stdin);
fgets(cor, 10, stdin);
j = *x;
while (j < f) {
if (carro[j].cor == cor);
{
printf("\nCarro: %d", j); // <---it doesn't work
printf("\nModelo: %s\n", carro[j].modelo); // <---it doesn't work
}
j = j + 1;
}
system("pause");
system("cls");
break;
default:
system("cls");
printf("Nao encontrado.\n\n");
system("pause");
system("cls");
break;
}
}
int main() {
struct fichacarro carro[49];
int n, x = 0, y, cont, f = 0;
printf("Numero de acoes: ");
scanf("%d", &n);
system("cls");
for (cont = 0; cont < n; cont++) {
printf("----OPCOES DE ESCOLHA----\n\n");
printf("1 - Inserir veiculo\n");
printf("2 - Excluir veiculo\n");
printf("3 - Pesquisar veiculo\n");
printf("4 - Sair\n\n");
printf("Opcao escolhida: ");
scanf("%d", &y);
switch (y) {
case 1:
inserir(carro, &x, &f);
break;
case 2:
excluir(carro, &x, &f);
break;
case 3:
pesquisar(carro, &x, f);
break;
case 4:
x = n;
break;
default:
system("cls");
printf("Nao encontrado.\n\n");
system("pause");
system("cls");
break;
}
}
return 0;
}

Related

Binary search without recursive

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;
}
}
*/

(C Language) Only show filled entries in list

I hope this will be the last time I ask something here. Everything in my Food Ordering Algorithm is finished, but showing the list of filled orders shows every slot available (0 to 100), rather than just the entries filled out. Any way to fix that?
Case 3: Shows all orders made. (But I want just the entries that are filled out, not the empty ones.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAM 100
typedef struct order
{
char nome[50];
char endereco[150];
char pedido[300];
char valor[10];
};
int main()
{
struct order lista[TAM];
int busca, acha, i, menu;
i = 0;
menu = 0;
int codigo = 0;
int c = 0;
while(menu != 4)
{
system("cls");
printf("====================\n");
printf("Selecione uma opcao\n");
printf("====================\n");
printf("1 - Cadastrar pedido\n");
printf("2 - Consultar pedido\n");
printf("3 - Emitir relatorio\n");
printf("4 - Sair\n");
scanf("%d", &menu);
fflush(stdin);
switch(menu)
{
case 1:
system("cls");
printf("Digite seu nome: \n");
scanf("%49[^\n]", lista[i].nome);
fflush(stdin);
printf("Digite seu endereco: \n");
scanf("%149[^\n]", lista[i].endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
scanf("%299[^\n]", lista[i].pedido);
fflush(stdin);
printf("Digite o valor total: \n");
scanf("%9[^\n]", lista[i].valor);
fflush(stdin);
system("cls");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
system("pause");
i = i + 1;
codigo = codigo + 1;
break;
case 2:
system("cls");
printf("Insira o codigo que deseja buscar:\n");
scanf("%d", &busca);
fflush(stdin);
if(busca < codigo)
{
printf("=============================\n");
printf("Codigo: %d\n", busca);
printf("Nome: %s\n", lista[busca].nome);
printf("Endereco: %s\n", lista[busca].endereco);
printf("Pedido: %s\n", lista[busca].pedido);
printf("Valor total: %s\n", lista[busca].valor);
printf("=============================\n");
system("pause");
}
else
{
printf("\n Codigo nao encontrado\n");
system("pause");
break;
}
break;
case 3:
system("cls");
c = 0;
for(i = 0; i < TAM; i++){
printf("=============================\n");
printf("Codigo: %d\n", c);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
c = c + 1;
}
system("pause");
break;
case 4:
return 0;
default:
printf("Opcao invalido\n");
system("pause");
}
}
return 0;
}
change
for(i = 0; i < TAM; i++){
to
for(i = 0; i < codigo ; i++){
codigo is the count og entrries, TAM is the max number of entries

Can't input new order

Okay, hopefully after this, I won't ask anymore questions here. I redid the entire code, replacing gets() with scanf(). Now though, whenever I choose to put a new order for the program, I just put the name and the process just ends, showing "return value 3221225477", preventing me from typing in the address, request and price. I screwed up somewhere, but I don't know what. Here's what I did:
Translation:
Case 1: Type name, address, order, total price.
Case 2: Search for code (Issue: new string overwrites old one constantly)
Case 3: Show list of all orders created.
Case 4: Exit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAM 100
struct order
{
char nome[50];
char endereco[150];
char pedido[300];
char valor[10];
};
int main()
{
struct order lista[TAM];
int busca, acha, i, menu;
menu = 0;
int codigo = 0;
int c = 0;
while(menu != 4)
{
system("cls");
printf("====================\n");
printf("Selecione uma opcao\n");
printf("====================\n");
printf("1 - Cadastrar pedido\n");
printf("2 - Consultar pedido\n");
printf("3 - Emitir relatorio\n");
printf("4 - Sair\n");
scanf("%d", &menu);
fflush(stdin);
switch(menu)
{
case 1:
system("cls");
printf("Digite seu nome: \n");
scanf("%49[^\n]", lista[i].nome);
fflush(stdin);
printf("Digite seu endereco: \n");
scanf("%149[^\n]", lista[i].endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
scanf("%299[^\n]", lista[i].pedido);
fflush(stdin);
printf("Digite o valor total: \n");
scanf("%9[^\n]", lista[i].valor);
fflush(stdin);
system("cls");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
system("pause");
i = i + 1;
codigo = codigo + 1;
break;
case 2:
system("cls");
printf("Insira o codigo que deseja buscar:\n");
scanf("%d", &busca);
fflush(stdin);
i = 0;
acha = 0;
while(i < TAM && acha == 0)
{
if(codigo == busca)
{
acha = 1;
}
else
{
i = i + 1;
codigo = codigo + 1;
}
if(acha == 1)
{
printf("=============================\n");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
system("pause");
}
else
{
printf("\n Codigo nao encontrado\n");
system("pause");
break;
}
}
break;
case 3:
system("cls");
c = 0;
for(i = 0; i < TAM; i++){
printf("=============================\n");
printf("Codigo: %d\n", c);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
c = c + 1;
}
system("pause");
break;
case 4:
return 0;
default:
printf("Opcao invalido\n");
system("pause");
}
}
return 0;
}
well the immediate cause is this
int busca, acha, i, menu; <<<<=== declare i , but not set to a value
....
scanf("%49[^\n]", lista[i].nome); <<<==== use i
you must set i to zero
int i = 0;

I cannot pass the value from the file to the struct

I'm a beginner in C, I'm trying to read a file in order to update a struct but every time I do it it gives me an error (I'm working with visual studio 2013).
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Registro{
int cedula;
char nombre[20];
char apellido[20];
char direccion[50];
int ingreso;
};
void agregarP(struct Registro * informacion, int * n){
int op,i,aux;
printf("Cuantas personas desea agregar?\n");
fflush(stdin);
scanf_s("%i", &op);
aux = op;
op += *n;
for (i = *n; i < op; i++){
printf("Introduzca la cedula\n");
scanf_s("%i", &informacion[i].cedula);
printf("Introduzca el nombre\n");
fflush(stdin);
gets_s(informacion[i].nombre);
printf("Introduzca el apellido\n");
gets_s(informacion[i].apellido);
printf("Introduzca la direccion\n");
gets_s(informacion[i].direccion);
printf("Introduzca el ingrso anual\n");
scanf_s("%i", &informacion[i].ingreso);
system("cls");
}
*n += aux;
}
bool comprobacion(int n1, int n2){
if (n1 == n2){
return true;
}
else {
return false;
}
}
void borrar(struct Registro * s, int *n){
int i, ced;
struct Registro aux;
bool compr;
printf("Introduzca la cedula de la persona que desea borrar\n");
fflush(stdin);
scanf_s("%i",&ced);
for (i = 0; i < *n; i++){
if (s[i].cedula == ced){
compr = comprobacion(*n, i);
if (compr){
break;
}
else{
aux = s[*n - 1];
s[*n - 1] = s[i];
s[i] = aux;
break;
}
}
}
*n -= 1;
}
void mostrar(struct Registro * informacion, int n){
int i;
printf("Cedula \t Nombre \t Apellido \t Direccion \t Ingreso \n");
for (i = 0; i < n; i++){
printf("%i \t ", informacion[i].cedula);
printf("%s \t ", informacion[i].nombre);
printf("%s \t ", informacion[i].apellido);
printf("%s \t ", informacion[i].direccion);
printf("%i \n", informacion[i].ingreso);
}
}
void mostrarPorOrden(struct Registro * s, int n){
int i, j,cont = 0, op;
struct Registro aux;
printf("1 para mostrar por orden de cedula\n");
printf("2 para mostrar por orden de apellido\n");
fflush(stdin);
scanf_s("%i", &op);
switch (op){
case 1: for (i = 0; i < n+1; i++){
cont = 0;
for (int j = 0; j < n - 1; j++)
{
if (s[j].cedula > s[j + 1].cedula){
aux = s[j+1];
s[j + 1] = s[j];
s[j] = aux;
cont++;
}
}
if (cont == 0) break;
}
mostrar(s, n);
break;
case 2: for (i = 0; i < n + 1; i++){
cont = 0;
for (int j = 0; j < n - 1; j++)
{
if (s[j].apellido[0] > s[j + 1].apellido[0]){
aux = s[j+1];
s[j + 1] = s[j];
s[j] = aux;
cont++;
}
}
if (cont == 0) break;
}
mostrar(&s[0], n);
break;
}
}
void guardarArch(FILE * ff, struct Registro * s, int n){
fopen_s(&ff, "Datos.txt", "w");
int i;
for (i = 0; i < n; i++){
fprintf(ff,"%d", s[i].cedula); fprintf(ff, "\n");
fprintf(ff, s[i].nombre); fprintf(ff, "\n");
fprintf(ff, s[i].apellido); fprintf(ff, "\n");
fprintf(ff, s[i].direccion); fprintf(ff, "\n");
fprintf(ff, "%d",s[i].ingreso); fprintf(ff, "\n");
}
fclose(ff);
}
void leerArch(FILE * ff, struct Registro * s, int * n){
fopen_s(&ff, "Datos.txt", "r");
int i = 0;
while (!feof(ff)){
}
fclose(ff);
}
void main(){
FILE * infor = new FILE;
struct Registro informacion[30];
int op = -1;
int persona = 0;
while (op != 0){
printf("1 para agregar una persona\n");
printf("2 para mostrar\n");
printf("3 para borrar\n");
printf("4 para mostrar ordenado\n");
printf("5 para guardarlo en un archivo\n");
printf("6 para leer de un archivo\n");
printf("0 para salir\n");
scanf_s("%i", &op);
fflush(stdin);
switch (op)
{
case 1: agregarP(&informacion[0], &persona);
printf("%i", persona);
break;
case 2: mostrar(&informacion[0], persona);
break;
case 3: borrar(&informacion[0], &persona);
break;
case 4: mostrarPorOrden(&informacion[0], persona);
break;
case 5: guardarArch(infor, &informacion[0], persona);
break;
case 6: leerArch(infor, &informacion[0], &persona);
break;
}
system("pause");
system("cls");
}
}
PD: Sorry for my english.
Edited.
This is the part where I'm having trouble, it breaks automatically. It reads the stuff now but with a lot of new lines
int ayudaLeer(FILE * ff, struct Registro * s, int * n){
if (feof(ff)) return -1;
char * c = new char[];
int p = fgetc(ff);
fscanf_s(ff, "%d", &s[*n].cedula);
fgets(c, 20, ff);
fgets(s[*n].nombre, 20, ff);
fgets(s[*n].apellido, 20, ff);
fgets(s[*n].direccion, 20, ff);
fscanf_s(ff, "%d", &s[*n].ingreso);
*n+=1;
ayudaLeer(ff, s, n);
}
void leerArch(FILE * ff, struct Registro * s, int * n){
fopen_s(&ff, "Datos.txt", "r");
int i = 0;
ayudaLeer(ff, s, &i);
*n = i-1;
fclose(ff);
}

C calculator if else

I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.
#include <stdio.h>
int main(){
printf("\tCalculadora\n\n");
int num1, num2, total;
char oper;
printf("Introduza o primeiro numero: \n");
scanf("%d", &num1);
printf("Introduza o segundo numero: \n");
scanf("%d", &num2);
printf("Escolha a operacao que quer realizar!\n\n");
scanf("%c", &oper);
if(oper == '+'){
printf("O resultado e: %d", num1+num2);
}
else if(oper == '-'){
printf("O resultado e: %d", num1-num2);
}
else if(oper == '*'){
printf("O resultado e: %d", num1*num2);
}
else{
printf("O resultado e: %d", num1/num2);
}
getchar();
getchar();
}
I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.
#include <stdio.h>
#include <stdlib.h>
#define ISIZE 100 // arbitrarily large
int main(){
double num1, num2;
int oper;
char inp[ISIZE+1] = "";
printf("\tCalculadora\n\n");
printf("Introduza o primeiro numero: "); // 1st operand
fgets (inp, ISIZE, stdin);
num1 = atof (inp);
printf("Introduza o segundo numero: "); // 2nd operand
fgets (inp, ISIZE, stdin);
num2 = atof (inp);
printf("Escolha a operacao que quer realizar! "); // operator
fgets (inp, ISIZE, stdin);
oper = inp[0];
printf ("O resultado e: %f %c %f = ", num1, oper, num2);
switch (oper) {
case '+': printf("%f\n", num1+num2); break;
case '-': printf("%f\n", num1-num2); break;
case '*': printf("%f\n", num1*num2); break;
case '/': if (num2!=0) printf("%f\n", num1/num2);
else printf ("Divisão por zero!\n");
break;
default: printf("Eu não sei o que operador\n");
}
return 0;
}
This
scanf("%c", &oper);
should change to
scanf(" %c", &oper);
so you let scanf() ignore the '\n' left by previous scanf()s.
I was also trying to apply my knowladage of C in a simple calculator and came across you question. In order to respect your if...else request I've come up with this solution. I hope this helps.
#include <stdio.h>
void sayHello( ) {
printf("Hello\n"); }
// to say hello to the user
int add( int num1, int num2) {
num1 = num1 + num2;
return num1;
}
int minus( int num1, int num2) {
num1 = num1 - num2;
return num1;
}
int times( int num1, int num2) {
num1 = num1 * num2;
return num1;
}
int divide( int num1, int num2) {
num1 = num1 / num2;
return num1;
}
// This is to declare the calculations
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
char c;
char f;
int n1;
int n2;
int total;
// n1 = ' ';
// n2 = ' ';
sayHello();
do {
c = ' ';
printf("Insert the type of Calculation you want to make:\n");
printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
c = getchar();
if(c == 'd') {
printf("\nInsert the first number:");
scanf("%d", &n1);
printf("Insert the second number:");
scanf("%d", &n2);
total = add( n1, n2 );
printf("%d plus %d equals to %d\n", n1, n2, total );
flush_input(); } else {
if( c == 't') {
printf("insert the base number:");
scanf("%d", &n1);
printf("Insert the subtracting number:");
scanf("%d", &n2);
total = minus( n1, n2 );
printf("The difference between %d and %d is %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'l') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = times( n1, n2 );
printf("%d times %d equals %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'v') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = divide( n1, n2 );
printf("%d divided by %d equals %d\n", n1, n2, total );
flush_input();
} else {
printf("I couln't understand the instruction\n Reseting program\n");
}
}
}
}
f = ' ';
printf("\nDo you wish to make another calculation?\n");
printf("Choose (y)es or (n)ot: ");
f = getchar();
// scanf("%c", &c);
getchar();
} while( f != 'n' );
printf("\nThat's all folks!\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
//declaration of function
float cal (float a, float b, char o);
int main(int argc, char *argv[])
{
// declaration of variable
float num1,num2;
int inum1,inum2;
char o;
//initialization of variable
num1=0;
num2=0;
//input
printf("Enter 1st number\n");
scanf("%f",&num1);
//input
printf("operator\n");
scanf(" %c", &o);
//input
printf("Enter 2nd number\n");
scanf(" %f", &num2);
inum1=num1;
inum2=num2;
if(cal(num1,num2,o)==0)
{
printf("Math Error");
}
if(cal(num1,num2,o)==1)
{
printf("%d",inum1%inum2);
}
else
printf("%.3f\n",cal(num1,num2,o));
return 0;
}
//definening function
float cal (float a, float b, char o)
{
if (o=='+')
return a+b;
if (o=='-')
return a-b;
if (o=='*')
return a*b;
if (o=='%')
return 1;
if (o=='/')
if (b!=0)
return a/b;
if (b==0)
return 0;
}

Resources