Related
I know I can write this code with fewer lines and I did it before, but I tried with an "if else" chain to explore different ways to code the same program since I'm still learning the basics. But doing this way I can't get the result if the third conditional(C is the greater one) is true. Only if the third conditional is true the program finish without printing anything. What am I doing wrong?
#include <stdio.h>
#include <conio.h>
int main(){
int a, b, c = 0;
printf("Please insert three different numbers:\n");
printf("Insert A value:");
scanf("%d", &a);
printf("Insert B value:");
scanf("%d", &b);
printf("Insert C value:");
scanf("%d", &c);
//comparing A, B and C to find the greater number
if(a > b){
if (a > c){
printf("\nThe greater is A: %d", a);
}
}else if (b > a){
if(b > c){
printf("\nThe greater is B: %d", b);
}
}else{
printf("\nThe greater is C: %d", c);
}
getch();
return 0;
}
Change you if statements to this:
if(a > b && a > c){
printf("\nThe greater is A: %d", a);
}else if (b > a && b > c){
printf("\nThe greater is B: %d", b);
}else if (c > a && c > b){
printf("\nThe greater is C: %d", c);
}
Also, using the same structure you have, you can use this:
if(a > b){
if (a > c){
printf("\nThe greater is A: %d", a);
}else {
printf("\nThe greater is C: %d", c);
}
}else if (b > a){
if(b > c){
printf("\nThe greater is B: %d", b);
}else{
printf("\nThe greater is C: %d", c);
}
This is the while loop and I would like to stop the loop a character 'q' is typed as an input. So when "Please enter the five requirements" appears and I type in q then it stops running
while (1)
{
printf("Please enter the five requirements:");
scanf("%d %f %f %d %d", &my, &mii, &mr, &ml, &mp);
printf("You entered: %d %f %f %d %d\n", my, mii, mr, ml, mp);
for (i = 0; i < 15; i++)
{
if (my <= mortGage[i].min_d && mii >= mortGage[i].max_iin && mr >= mortGage[i].max_rt &&
ml <= mortGage[i].min_l && mp >= mortGage[i].max_pf)
{
printf("name is : %s\n", mortGage[i].name_b);
printf("min duration is : %d\n", mortGage[i].min_d);
printf("max initial rate is : %f\n", mortGage[i].max_iin);
printf("max rate is : %f\n", mortGage[i].max_rt);
printf("min loan is : %d\n", mortGage[i].min_l);
printf("max product fees is : %d\n", mortGage[i].max_pf);
printf("\n");
}
else
{
printf("");
}
//if (my == 'q'|| mii == 'q' || mr == 'q' || ml == 'q' || mp == 'q')
//break;
}
}
I'm not sure if it can help you. This is what I do here:
#include <stdio.h>
int main()
{
int check;
while (1)
{
printf("Please enter the five requirements:");
check=scanf("%d %f %f %d %d", &my, &mii, &mr, &ml, &mp);
if(checker==0){
printf("Input Q\n");
break;
}else{
printf("You entered: %d %f %f %d %d\n", my, mii, mr, ml, mp);
for (i = 0; i < 15; i++)
{
if (my <= mortGage[i].min_d && mii >= mortGage[i].max_iin && mr >= mortGage[i].max_rt &&
ml <= mortGage[i].min_l && mp >= mortGage[i].max_pf)
{
printf("name is : %s\n", mortGage[i].name_b);
printf("min duration is : %d\n", mortGage[i].min_d);
printf("max initial rate is : %f\n", mortGage[i].max_iin);
printf("max rate is : %f\n", mortGage[i].max_rt);
printf("min loan is : %d\n", mortGage[i].min_l);
printf("max product fees is : %d\n", mortGage[i].max_pf);
printf("\n");
}else{
printf("");
}
}
}
}
return 0;
}
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: ******
The task is to read N digits within a range from 0 to 9 and find frequency of occurrence for entered digits. In addition to that, I need to find min and max values and also the most common number(s). Using at least 3 functions is required(storing input isn't allowed))
So far I completed finding occurrences and min and max value entered.
I have problems with finding the most common number(s) and creating functions. I have created separate variables for each number to find the frequency.
Also, this code doesn't seem to be very good and in case you have better solutions for this problem, please share.
{
int n=0;
int max=0,min=9;
int freq0=0,freq1=0,freq2=0,freq3=0,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0;
for (;;)
{
printf ("Please enter the number in range from 0 to 9 (to break enter: 11): ");
scanf ("%d",&n);
if (n==11)//to exit the loop 11 is setteled as a stop value
break;
if (n==0)
freq0++;
if (n==1)
freq1++;
if (n==2)
freq2++;
if (n==3)
freq3++;
if (n==4)
freq4++;
if (n==5)
freq5++;
if (n==6)
freq6++;
if (n==7)
freq7++;
if (n==8)
freq8++;
if (n==9)
freq9++;
if (n>max)
max=n;
if (n<min)
min=n;
}
printf ("Number 0 occured %d times\n",freq0);
printf ("Number 1 occured %d times\n",freq1);
printf ("Number 2 occured %d times\n",freq2);
printf ("Number 3 occured %d times\n",freq3);
printf ("Number 4 occured %d times\n",freq4);
printf ("Number 5 occured %d times\n",freq5);
printf ("Number 6 occured %d times\n",freq6);
printf ("Number 7 occured %d times\n",freq7);
printf ("Number 8 occured %d times\n",freq8);
printf ("Number 9 occured %d times\n",freq9);
printf ("highest %d \n", max);
printf ("smallest %d\n",min);
return 0;
}
#include <stdio.h>
#include <limits.h>
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
int main(void) {
int n=0;
int value_max=INT_MIN;
int value_min=INT_MAX;
int freq[10] = {0};
for(;;)
{
printf ("Please enter the number in range from 0 to 9 (to break enter: 11): \n");
scanf ("%d",&n);
if (n==11) break;
freq[n]++;
value_max = MAX(n, value_max);
value_min = MIN(n, value_min);
}
for(n=0; n<10; ++n)
{
if (freq[n] == 0) continue;
printf("Frequency of %d : %d\n", n, freq[n]);
}
printf("Maximum value : %d\n", value_max);
printf("Minimum value : %d\n", value_min);
return 0;
}
Test Input
4 5 6 1 2 3 4 5 6 11
Output
Frequency of 1 : 1
Frequency of 2 : 1
Frequency of 3 : 1
Frequency of 4 : 2
Frequency of 5 : 2
Frequency of 6 : 2
Maximum value : 6
Minimum value : 1
Try this.
#include <stdio.h>
int min(int a, int b) { return (a < b) ? a : b; }
int max(int a, int b) { return (a > b) ? a : b; }
int valid(int n) { return (n >= 0 && n <= 9) ? 1 : 0; }
int main() {
int i, n, min_number = 10, max_number = -1, max_frequency = 0;
int freq[10] = {0,0,0,0,0,0,0,0,0,0};
// Read all numbers from input (read until end of file or press Ctrl+Z in console)
while (scanf("%d", &n) > 0) {
if (valid(n) == 0) {
printf("Number %d is invalid and will be ignored\n", n);
continue;
}
freq[n] += 1;
min_number = min(min_number, n);
max_number = max(max_number, n);
max_frequency = max(max_frequency, freq[n]);
}
printf("Occurences of digits:\n");
for (i = 0; i < 10; i++)
printf("Number %d occured %d times\n", i, freq[i]);
printf("\n\nMin value: %d\n", min);
printf("Max value: %d\n", max);
// Print numbers with greatest frequency
printf("\n\nMost common numbers: ");
for (i = 0; i < 10; i++) {
if (freq[i] == max_frequency)
printf("%d\n", i);
}
return 0;
}
#include <stdio.h>
void test(int N){
int arr[] = {0,0,0,0,0,0,0,0,0,0};
for (int i =0; i < N; i++){
int num;
printf ("Please enter the number in range from 0 to 9 (to break enter: 11): ");
scanf ("%d",&num);
if (num==11) break;
if (num>9 || num<0){
printf("Number is not in range 0..9! Try another number..\n");
i--;
continue;
}
arr[num]++;
}
int max = 0, min = 9, max_occurrences = 0, min_occurrences = N;
for (int i = 0; i < 10; i++){
printf ("Number %d occured %d times\n", i, arr[i]);
max_occurrences = arr[max_occurrences] < arr[i] && arr[i]!=0? i : max_occurrences;
min_occurrences = arr[min_occurrences] > arr[i] && arr[i]!=0? i : min_occurrences;
max = max < i && arr[i]!=0? i : max;
min = min > i && arr[i]!=0? i : min;
}
printf("max occurrences : %d \nmin occurrences : %d \nmax common : %d \nmin common : %d \n ", max_occurrences, min_occurrences, max, min);
}
int main()
{
test(6);
return 0;
}
The calculator program was an assignment for my C introduction web class.
How would I better include this section: (currently included in every else if statement)
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
in the code without changing output?
Source code:
#include <stdio.h>
int laskesumma(int a, int b);
int laskeerotus(int a, int b);
int lasketulo(int a, int b);
int main(void)
{
int valinta, ekaluku, tokaluku;
do {
printf("1: kahden luvun summa\n2: kahden luvun erotus\n3: kahden luvun tulo\n<0: ohjelman lopetus\n\nValitse laskutoimitus:");
scanf("%d", &valinta);
if (valinta < 0)
{ printf("Ohjelma lopetetaan...\n\n"); }
else if (valinta == 1)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku,tokaluku));
}
else if (valinta == 2)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d - %d = %d\n\n", ekaluku, tokaluku, laskeerotus(ekaluku,tokaluku));
}
else if (valinta == 3)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d * %d = %d\n\n", ekaluku, tokaluku, lasketulo(ekaluku,tokaluku));
}
else
{ printf("Antamasi luku ei kelpaa.\n"); }
} while (valinta>0);
return 0;
}
//Addition
int laskesumma(int a, int b) {
int tulos;
tulos = a+b;
return tulos;
}
//Subtraction
int laskeerotus(int a, int b) {
int tulos;
tulos = a-b;
return tulos;
}
//Multiplication
int lasketulo(int a, int b) {
int tulos;
tulos = a*b;
return tulos;
}
Is there anything else I could fix for better readability or decreasing the size of the program?
One possibility is:
int ekaluku_tokaluku(int *ekaluku, int *tokaluku)
{
printf("\nSyötä ensimmäinen luku:");
if (scanf("%d", ekaluku) != 1)
return EOF;
printf("Syötä toinen luku:");
if (scanf("%d", tokaluku) != 1)
return EOF;
return 0;
}
Note that the variables are passed to the function as pointers, so there is no & in the scanf() calls. Some people might use a prefix such as p_ekaluku (or pEkaluku) on the names to indicate that they're a pointer.
You'd use it like this:
else if (valinta == 1)
{
if (ekaluku_tokaluku(&ekaluku, &tokaluku) != 0)
break;
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku, tokaluku));
}
Returning 0 on success is a common pattern. It's always worth checking that your code handles EOF conditions. You could consider adding fflush(stdout); after the printf() and before the scanf() statements in the function.
Just use a function if you're repeating those lines of codes a lot and return the integer value.
int userInput() {
int ekaluku;
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
return ekaluki;
}
Whenever you repeat a code block somewhere in your program, you should always consider to put that code block into a function. That will make it much easier to maintain your code.
Besides that I'll suggest that you don't use scanf - it has many surprises. For instance try to give your program the input 1a
Instead use sscanf and fgets as they'll give you less surprises.
The function could look like:
int get_input(FILE *fp, int n)
{
int d = 0;
char line[LINESIZE];
if (n > 0)
{
printf("Input the %d. number\n", n);
}
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
if (sscanf(line, "%d", &d) != 1)
{
printf("Error reading input\n");
return 0;
}
return d;
}
and it can be used like:
do
{
printf("1: kahden luvun summa\n2: kahden luvun erotus\n3: kahden luvun tulo\n<0: ohjelman lopetus\n\nValitse laskutoimitus:");
valinta = get_input(stdin, 0);
if (valinta < 0)
{
printf("Ohjelma lopetetaan...\n\n");
}
else if (valinta == 1)
{
ekaluku= get_input(stdin, 1);
tokaluku= get_input(stdin, 2);
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku,tokaluku));
}
This can be a little bit shorter (number of lines):
int laskesumma(int a, int b) { return (a+b);} //Addition
int laskeerotus(int a, int b){ return (a-b);} //Subtraction
int lasketulo(int a, int b) { return (a*b);} //Multiplication
but lower readibility in case of needed more complicated functions...
reduce code like this
#include <stdio.h>
#define make_func(name, op)\
static inline int name(int a, int b){\
return a op b;\
}\
/**/
make_func(laskesumma , +) //Addition
make_func(laskeerotus, -) //Subtraction
make_func(lasketulo , *) //Multiplication
#define op(no) ( " +-*"[no] )
typedef int (*Func)(int,int);
#define func(no) ( (Func[]){ 0, laskesumma, laskeerotus, lasketulo}[no] )
enum { QUIT, ADD, SUB, MUL };
int main(void){
int valinta, ekaluku, tokaluku;
do {
printf("%d: kahden luvun summa\n"
"%d: kahden luvun erotus\n"
"%d: kahden luvun tulo\n"
"<%d: ohjelman lopetus\n\n"
"Valitse laskutoimitus:", ADD, SUB, MUL, QUIT);fflush(stdout);
scanf("%d", &valinta);
switch(valinta){
case ADD:
case SUB:
case MUL:
printf("\nSyota ensimmainen luku:");fflush(stdout);
scanf("%d", &ekaluku);
printf("Syota toinen luku:");fflush(stdout);
scanf("%d", &tokaluku);
printf("%d %c %d = %d\n\n", ekaluku, op(valinta), tokaluku, func(valinta)(ekaluku, tokaluku));
break;
default:
if(valinta < QUIT){
printf("Ohjelma lopetetaan...\n\n");
return 0;
}
printf("Antamasi luku ei kelpaa.\n");
}
} while (valinta > QUIT);
return 0;
}
Try to use switch case in your code
do
{
if(valinta<0)
printf("Ohjelma lopetetaan...\n\n");
switch(valinta)
{
case 1:
case 2:
case 3:
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
break;
default: printf("Antamasi luku ei kelpaa.\n");
}
}while(valinta>0);