I have to do a short assignment for my introductory C class, where I have to ask for a number "N" from the user and calculate it's factorial. The requirements were for me to create a function with the prototype long int factorial(int N). I managed to do it, but I'm confused as to why my code is working with a specific change I made. Here is my code:
#include <stdio.h>
long int factorial(int);
int main(void)
{
int N;
printf("Enter a number: ");
scanf("%d", &N);
printf("The factorial of %d is: %ld", N, factorial(N));
return 0;
}
long int factorial(int N)
{
long int result=1 ;
int i;
for(i=1; i<=N; i++)
result = result * i;
return result;
}
My code at this point didn't work, and would just return the result of N+1 (if I input 5 for example, it would output 6). I was tweaking random things at this point to see what was the problem, and the removal of "void" in my main function fixed it. The problem is, I don't understand why.
#include <stdio.h>
long int factorial(int);
int main()
{
int N;
printf("Enter a number: ");
scanf("%d", &N);
printf("The factorial of %d is: %ld", N, factorial(N));
return 0;
}
long int factorial(int N)
{
long int result=1 ;
int i;
for(i=1; i<=N; i++)
result = result * i;
return result;
}
Could anyone explain why the removal of void in my code fixed this?
Related
#include <stdio.h>
#include <conio.h>
int sum();
//find the sum of two numbers entered by the user.
int main(){
int n, m;
printf("Enter two numbers: \n");
scanf("%d", &m);
scanf("%d", &n);
int result = sum(m, n);
printf(result);
getch();
return 0;
}
int sum(m, n){
int c;
c = m+n;
return c;
}
i was just writing a simple program with function but i don't know why it is not running it tells me to debug can someone tell me what is the problem with it
Change int sum() ; to int sum(int, int) ;
Change printf(result) to printf("%d", result) ;
Change int sum(m, n) to int sum(int m, int n) ;(https://i.stack.imgur.com/Z07cx.jpg)
Another way of writing above program is
(https://i.stack.imgur.com/VOXRY.jpg)
#include <stdio.h>
#include <conio.h>
int sum(int n, int m);
//find the sum of two numbers entered by the user.
int main(){
int n, m;
printf("Enter two numbers: \n");
scanf("%d", &m);
scanf("%d", &n);
int result = sum(m, n);
printf("%d",result);
getch();
return 0;
}
int sum(int n, int m){
int c;
c = m+n;
return c;
}
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.
I was trying to construct a program to calculate factorial using user defined function but it is giving a garbage value this program was an assignment for c-cat preparation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int accept_num(); // Function call
int fact(); // Function call
void display_num(); // Function call
int main()
{
int num;
num = fact(); //calling factorial
display_num(num); //calling printf
}
//take input
int accept_num()
{
int n;
printf("Enter number: ");
scanf("%d",&n);
return n;
}
//calculate factorial
int fact()
{
int i,num1;
unsigned long long factr=1;
num1 = accept_num();
for(i=1; i<=num1; i++)
{
factr *= i;
}
return factr;
}
void display_num(int num2)
{
printf("Answer = %llu",num2);
}
Mismatching types often leads to garbage value. After calculating factorial, you stored it to int type and in display_num() function you are printing unsigned long long int which has more number of bits reserved than int. Also if you use int i it will result into false value of factorial after loop iterates after limit of int.
Below is the refined code, replace every int with unsigned long long int:
#include<stdio.h>
#include<stdlib.h>
unsigned long long int accept_num(); // Function call
unsigned long long int fact(); // Function call
void display_num(); // Function call
int main()
{
//changed the datatype of num
unsigned long long int num;
num = fact(); //calling factorial
display_num(num); //calling printf
}
//take input
unsigned long long int accept_num()
{
//changed datatype of n
unsigned long long int n;
printf("Enter number: ");
scanf("%llu",&n);
return n;
}
//calculate factorial
unsigned long long int fact()
{
unsigned long long int i;
//changed datatype of num1
unsigned long long int num1;
unsigned long long int factr=1;
num1 = accept_num();
for(i=1; i<=num1; i++)
{
factr *= i;
}
return factr;
}
//changed datatype of argument num2
void display_num(unsigned long long int num2)
{
printf("Answer = %llu",num2);
}
Also, there are more redundant variables which can be reduced. Refer to this code:
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int inputNumber;
printf("Enter a positive integer: ");
scanf("%d",&inputNumber);
printf("Factorial of %d = %ld", inputNumber, multiplyNumbers(inputNumber));
return 0;
}
//calculate factorial using recursion
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
I would like to write a program which can find all prime numbers between two numbers in t test cases. But my program had crashed when I run it.
Please, could anyone help me?
My code:
#include <stdio.h>
#include <malloc.h>
#include <math.h>
void print(int a,int b)
{
int *p,i;
int x;
p = (int *) malloc (sizeof(int)*(b-a));
for(i=0;i<(b-a);i++) p[i]=a+i;
for(i=0;i<(b-a)/2;i++)
{
if(p[i]!=0)
{
if(p[i]%i==0) p[i]=0;
}
}
for(i=0;i<=(b-a);i++) if(p[i]!=0) printf("%d ",p[i]);
free(p);
}
int main(void)
{
int t,i,m,n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&m,&n);
print(m,n);
}
return 0;
}
The problem is stumbling on allocating memory in a range, allocating one element too few (should have been malloc (sizeof(int)*(b-a+1));) and then not sticking to indexing the memory allocated. This could be so much simpler: no arrays needed - if a number has a divisor, there is no need to check any other divisors.
Sometimes it is easier to side-step the problems than struggle with them.
#include <stdio.h>
#include <math.h>
int prime(int n)
{
int s, i;
if (n == 1 || n == 2)
return 1;
if (n % 2 == 0) // no even numbers
return 0;
s = (int)sqrt(n); // limit the loop
for (i=3; i<=s; i+=2) // odd numbers only
if (n % i == 0)
return 0;
return 1;
}
void print(int a, int b)
{
int n;
for (n=a; n<=b; n++)
if (prime (n))
printf("%d ", n);
printf("\n");
}
int main(void)
{
int t, i, m, n;
printf("Input number of ranges to test: ");
scanf("%d", &t);
for(i=0; i<t; i++)
{
printf("Input bottom and top of range: ");
scanf("%d %d", &m, &n);
print(m, n);
}
return 0;
}
You messed up the termination of the for-loops. You allocated b-a bytes but you are iterating over b-a+1 items...
for(i=0;i<=(b-a);i++) p[i]=a+i;
needs to be a i<(b-a) or else you have a segfault (in both loops).
Also as BLUEPIX pointed out:
for(i=0;i<b/2;i++)
needs to be i<(b-a)/2 for iterating over half the intervall.
p[i]%i
Division by zero in the first iteration i==0.
After this the programm should terminate without an error.
I am learning function in C. I want to sum multiple integers using arguments in function. I managed to write a code for adding two integers, but how if I want to add multiple integers and print the total of them? please guide me. Code which i wrote is;
#include<stdio.h>
#include<conio.h>
int sum(int a, int b, int c);
int main (void){
int x,y,z;
clrscr();
printf("Enter first integer to add.\n");
scanf("%d",&x);
printf("Enter second integer to add.\n");
scanf("%d",&y);
sum(x, y, z);
printf("Total = %d.\n",sum(x, y, z));
getch();
return 0;
}
int sum (int a, int b, int c){
c=a+b;
return c;
}
You can do something like this.
sum = 0;
while (ch == "y")
{
scanf("%d", &a);
sum+=a;
printf("Do you want to continue: ");
scanf("%c\n", &ch);
}
printf("%d", sum);
The idea is to have a variable sum whose initial value is 0.
Have a while loop that takes a integer a as input & add it to sum.
You can mantain a variable ch, which can be used to exit out of the loop. Only if the user enters "y", the user will be asked for integer again.
try this !
int main()
{
int var[100];
int count = 5;
printf("enter number %d number ", count);
for( int i = 0; i < count; i++ )
{
scanf( "%d", &var[i] );
}
printf("sum=%d", sum(var, count) );
return 0;
}
int sum( int var[], int count )
{
int sum = 0;
for( int i = 0; i < count; i++ )
{
sum += var[i];
}
return sum;
}
Currently you're overwriting the third argument to the function with the sum of the first two and return it. This should probably change a bit.
Just think about how you'd write a sum of three numbers in mathematics and you should see the solution.