Factorial calculator using functions in C - c

I am learning about functions and how to call upon them and use them in class. I don't quite understand where I've gone wrong here. I know that there are some mistakes around the int main part. I have asked my teacher and he is reluctant on giving me an example that would solve my problems or help me out. I think my main problem is at factorial_result = factorial();
#include <stdio.h>
void mystamp(void)
{
printf("My name is John Appleseed\n");
printf("My lab time is 12:30 on Sunday\n");
return;
}
int getnum(void)
{
int local_var;
printf("Please enter an integer: ");
scanf("%d%*c", local_var);
return(local_var);
}
int factorial(void)
{
int x,f=1,local_var;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial();
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}

Declare local_var as a global variable and do:
local_var = getnum();
OR
Change main() to:
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial(result);
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}
And factorial() to:
int factorial(int n)
{
int x,f=1,local_var=n;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}

Your factorial should be calculated based on the input( i.e in your case int result ).
So, your method factorial() should looks as follows :
int factorial( int number )
{
int factorial_value = 1;
while( number > 0 )
{
factorial_value *= number;
number--;
}
return factorial_value;
}
Then, the correct factorial would be returned and printed accordingly ! Regarding the scope of the variables that you have used, see the comments under your question.

#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}
This is a simple factorial program using recursion calling function !

include
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate its factorial\n"); scanf("%d", &n);
for (c = 1; c <= n; c++) fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}

Related

Factorial program in c

Trying to make a code that gets the factorial of the inputted number.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
int main()
{
int endvalue, numA, numB;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA, numB);
printf("%d", endvalue);
return 0;}
getch();
return 0;
}
For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)
int factorial(int number, int i)
{
for(i = number - 1; i>0; i--){
number = number * i;
}
if (number == 0) {printf("1");}
return number;
}
Is there anything I missed in the code that's causing these errors?
A definiton of factorial is:
factorial(0) = 1
factorial(n) = n * factorial(n-1)
Note: Factorial is legal only for number >= 0
In C, this definition is:
int factorial(int number)
{
if (number < 0)
return -1;
if (number == 0)
return (1);
/*else*/
return (number * factorial(number-1));
}
#include <stdio.h>
#include <string.h>
int factorial(int number)
{
int endval=1;
for(int i = number ; i>0; i--){
endval *= i;
}
return endval;
}
int main()
{
int endvalue=0;
int numA=0;
char userchoice[1];
printf("Enter a choice to make (f for factorial): ");
int ret=scanf("%s", userchoice);
if (!ret){
printf("Error in scanf: %d", ret);
}
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getchar();
return 0;
}
Code with some changes will work
factorial() function can get only one argument.
As a good habit all variables must be initialized.
Add include statement to source and be explicit not rely on compiler.
As we use strcmp() we must include string.h
use standard getchar() instead of getch()
Also can check return value of library function scanf() to ensure reading is correct or not.
You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.
There are possibly few things to correct. See please attached code.
int factorial(int number)
{
if (number == 0){ return 1; }
int endval=1, i;
for(i = 1; i<=number; i++) { endval *= i; }
return endval;
}
int main() {
int endvalue, numA;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0) {
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getch();
return 0;
}

program modularization (does the if else program below contain the process of modularization?)

hello sorry in advance because i ask a very simple question, but i really ask for help, i have a school assignment, but i don't know how to solve it, please help
Stimulation
After you study program modularization, does the if else program below contain the process of modularization?
#include <stdio.h>
main(){
int a,b,c, max;
printf("enter value a :");scanf("%d",&a);
printf("enter value b :");scanf("%d",&b);
printf("enter value c :");scanf("%d",&c);
//checking 1 program module
if((a>b)&&(a>c))
{
max = a;
printf("highest value checking 1 : %d" ,max);
}else if(b > c)
{
max=b;
printf("highest value checking 1 : %d" ,max);
}else{
max=c;
printf("highest value checking 1 : %d" ,max);
}
printf("\n");
int number1, number2, number3;
number1=a;
number2=b;
number3=c;
//checking 2 main programs
if((number1>number2)&&(number2>number3)){
max = number1;
printf("highest score checking 2 : %d" ,max);
}else if(number2 > number3)
{
max=number2;
printf("highest score checking 2 : %d" , max);
}else{
max=number3;
printf(highest score checking 2 : %d" ,max);
}
}
Identification of problems.
Write down the hypothesis from the results of the if else program study. Is the hypothesis alternative (the if else program line is in accordance with the concept of modularization) or the hypothesis is a null hypothesis (the if else program is not in accordance with the concept of modularization). Explain the hypothesis in detail, and point out which line of if else program strengthens your hypothesis statement!
The program is not modular.
Here is the analysis:
The two if/else blocks are nearly identical.
The printf statements are replicated code.
The scanf calls are replicated code.
The code can only handle three numbers.
Amongst other things, modularization is a process of eliminating replicated/duplicated code that is similar and placing the common code in [smaller] functions.
A good maxim to follow is that a given function: should do one thing well.
We can modularize the code in several steps:
Move the first if/else block into a separate function (e.g. getmax)
Eliminate duplicate printf in getmax
Make getmax more general so it can handle the second if/else more easily
Convert second if/else block in main to use getmax
Put user input (printf/scanf) into common function
Convert program to use arrays rather than individual scalars. This is particularly evident with: int number1,number2,number3;. It can be simplified into: int number[3];
Convert program to prompt user for number of elements in the array
Move the first if/else block into a separate function:
#include <stdio.h>
// checking 1 program module
int
getmax(int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
printf("highest value checking 1 : %d\n", max);
}
else if (b > c) {
max = b;
printf("highest value checking 1 : %d\n", max);
}
else {
max = c;
printf("highest value checking 1 : %d\n", max);
}
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax(a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Eliminate duplicate printf in getmax:
#include <stdio.h>
// checking 1 program module
int
getmax(int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest value checking 1 : %d\n", max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax(a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Make getmax more general so it can handle the second if/else more easily:
#include <stdio.h>
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Convert second if/else block in main to use getmax:
#include <stdio.h>
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
getmax("score",number1,number2,number3);
return 0;
}
Step 6: Put user input into common function:
#include <stdio.h>
// ask user for number
int
asknum(const char *prompt)
{
char buf[1000];
int num;
printf("enter value %s : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
a = asknum("a");
b = asknum("b");
c = asknum("c");
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
getmax("score",number1,number2,number3);
return 0;
}
Convert program to use arrays rather than individual scalars:
#include <stdio.h>
// ask user for number
int
asknum(int prompt)
{
char buf[1000];
int num;
printf("enter value %d : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// checking 1 program module
int
getmax(const char *what,const int *arr,int count)
{
int idx;
int val;
int max = -1;
if (count > 0) {
max = arr[0];
for (idx = 1; idx < count; ++idx) {
val = arr[idx];
if (val > max)
max = val;
}
printf("highest %s checking 1 : %d\n", what, max);
}
return max;
}
int
main(void)
{
int idx;
int count = 3;
int arr[count];
for (idx = 0; idx < count; ++idx)
arr[idx] = asknum(idx);
getmax("value",arr,count);
int number[count];
for (idx = 0; idx < count; ++idx)
number[idx] = arr[idx];
//checking 2 main programs
getmax("score",number,count);
return 0;
}
Convert program to prompt user for number of elements in the array
#include <stdio.h>
// ask user for number
int
asknum(const char *prompt)
{
char buf[1000];
int num;
printf("%s : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// ask user for array value
int
askval(int idx)
{
char prompt[100];
int num;
sprintf(prompt,"Enter array value %d",idx);
num = asknum(prompt);
return num;
}
// checking 1 program module
int
getmax(const char *what,const int *arr,int count)
{
int idx;
int val;
int max = -1;
if (count > 0) {
max = arr[0];
for (idx = 1; idx < count; ++idx) {
val = arr[idx];
if (val > max)
max = val;
}
printf("highest %s value : %d\n", what, max);
}
return max;
}
int
main(void)
{
int idx;
int count = asknum("Enter the number of array elements");
int arr[count];
for (idx = 0; idx < count; ++idx)
arr[idx] = askval(idx);
getmax("value",arr,count);
int number[count];
for (idx = 0; idx < count; ++idx)
number[idx] = arr[idx];
//checking 2 main programs
getmax("score",number,count);
return 0;
}

Finding factorial with C

just a newbie in C here. I'm trying to print out the factorial given the input using recursion & pointers, but when my input is 5, the output was 2293620. Can somebody help me with this? I'm not sure where did that number come from, because factorial of 5 should give me 120. Thanks for your help!
#include<stdio.h>
int countlength(int *num) {
int x = 1;
if (*num == 1) {
return 1;
} else {
return *num * countlength(num-1);
}
}
int main() {
int n, l;
printf("Enter number: ");
scanf("%d", &n);
l = countlength(&n);
printf("The factorial of %d is %d\n", n, l);
return 0;
}
Remove references from your code.
#include<stdio.h>
int countlength(int num) {
int x = 1;
if (num == 1) {
return 1;
} else {
return num * countlength(num-1);
}
}
int main() {
int n, l;
printf("Enter number: ");
scanf("%d", &n);
l = countlength(n);
printf("The factorial of %d is %d\n", n, l);
return 0;
}
In this case, I think you don't need to use pass by reference. You should use pass by value. Then your code will work perfectlyly
Change this line:
return num * countlength(num - 1);
to this:
int val = *num - 1;
return *num * countlength(&val);
So you correctly assign the value and pass it as a pointer.
int countlength(int *num) {
int x = *num - 1;
if (*num == 1) {
return 1;
} else {
return *num * countlength(&x);
}
}
int main() {
int n, l;
printf("Enter number: ");
scanf("%d", &n);
l = countlength(&n);
printf("The factorial of %d is %d\n", n, l);
return 0;
}```
**Try this**
int countlength(int *num) {
if (*num == 1) {
return 1;
} else {
return *num * countlength(&(*num - 1));
}
}
int main() {
int n, l;
printf("Enter number: ");
scanf("%d", &n);
l = countlength(&n);
printf("The factorial of %d is %d\n", n, l);
return 0;
}
try this

How to call function that counts digits in an integer

My function should get a non-negative integer, and return how many digits there are in the number, for Example for the number 563 the function return 3.
And for 0 will return 1.
*I'm new in c so it still very confusing for me.
Thanks.
Here is my code:
#include <stdio.h>
int numOfDigits(int n); //Declartion
void main()
{
int num1, counter = 0, newNum;
printf("Enter A Number: ");
scanf("%d", &num1);
}
int numOfDigits(int n1)
{
int counter = 0;
if (n1 == 0)
return 1;
while (n1 > 0) {
counter++;
n1 /= 10;
}
return counter;
}
What should I write to make the program work?
Just call the digit counting function that you made and assign its return value to a variable, and then print the value of that variable using printf() function; or alternatively, call your digit counting function inside printf() as an argument:
#include <stdio.h>
int numOfDigits(int n);
int main(void)
{
int num1;
int counter = 0;
printf("Enter A Number: ");
scanf("%d", &num1);
counter = numOfDigits(num1);
printf("number of digits: %d\n", counter);
//printf("number of digits: %d\n", numOfDigits(num1)); alternate method
}
int numOfDigits(int n1)
{
int counter = 0;
if (n1 == 0)
return 1;
while (n1 > 0) {
counter++;
n1 /= 10;
}
return counter;
}
A couple of notes:
Since you mentioned that you need to get a non-negative number, consider using unsigned int type, and change the format specifier inside scanf() and printf() call to "%u".
Function main should be declared as int main(void) or int main(int argc, char **argv)

Function for Pre-incrementing a variable return very wrong answer in C

I in my program, I'm attempting to create two different variables that will look the user's input integers and count how many are over 20 and how many are between 10 and 90. Unfortunately, both functions (counter_20 and between_count) return the same result, and when printed, it is an exorbitantly high and incorrect number. Any help would be greatly appreciated! My code is as follows:
#include <stdio.h>
#include <stdbool.h>
int getNumber(void);
float average_counter(int sum, int numCounter);
int counter_20(int input);
int between_counter(int input);
void print_results(int sum, int average, int numCounter, int sumOfTwenties, int betweenCount);
int main (void){
int a, b, c, e, f;
float d;
bool x = true;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
while(x = true){
if(a != 9999){
if(a != 0){
b += a;
c++;
d = average_counter(b, c);
e = counter_20(a);
f = between_counter(a);
}
else{
printf("No input was provided.");
}
}
else{
break;
}
}
print_results(b, d, c, e, f);
}
int getNumber(void){
int input;
printf("Please input an integer. If you would like to stop inputting integers and see the$
scanf(" %d", &input);
return input;
}
float average_counter(int sum, int numCounter){
float average;
average = sum/numCounter;
return average;
}
//One of my functions for counting the number of integers over 20
int counter_20(int input){
int countTwenties;
if(input > 20){
++countTwenties;
}
printf(" %d", countTwenties);
return countTwenties;
}
//my function for counting the integers between 10 1nd 90
int between_counter(int input){
int betweenCount;
if(input < 90){
if(input > 10){
++betweenCount;
}
else{
}
}
return betweenCount;
}
void print_results(int sum, int average, int numCounter, int countTwenties, int betweenCount){
printf("\nThe sum is: %d", sum);
printf("\nThe average is: %d", average);
printf("\nThe number of integers is: %d", numCounter);
printf("\nThe number of integers over 20 is: %d", countTwenties);
printf("\nThe number of integers between 10 and 90 is: %d", betweenCount);
return;
}
int counter_20(int input){
int countTwenties;
if(input > 20){
++countTwenties;
}
printf(" %d", countTwenties);
return countTwenties;
}
countTwenties is uninitialized and using uninitialized variables lead to undefined behavior. Fix it by initializing the variable like
int countTwenties=0;
As pointed out in my comment
while(x = true)
should be
while(x == true)
Normally compiler throws a warning when you have something like this in the code

Resources