I have a program that uses a tail recursion function to add the value entered and all the previous values. For example if the user enters 3, the function calculates 3+2+1 and gets an answer of 6. However this only sometimes works.
Here is my code below:
int addNum(int n);
int main(int argc, char *argv[]) {
int num;
printf("Enter an integer greater than zero, (q to quit): \n");
while(scanf("%d", &num) > 0){
if(num < 0){
continue;
}
else if(num == 0){
printf("Answer = 0 \n");
}
else{
printf("Answer = %d \n", addNum(num));
}
printf("Enter a positive number: \n");
}
return 0;
}
int addNum(int n){
int answer;
if(n > 0){
answer = n += addNum(n - 1);
}
return answer;
}
The output I get from this code is very peculiar. For numbers 0-6 I get the right answers. Once I get to 7 and 8 both the answers are incorrect. I keep going and 9-12 the answers are correct again. Then 13 and 14 are incorrect. It keeps going back and fourth like this. I have absolutely no clue what is going on if someone could help. If it is something simple and wrong with my code please don't give me the answer but rather a hint at the problem.
I will post the output below so you can see what is going on. I decided to use pastebin for my output to save room. http://pastebin.com/DjJfxJAT
You don't initialize answer in addNum(), so whenever you call it with n == 0, undefined behavior occurs since you end up returning an uninitialized value. It's only by luck that you ever get the right answer.
I think this code itself explains things
int addNum(int n);
int answer=0;
int main(int argc, char *argv[]) {
int num;
printf("Enter an integer greater than zero, (q to quit): \n");
while(scanf("%d", &num) > 0){
if(num < 0){
continue;
}
else if(num == 0){
printf("Answer = 0 \n");
}
else{
answer=0;
printf("Answer = %d \n", addNum(num));
}
printf("Enter a positive number: \n");
}
return 0;
}
int addNum(int n){
if(n > 0){
answer = n += addNum(n - 1);
}
return answer;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
#include <string.h>
#include <conio.h>
#include <math.h>
#include "helper2.h"
char validLoop = ' ';
int choice;
int validInput = 0;
main(){
repeat:
clrscr();
printf("=======================\nMenu\n=======================\n[1] Binary to Decimal\n[2] Sorting Algorithm(Ascending Descending)\n[3] Palindrome Checker\n=======================\n");
do{
printf("Enter Your Choice: ");
scanf("%d", &choice);
if (choice == 1 || choice == 2 || choice == 3){
validInput = 1;
}
else{
printf("Invalid Input! Please Input a value given within the choices.\n");
}
} while(validInput == 0);
if (choice == 1){
BinToDec();
}
if (choice == 2){
sorting();
}
if (choice == 3){
checker();
}
printf("\nPress Y||y to repeat or any key to exit.");
validLoop = getche();
if (validLoop == 'y' || validLoop == 'Y'){
goto repeat;
}
else{
return 0;
}
}
im getting errors on where my validLoop, choice, and validInput isnt being initialized and says "Declaration is not allowed here." it also says a statement is missing a ; on line 11. am i doing something wrong in my part?
edit: sorry, i forgot to add the header:
char checker(){
int i;
int check = 0;
char checker();
char word[50];
printf("Insert a string: ");
scanf("%s", &word);
for (i=0;i<strlen(word)/2;i++){
if (word[i] == word[strlen(word)-i-1]){
check++;
}
}
if (check == strlen(word)/2){
printf("%s is a palindrome", word);
}
else{
printf("%s is not a palindrome", word);
}
return 0;
}
int BinToDec(){
char binary[8];
int i;
int sum=0;
int value;
int length;
printf("Input binary number you want to convert to decimal: ");
scanf("%s", binary);
length = strlen(binary);
for (i=strlen(binary)-1;i>=0;i--){
value = length - (i + 1);
if ((int)binary[i]-48 == 1){
sum = sum + pow(2.0, (float)value);
}
}
printf("%d", sum);
getch();
return 0;
}
int sorting(){
int i;
int sort[10];
int min;
int temp;
int currentElement;
int compareElement;
printf("Input integers to sort: ");
for (i=0;i<10;i++){
scanf("%d", &sort[i]);
for (currentElement=0;currentElement<(sizeof(sort)/sizeof(sort[0]))-1;currentElement++){
min = currentElement;
for (compareElement=currentElement+1;compareElement<(sizeof(sort)/sizeof(sort[0]))-1;compareElement++){
if (sort[compareElement] < sort[currentElement]){
min = compareElement;
}
}
temp = sort[currentElement];
sort[currentElement] = sort[min];
sort[min] = temp;
}
printf("Ascending Order: ");
for (currentElement=0;currentElement<=(sizeof(sort)/sizeof(sort[0]))-1;currentElement++){
printf("%d, ", sort[currentElement]);
}
printf("\n");
printf("Descending Order: ");
for (currentElement=(sizeof(sort)/sizeof(sort[0]))-1;currentElement>=0;currentElement--){
printf("%d, ", sort[currentElement]);
}
printf("\n");
return 0;
}
basically the whole this is supposed to be a program to call my functions from the header file. everything was smooth sailing and it was even working before i tried adding validations on my part. i dont know if this really helps but i would appreciate every feedback with this. im using a turbo c emulator as my compiler and working environment.
printf("Input integers to sort: ");
for (i=0;i<10;i++){
scanf("%d", &sort[i]);
Seems closing } is missing. Writing actual definitions in header is not a good habit.
Other coding issues aside.
In the code that you show is in your header file you have the following line:
char checker();
within function char checker() I suspect that this is your culprit.
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)
So i'm having trouble making a program that asks the user to enter a number and then using that number I must increase the value of the pointer towards two_count and three_count. These are counter the factors of two's and three's in the number entered.
For example if the user input 2, then the program should spit out
"There have been 1 factor of 2 and 0 factors of 3"
Then the user can input 0 to exit program
What I have so far is
include <stdio.h>
void main()
{
int* two_count;
int* three_count;
int num;
while(two_count >= 0 || three_count >= 0)
{
printf("Enter a number: \n");
scanf("%d", &num);
if(num % 2)
{
two_count++;
}
else if(num % 3)
{
three_count++;
}
else if(num == 0)
{
printf("Thank you for playing, enjoy your day!\n");
break;
}
printf("So far, there have been %d factors of 2 and %d factors of 3\n", two_count, three_count);
}
}
Thanks!
If you want to use pointers, you can do it like this
int two_count = 0;
int* two_count_ptr = &two_count;
int three_count = 0;
int* three_count_ptr = &three_count;
Then, for retrieving value and incrementing you would need to dereference the pointer
while(*two_count_ptr >= 0 || *three_count_ptr >= 0)
(*two_count_ptr)++;
Hope this helps.
I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The code below is to read input from the user to check if an int [1-100] is a prime number or not. (If out of range, will print "Done). If non prime, will output that to the console and the number divisible.
Right now this program is running correctly for 1-10 except for 3 and 9... Any suggestions?
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101)
{
if (num==1||num==2)
printf("Prime\n");
for (i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}
First, make sure your code has appropriate whitespace. This will help you realize when things aren't lined up like you think they are.
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101){
if (num==1||num==2)
printf("Prime\n");
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}
Now you should realize that your else statement happens on the first check! So when 3 is not divisible by 2, it prints "prime."
And then it breaks out of the loop.
And this happens for EVERY number. All your program is doing is checking to see if numbers are divisible by 2.
If you wrote "Odd" instead of "Prime" it would at least be correct there.
This is the kind of problem where setting a flag might be useful (there are other ways to do this, but this is one way).
So you could set a flag, say int isPrime = 1;
Now, if you find out that the number is not prime, you simply set isPrime = 0;.
Finally, at the end of the for loop (let me repeat: AFTER the for loop finishes), you need to check that variable.
And you can say,
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
I'll let you figure out how to print the divisor :)
(For reference, correctly using the flag would look like this -- and for clarity I removed the 'feature' in which it continuously looped)
#include <stdio.h>
int main()
{
int num, i;
int isPrime = 1;
printf("Number [1-100]:? \n");
scanf("%d", &num);
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
isPrime = 0;
break;
}
}
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
printf("Done\n");
}
The reason why 3 is behaving differently is that the for logic never reaches 3. For "(i=2; i <= num/2; ++i)", if num equals 3, then the i (being 2) is no longer less than 3/2, which is 1 (after rounding off). So, you should add "num==3" check to the "if (num==1||num==2)".
You're not checking the entire range between 2 and num/2. You need a while loop and a prime flag.
Something like this.
while(num>0 && num <101)
{
unsigned char prime = 1; // set prime flag
i = 2;
while( i < (num/2)+1)
{
if(num%i == 0)
prime = 0;
i++;
}
if(num == 1)
prime = 0;
if(prime == 0)
printf("%d is nonprime\n", num);
else
printf("%d is prime\n", num);
prime = 1;
printf("Number[1-100]:? \n");
scanf("%d",&num);
}