This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?
int n();
int main(){
int num;
printf("Enter num:\n");
scanf("%d", &num);
n(num);
printf("The sum of %d is: %f", num, n(num));
return 0;
}
int n(int x){
if (x != 0){
return n(x) + n(x-1);
**strong text** }
else{
return x;
}
}
Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.
Also, in the last printf() function, %f should have been %d:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %d", num, n(num));
return 0;
}
Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.
If you really want to convert it to a float:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %f", num, (double) n(num));
return 0;
}
*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.
More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,
int n();
int main(){
int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
}
int n(int x){
if (x != 0){
return x + n(x-1);
**strong text** }
else{
return x;
}
}
Related
I am trying to make a program that takes two user inputs (x and y), checks all numbers in the interval for all prime numbers, and then prints only the three largest prime numbers if available. So far, my code checks all the prime numbers in an interval starting from the largest to the smallest.
My code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primeChecker(divisor+1,dividend);
}
void largestonly(int*counter, int*largest1, int*largest2, int*largest3){
int temp;
temp=*counter;
if (temp>*largest1&&*largest2) ///incomplete attempt
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y,largest1, largest2, largest3, counter, divisor, dividend, i;
divisor=2;
dividend=counter;
inputXY(&x, &y);
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for (i=0; i<=3; i++){
for(counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1) largestonly(&counter, &largest1, &largest2, &largest3);
}
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
I have yet to successfully write a working function that can sort all the integers produced by the for loop in main(). It is the largestonly() function as seen above. In relation to that, my printlargest() function undoubtedly does not work. My idea in here is that if largest1 does not contain any value (or is equal to 0 or some other more appropriate value that I could not think of), the function will only print the two largest prime numbers found. Relatively, if both largest1 and largest2 are empty, only the largest prime number will be printed. If all variables are empty, it should print "No prime numbers found!". I am very lost with what to do with my code at the moment so any type of help will be greatly appreciated. Thank you.
There are a few things to do here.
First, pay attention to the line 21, you call a primeChecker() function that doesn't exist. It will raise an error when compiling.
Second, you don't have to "sort" anything. You only have to store the prime numbers into the variables as they arrive. I noticed you consider largest3 to be the first one that has to be filled (at least it is what can be understood from printlargest()), this gives us the following:
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
Additionally, there is no need to pass the address of counter in the first place, as you won't need to modify it.
Lastly, in the main() function, you don't need a double loop. Think of it this way. If you were to do the exercise mentally, you'd go down the numbers, check if they were primes, and write them down if they satisfy the conditions: being primes and being the first, second or third. You wouldn't need to do it 3 times. Hence:
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
Also, the way you declared your variables without initializing them can sometimes be dangerous. In this case, as largest1, largest2 and largest3 weren't set to 0, you'd have had no chance to trigger any of the printlargest() cases. It may be because you were stuck on a part of your program you thought would also handle that but I still want to point it out, just in case.
EDIT: you could also add a condition in the for loop such that if largest1 is not equal to 0, it exits the loop. It would prevent the program to loop through (potentially) big amount of numbers when you already have everything you need. It would look like this (with the existing for loop, for context):
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
if(largest1 != 0)
break;
}
Hope this clears out the issues you had, feel free to ask anything if necessary, or to point out things I'd have misunderstood in your question.
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primechecker(divisor+1,dividend);
}
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
First, define how you would check for a prime number:
bool is_prime(int num)
{
if (num < 2)
return false;
for (int i = 2; i <= num / i; ++i)
if (num % i == 0)
return false;
return true;
}
Then, define a function that returns the 3 largest prime numbers in a given interval:
void get_max_3_in_range(int lo, int hi, int *max1, int *max2, int *max3)
{
*max1 = 0; // smallest
*max2 = 0;
*max3 = 0; // largest
int round = 0;
for (int i = lo; i <= hi; ++i) {
if (is_prime(i)) {
if (round % 3 == 0) *max1 = i;
if (round % 3 == 1) *max2 = i;
if (round % 3 == 2) *max3 = i;
++round;
}
}
if (*max1 > *max2) swap_int(max1, max2);
if (*max2 > *max3) swap_int(max2, max3);
}
Here is your swap():
void swap_int(int *v1, int *v2)
{
int tmp = *v1;
*v1 = *v2;
*v2 = tmp;
}
Driver program:
int main(void)
{
int x, y;
inputXY(&x, &y);
int max1, max2, max3;
get_max_3_in_range(x, y, &max1, &max2, &max3);
printf("x = %d\ty = %d\n", x, y);
printf("max1 = %d\tmax2 = %d\tmax3 = %d\n", max1, max2, max3);
}
Output:
Enter value of x: 0
Enter value of y: 100
x = 0 y = 100
max1 = 83 max2 = 89 max3 = 97
You can choose what to output in case one or more of the maximums is/are zero. Here, I chose to print them all.
Side note: Your inputXY() is very error-prone. Because if the user enters a string, your code will break. scanf() returns a value that you must check.
Following is a better version:
void inputXY(int *x, int *y)
{
for(;;) {
printf("Enter value of x: ");
if (scanf("%d", x) != 1)
flush_stdin();
else
break;
}
flush_stdin();
for(;;) {
printf("Enter value of y: ");
if (scanf("%d", y) != 1)
flush_stdin();
else
break;
}
}
And flush_stdin() (Never do fflush(stdin)!!) will clear what remained in the buffer, in case the user didn't enter (just) a number:
void flush_stdin(void)
{
scanf("%*[^\n]");
}
I am pretty new to C, and am working on a pretty big project. I am trying to make a calculator, and so far I only have the addition. They way it works is that it asks for how many numbers they want in the addition statement, and then I use a while() loop to try to get all the info. Just some side info - I am using the Cygwin terminal on a Windows 10 operating system.
#include <stdio.h>
int main(){
char Etype;
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%c", &Etype);
if(Etype == 'a' || Etype == 'A') {
int Anum;
int x = 1;
int y;
printf("How many numbers do you want in this addition statement?\n");
scanf("%f", &Anum);
while(x < Anum) {
printf("Emter number %d\n", x);
scanf("%d", &y);
x = x + 1;
}
}
}
whenever I answer how many numbers I want on my statement, nothing happens. I hope you can help, and if so thank you!
At the very least, you should either look at the compiler warnings, or get a better compiler and look at the compiler warnings.
clang-7 -pthread -lm -o main main.c
main.c:16:29: warning: format specifies type 'float *' but the argument has type
'int *' [-Wformat]
scanf("%f", &Anum);
~~ ^~~~~
%d
1 warning generated.
Perhaps you just forget to summary the answer.
To input an integer, you should use %d instead of %f.
What's more, x should be initialized with 0.
You can edit your codes as:
#include <stdio.h>
int main(){
char Etype;
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%c", &Etype);
if(Etype == 'a' || Etype == 'A') {
int Anum;
int x = 0; // count from 0
int y;
int sum = 0; // to summary the answer
printf("How many numbers do you want in this addition statement?\n");
scanf("%d", &Anum); // use %d to input integer
while(x < Anum) {
printf("Emter number %d\n", x);
scanf("%d", &y);
sum += y; // summary
x = x + 1;
}
printf("Answer: %d\n", sum); // print the answer after calculation
}
}
Or a clearer version:
#include <stdio.h>
int main(){
char eType[2];
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%s", eType);
if(eType[0] == 'a' || eType[0] == 'A')
{
int n, sum = 0;
printf("How many numbers do you want in this addition statement?\n");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int x;
printf("Enter number %d\n", i);
scanf("%d", &x);
sum += x;
}
printf("Answer: %d\n", sum);
}
}
I am new to the C programming language. I am attempting to run the code below an N amount of times (based on the user input of "Enter amount of iterations"). I am trying to do this using a for loop (also tried with a while loop) but have been unsuccessful.
Whenever I run the code below, my terminal continuously repeats "Enter two float numbers:". I have to close the terminal and reopen it to try again. Does the issue have to do with my for loop? I am interpreting my for loop as: "a=0; if a > 0; increment a". Is there a way I can set a limit for "if a > 0" or should I be using a while loop? If the user enters "3" for amount of iterations, I am expecting the program to ask "Enter two float numbers" 3 times (with the answer).
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
CORRECT ANSWER Formatted for readability:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
This should behave more like you would like it to:
#include <stdio.h>
static float sum(float m, float n)
{
return m + n;
}
int main(void)
{
float x, y;
int a;
printf("Enter amount of iterations: ");
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Invalid input for iterations\n");
return 1;
}
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
if (scanf("%f %f", &x, &y) != 2)
{
fprintf(stderr, "Failed to read to floating point numbers\n");
return 1;
}
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
Note that it checks that the input operations are successful, and reports errors on standard error (stderr). The code uses a standard C for loop to count from 0 up to a limit — this is idiomatic C. You should get used to using it.
As I noted in a comment, the a in the for loop is different from and unrelated to the a declared earlier in your code and set by the input operation. The a in the for loop is not initialized; you can't tell how many times the loop will be executed. A good compiler should warn you about redefining or shadowing a.
for (i = 0; i < a; i++); - answer provided by J.S!
At my university I was asked to create a program that asks the user for two inputs. One is the base and the other is the power of a number. I am not allowed to use math.h only loops.
This is my code thus far:
#include <stdio.h>
int main() {
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
for(reps = base; reps <= power; reps += 1) {
printf("* %d ", base);
}
for(number; number <= power;number += 1) {
int result = base * base;
for (result; number <= power; result = base * result) {
result = result * base;
printf("\n or %d", result);
}
}
return 0;
}
Please help me. I am so lost and I feel like crying :( not that it matters.
(Your main issue is that you are using an uninitialised variable; the behaviour of doing that in C is undefined.)
But let's rework the answer. The first thing to do is to separate the actual power function from all the input and output. With regards to that function, I'll put my favourite way into the answer pool on the understanding that you'll work through it carefully and understand it.
You can ace this problem using a technique called exponentiation by squaring:
int getPower(int base, int power/*must be non-negative*/)
{
int ret = 1;
while (power){
if (power & 1){ /*this means the current value of `power` is odd*/
ret *= base;
}
power >>= 1; /*ToDo - figure this out with your debugger*/
base *= base;
}
return ret;
}
The method is adequately explained in https://en.wikipedia.org/wiki/Exponentiation_by_squaring
The loop for calculating the power looks like this
int product = 1;
for(int multiplicationCounter = 1;multiplicationCounter <= power; multiplicationCounter ++) {
product *= base;
}
printf("Result is %d", product);
You can integrate this in your code, maybe change the output.
This should replace your whole second for-loop.
assume both base and power is positive integer,
then
int Result =1;
for (int i=0; i<=power;i++)
{
if(power==0)
Result=1;
Result =Result*base;
}
This should work
#include <stdio.h>
int main()
{
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
int result=1:
for(number=1; number <= power;number += 1)
{
result=result*base
}
printf("The result is %d", result);
return 0;
}
I have to create and call a function from main. Then I have to call scanf to read two integers and print out the bigger one. Then I have to do another scanf, but this time with doubles instead of integers.
int main()
{
int x, y;
scanf("%d%d", &x, &y);
if (x > y)
{
printf("%d", x);
}
scanf("%lf%lf", &w, &z);
if ( w > z)
{
printf("%f", w);
}
return 0;
}
I'm not sure if I did this right and how would I check the return value to see that the scanf worked? Thanks.
how would I check the return value to see that the scanf worked?
By checking the return value of scanf().
if( scanf("%d%d", &x, &y) != 2)
{
/* input error */
}
if (x > y)
{
printf("%d", x);
}
if(scanf("%lf%lf", &w, &z) != 2)
{
/* input error */
}
if ( w > z)
{
printf("%f", w);
}
From scanf() documentation:
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in
the event of an early matching failure.
The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF is also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set
indicate the error.
In your case, you can check whether scanf() has worked succesfully or not as follows,
if( scanf("%d%d", &x, &y) == 2)
{
if (x > y)
{
printf("%d", x);
}
}
else
{
printf("\nFailure");
}
scanf() returns the number of arguments successfuly read by it.
It says you're trying to call a function from main. Does that mean that your teacher wants a function besides main? In which case you want to create one as below. You will also have to do something similar only with double integers.
#include stdio.h
int bigger(void);
int main(void)
{
int larger;
larger = bigger(void);
printf("The Larger integer is: %d\n", larger);
return 0;
}
int bigger(void)
{
int x,y,z;
printf("Enter your first integer\n");
scanf("%d", &x);
printf("Enter your second integer\n");
scanf("%d", &x);
if(x > y)
{
z = x;
}
else
{
z = y;
}
return z;
}
sollution for
I have to create and call a function from main. Then I have to call scanf to read two integers and print out the bigger one. Then I have to do another scanf, but this time with doubles instead of integers.*/
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b;
printf("enter any two numbers");
scanf(" %d\n %d",&a,&b);
if(a>b){
printf("bigger number is %d",a);
}else{
printf("bigger number is %d\n",b);
}
float c,d;
printf("enter any two numbers");
scanf(" %f\n %f",&c,&d);
if(c>d){
printf("bigger number is %.2f",c);
}else{
printf("bigger number is %.2f\n",d);
}
system("pause");
return 0;`
}