I am implementing a polynomial using array. This is the Problem Statement:
Write a menu-driven program to represent Polynomials as a data structure using arrays. and write functions to add, subtract and multiply two polynomials; multiply a polynomial with a constant, find whether a polynomial is a "zero- polynomial, return the degree of the polynomial. Assume that a new polynomial is created after each operation. How would you input and output polynomials?
I have created the input and output functions. But my do while loop is running twice.. Help me finding out why.
The do-while loop
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
The print_menu() function
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
The create_poly() function
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly() function
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
Here is a sample output:
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:1
ch = 1
Enter size of the polynomial:2
Enter terms of the polynomial(coeff then exponent):
2 4
6 7
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:
ch =
Invalid choice.
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:q
ch = q
Tried flushing the stdinā¦ The problem stays. Printing the value of ch in each step, I think it is a whitespace. Where does the white space comes?
The answer to abnormal behavior of scanf answers this question also.
If you test the next code you will note the same problem
int main() {
char c;
do {
scanf_s("%c", &c);
if (c != 'q')
printf("test scanf() function\n");
} while (c);
}
the scanf() function works when the enter key is pressed, but this insert another char in the buffer input, the char of new line '\n', it is taken again by scanf() because the loop block. Try to change the previous code by this code:`
do {
scanf_s("%c", &c); // or c = getchar();
switch (c){
case '\n':
break;
default:
printf("test scanf() function\n");
}
} while (c);`
and will work fine. In your code only add a new case in the switch block:
switch(ch) {
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case '\n':
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
sorry, English is not my native language
There's an extra character waiting to be consumed after you make your initial choice, that's why the loop is executing twice.
See this question on the comp.lang.c FAQ
Related
i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');
When this program is executed and case 1 is chosen, a submenu will be displayed. In this submenu there is an option to go back to the main menu, now this isn't displaying properly when chosen as it seems to be displaying the main menu twice as well as the default. This is the code:
#include <stdio.h>
#include "functions.h" //calls the functions.h file
int switch1();
int switch2();
int main() {
//Declaring variable
char command;
do {
do {
printf(SPLIT);
printf("\nEnter choice to operate one of the following functions.\n");
printf("1 - Operate using integer representation\n");
printf("2 - Operate using textual representation\n");
printf("0 - Quit\n");
printf("Choice:");
scanf("%c", &command);
switch (command) {
case '1':
switch1(); //Executes function switch1
break;
case '2':
switch2(); //Executes function switch2
break;
case '0':
printf(SPLIT);
printf("\nQuitting.");
printf(SPLIT);
return 0; //Program stops
default: //Switch statement reaches default if no other cases are reached
printf("\nIncorrect input, please re-try.\nEnter choice\n");
break;
}
} while(command != '0');
} while (command < '0' || command > '2');
return 0;
}
int switch1() {
//Declaring variables
char command;
int *array, *iZeroed = NULL;
printf(SPLIT);
printf("\nInteger representation will be used!\n");
array = generate(); //Executes function generate and sets the return to be array
do {
do {
printf("\nChoose an option:\n");
printf("1) Shuffle the array\n");
printf("2) Sort the array\n");
printf("3) Zero an element from the array\n");
printf("4) Display previous zeroed out element\n");
printf("0) Go back to main menu\n");
printf("Choice:");
scanf(" %c", &command);
switch (command) {
case '1':
array = shuffle(array); //Executes function shuffle and sets the return to be the new array
break;
case '2':
array = sort(array); //Executes function shuffle and sets the return to be the new array
break;
case '3':
iZeroed = shoot(array); //Executes function shoot and sets the return to be the element changed to 0
break;
case '4':
target(iZeroed); //Executes function target
break;
case '0':
return 0;
default: //Switch statement reaches default if no other cases are reached
printf(SPLIT);
printf("\nIncorrect input. Please re-enter an option\n");
break;
}
} while (command != '0');
} while (command < '0' || command > '1');
return 0;
}
This is the output I am getting when I choose to go back to main menu:
====================================================================
Choose an option:
1) Shuffle the array
2) Sort the array
3) Zero an element from the array
4) Display previous zeroed out element
0) Go back to main menu
Choice:0
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Incorrect input, please re-try.
Enter choice
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Place a space character int the format string for scanf() before the input specifier %c, and it means scanf() should drop whitespace characters there.
You are already doing so in your switch1() function, so you should also do so in your main() function.
printf("Choice:");
scanf("%c", &command);
Make it " %c"
I am trying this code with exit case, the exit case doesn't work it still asks me for the two numbers and then it exits. I have provided the output. What is the alternative to the switch case that I can use for menu driven programs?
Sample input/output:
::::::Menu:::::
1. Addition:
2. Subtraction
3. Multiplication
4. Division
5. Mod
6. Exit
Enter your choice:6
Enter the values of a and b:3 4
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b,c;
int no;
do{
printf("\n::::::Menu:::::\n");
printf(" 1. Addition:\n 2. Subtraction \n 3. Multiplication \n 4. Division \n 5. Mod \n 6. Exit");
printf("\nEnter your choice:");
scanf("%d",&no);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
switch(no){
case 1:
c = a + b;
printf("\nAddition is:%d",c);
break;
case 2:
c = a - b;
printf("\nSubtraction is:%d",c);
break;
case 3:
c = a * b;
printf("\nMultiplication is:%d",c);
break;
case 4:
c = a / b;
printf("\nDivision is:%f",c);
break;
case 5:
c = a % b;
printf("\nMod is:%d",c);
break;
case 6:
exit(1);
default:
printf("\nInvalid choice\n");
break;
}
}while(no!=6);
return 0;
}
Your program asks for two numbers because you are checking for the exit code after the second scanf statement. If you wish the program to exit when 6 is entered, then you have to add an if statement in between the first and second scanf. You should additionally removed the exit case from your switch statement. Below is an example:
printf("\nEnter your choice:");
scanf("%d",&no);
if (no == 6)
exit(0);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
You're reading the user's menu option, then asking for the next two numbers before you get to the switch statement, so of course it will always ask for those two numbers.
You need to either check specifically for 6 right after reading the menu input, or you need to move the second prompts to only where they're needed, i.e. inside each case.
It keeps asking for the two numbers because the switch statement is positioned right AFTER you ask for the user input. I restructured your code, this should work:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b,c;
int no;
while(1){
printf("\n::::::Menu:::::\n");
printf(" 1. Addition:\n 2. Subtraction \n 3. Multiplication \n 4. Division \n 5. Mod \n 6. Exit");
printf("\nEnter your choice:");
scanf("%d",&no);
if (no == 6)
break;
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
switch(no){
case 1:
c = a + b;
printf("\nAddition is:%d",c);
break;
case 2:
c = a - b;
printf("\nSubtraction is:%d",c);
break;
case 3:
c = a * b;
printf("\nMultiplication is:%d",c);
break;
case 4:
c = a / b;
printf("\nDivision is:%f",c);
break;
case 5:
c = a % b;
printf("\nMod is:%d",c);
break;
default:
printf("\nInvalid choice\n");
break;
}
}
return 0;
}
Note how I changed the do-while to a while-true and explicitly check for no == 6 PRIOR to asking for user input.
The statements in C are meant to be executed sequentially unless you disrupt the normal flow of action using jumps. In your case
printf("\nEnter your choice:");
scanf("%d",&no);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
// Only now does the switch start.
You ask for the choice first and then for the two numbers. That is why you always end up in entering the two values. One way is to take the exit out of the switch-case which perhaps is the simplest solution I guess. Something like
printf("\nEnter your choice:");
scanf("%d",&no);
if ( 6 == no )
exit(1);
What is the alternative to the switch case that I can use for menu
driven programs
Well, switch-case is exactly made for that. Why think of an alternative?
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
int main()
{
char ch;
while(1)
{
printf("l.print l c.print c q. exit \n");
printf("enter choice ");
scanf("%c",&ch);
switch(ch)
{
case 'l':
printf("You have typed l \n");
break;
case 'c':
printf("yoh have typed c \n");
break;
case 'q':
exit(0);
}
}
return 0;
}
I have a very simple program like this
int main()
{
int opt;
int n;
int flag = 1;
while(flag)
{
printf("m inside while.Press c to continue\n");
if((opt = getchar())== 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
printf("m out\n");
return 0;
}
I get output like this:
m inside while.Press c to continue
c
choose a number
1
entered one
m broke
m inside while.Press c to continue
m inside while.Press c to continue
c
choose a number
My doubt is why "m inside while.Press c to continue" gets printed twice after every loop??
Thanks in advance
This is because of \n character left behind by previous scanf. When you input a number and press Enter key, an additional \n character passed to the standard input buffer. scanf reads that nuber leaving behind \n in the buffer. On next iteration of loop getchar reads \n before pressing any character by you and hence m inside while.Press c to continue printed twice as \n is not c.
Place this snippet of code just after the scanf statement in your while loop to eat up the newline characters
while(getchar() != '\n');
This will eat up any number of \n.
For more detailed explanation on the behavior of getchar read this answer.
You final code should be
int main()
{
int opt;
int n;
int flag = 1;
while(flag)
{
printf("m inside while.Press c to continue\n");
if((opt = getchar())== 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
while(getchar() != '\n');
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
printf("m out\n");
return 0;
}
After scanf reads the input there is a '\n' still in the buffer you have to clear it otherwise it will be readed by getchar in the next time and as it's != 'c' it will prompt again:
Try this :
printf("choose a number\n");
scanf(" %d",&n);
char c;
while (c = getchar != '\n' && c != EOF); // clear the buffer
while(flag)
{
printf("m inside while.Press c to continue\n");
while((opt=getchar()) != '\n') {
if(opt == 'c')
{
printf("choose a number\n");
scanf(" %d",&n);
switch(n)
{
case 0:
printf("m zero\n");
break;
case 1:
printf("entered one\n");
break;
case 3:
printf("m exit\n");
flag = 0;
break;
}
printf("m broke\n");
}
}
}
I'm using a while, switch, case statement for my menu and when it runs it keeps saying enter choice, I know while(1) creates an infinite loop but is there a way to avoid this?
while(1)
{
printf("\nEnter Choice \n");
scanf("%d",&i);
switch(i)
{
case 1:
{
printf("Enter value to add to beginning: ");
scanf("%c",&value);
begin(value);
display();
break;
}
case 2:
{
printf("Enter value to add last: ");
scanf("%c",&value);
end(value);
display();
break;
}
case 3:
{
printf("Value to enter before\n");
scanf("%c",&loc);
printf("Enter value to add before\n");
scanf("%c",&value);
before(value,loc);
display();
break;
}
case 4 :
{
display();
break;
}
}
}
Any help would be appreciated.
While(1) is ok. But you have to have some conditions to finish the loop. Like :
while(1){
.........
if(i == 0)
break;
............
}
Add a space at the beginning of every "%d" and "%c",because scanf always leaves a newline characters in buffer:
"%d"->" %d"
"%c"->" %c"
Alternative solution,
int i = !SOME_VALUE;
while(i != SOME_VALUE)
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
switch(i)
{
case SOME_VALUE: break;
.
.
.
// the rest of the switch cases
}
}
SOME_VALUE is any integer number notify to stop loop.
Alternatively, you may want to put a condition in the loop that relates to the input, e.g.
do
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
// the rest of the switch is after this
} while (i != SOME_VALUE);
Note the use of the do loop, which tests the condition at the end, after a value has been read into i.
I would probably write a function that can be called in the loop:
while ((i = prompt_for("Enter choice")) != EOF)
{
switch (i)
{
case ...
}
}
And the prompt_for() function might be:
int prompt_for(const char *prompt)
{
int choice;
printf("%s: ", prompt);
if (scanf("%d", &choice) != 1)
return EOF;
// Other validation? Non-negative? Is zero allowed? Retries?
return choice;
}
You can also find relevant discussion at:
scanf() validation.
What is the reason for error while returning a structure in this C program?
Common macro to read input data and check its validity