I've been trying to write a recursive function that scans a series of numbers and returns the sum of the numbers in odd indexes minus the sum of numbers in even indexes.
biggest problems: the function is not supposed to receive any parameters when called upon; and I have to do it in one function.
Edit: so, I wrote this code and it seems to work for the most part, but the problem is I wasn't supposed to send any parameters with the function (f wasn't supposed to exist)
void Ex1() // this is sort of like the main
{
int f = 1, res;
res = sumofodd_even(f);
printf("sum is: %d\n", res-1);
}
int sumofodd_even(int flag)
{
int num = 0;
printf("enter a number. to stop enter -1 >> \n");
scanf_s("%d", &num);
if (num != -1)
{
if (flag == -1)
num *= -1;
return num + sumofodd_even((-1) * flag);
}
}
btw: can't use pointers or arrays...
will appreciate any help.
One approach might be to just use a boolean flag that gets flipped at every recursion:
#include <stdbool.h>
#include <stdio.h>
int sumofodd_even(const bool odd) {
printf("enter a number. to stop enter -1 >> ");
int num = 0;
scanf("%d", &num);
if (num == -1) {
return 0; // breaks the recursion
}
num *= odd ? 1 : -1;
return num + sumofodd_even(!odd);
}
int main(void) {
printf("sum is: %d\n", sumofodd_even(false)); // zero is even, thus we start with odd == false
return 0;
}
you can use odd to mark if the read value should be treated as an odd number or as an even number, and thus change its sign accordingly.
Alternative to counting iterations or flipping a flag is to simply use two functions. After all, your algorithm has two states: process an even-indexed number, or process an odd-indexed number. Rather than have one function with an if statement, just use a function for each state, and have those functions transition between states by calling on each other.
int sum_of_odd() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_even() + num;
}
int sum_of_even() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_odd() - num;
}
And of course you'd start the algorithm by calling sum_of_odd(), since the first number is odd-indexed (unless you want to "index by zero").
Related
I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.
the question is "write a recursive function that ends when -1 is entered, than return how many times an even number was scanned.
naturals(int);
static void main() {
int num;
printf("enter numbers\n");
scanf("%d", &num);
naturals(num);
}
naturals(int num) {
int count = 0;
if (num % 2 == 0) {
count++;
}
if (num == -1) {
printf("%d", count);
return 0;
}
scanf("%d", &num);
return naturals(num);
}
i know that it resets "count" to 0 at the start of the function, how do i solve this?
This is a good place to make use of the ?: operator:
#include <stdio.h>
int naturals(int count)
{
int num;
scanf("%d", &num);
return num == -1 ? count : naturals(num % 2 == 0 ? count+1 : count);
}
int main(int argc, char **argv)
{
printf("enter numbers\n");
printf("even numbers entered = %d\n", naturals(0));
}
Here I'm passing 0 in as the initial count in the call to naturals in main, then for each number entered count is incremented if the number is even; otherwise we just pass the unincremented count to the next invocation of naturals. Prior to making the recursive call to naturals we check to see if the number entered is -1; if it is we return the current value of count, otherwise we proceed to make a recursive call to naturals.
If you prefer, the return line in naturals can be replaced with
if(num == -1)
return count;
else if(num % 2 == 0)
return naturals(count+1);
else
return naturals(count);
which is functionally the same. It has the disadvantage of having three separate return statements which IMO is more confusing, but YMMV.
You can't keep track of count inside your recursive function. As you have correctly observed, count is reset to 0 every time the function runs. Instead, you'll have to keep track of count outside of your function. Here are some ways of doing this:
Pass count as a parameter to your recursive function, update it, and have your recursive function return the new value;
Create a global variable count and update is as necessary every time the recursive function runs.
#include <stdio.h>
#include <math.h>l
naturals(int, int);
static void main() {
int num, count = 0;
printf("enter numbers\n");
scanf("%d", &num);
naturals(num, count);
}
naturals(int num, int count) {
if (num % 2 == 0) {
count += 1;
}
if (num == -1) {
printf("%d\n", count);
return 0;
}
scanf("%d", &num);
return naturals(num, count);
}
solved it thanks!
My assignment is to check if a number is prime, but I have to use three sections to do it. The first is the main body of code and that is followed by two functions. The first checks if the number is even, and the second checks if it is prime. I know this is a rather tedious way to check if a number is prime but it is meant to get us introduced to functions and function calls!
UPDATE
I have gotten it all to work besides printing the smallest divisor of a non prime number. I thought using i from the second function would work but it will not output. I have copied by code below -- please help if you have any suggestions!
#include <stdio.h>
#include <math.h>
int even (int);
int find_div (int);
int main() {
int num, resultEven, resultPrime, i;
printf("Enter a number that you think is a prime number (between 2 and 1000)> \n");
scanf("%d", &num);
while (num < 2 || num > 1000) {
if (num < 2) {
printf("Error: number too small. The smallest prime is 2.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else if (num > 1000) {
printf("Error: largest number accepted is 1000.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else {
}
}
resultEven = even(num);
resultPrime = find_div(num);
if (resultEven == 1) {
printf("2 is the smallest divisor of %d. Number not prime\n", num);
}
else if (resultPrime == 1) {
printf("%d is the smallest divisor of %d. Number not prime\n", i, num);
}
else {
printf("%d is a prime number.\n", num);
}
return 0;
}
int even(int num) {
if (num % 2 == 0) {
return 1;
}
else {
return 0;
}
}
int find_div(int num) {
int i;
for (i = 2; i <= (num/2); i++) {
if (num % i == 0) {
return 1;
}
if (num == i) {
return 0;
}
}
return i;
}
I would create a function for Wilsons theorem (p-1)! = 1 (mod p) iff p is prime, first off, to make the functions nice and easy you will only need the one. for numbers less than 1000 it should work fine.
something like,
//it will return 1 iff p is prime
int wilson(int p)
{
int i, result = 1;
for (i = 0; i < p; i++)
{
result *= i;
result = result % p;
}
return result;
}
however if your not printing check that you have included, at the top of your file
#include <stdio.h>
your
resultEven = even(num)
needs a ; at the end but that was mentioned in the comments, besides that your methodology though odd is correct, also you do not need the empy else, that can simply be removed and your good
UPDATE:
//if return value == 1 its prime, else not prime, and
//return value = smallest divisor
int findDiv(int p)
{
int i= 0;
for (; i <= n/2; i++)
{
//you number is a multiple of i
if (num % i == 0)
{
//this is your divisor
return num;
}
}
//1 is the largest divisor besides p itself/smallest/only other
return 1;
}
your function call is correct but you need a semi colon (;) at the end of:
resultEven = even(num)
otherwise this program effectively checks for evenness. To check for prime one way is to ensure the number has no factors other than one and itself. This is done by finding the div of every whole number from 2 to half of the number being tested using a for loop. If a number produces a div of 0 then it is not prime because t has a factor other than 1 and itself.
so my task is as follows: Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.
I have all of the variable add up correctly however cannot seem to get the function to stop on a prime number. To try to correct this I made the variable "primecheck" and set it to 2++ thinking that it would be every integer above 2 (obviously not possible but one could hope). any assistance would be much appreciated!
int main (void)
{
int sum = 0, num = 0, i = 0, primecheck = 0, two = 2;
primecheck = two++;
do
{
printf ("Enter an integer: ");
scanf ("%d", &num);
if (num % primecheck == 0 && primecheck != num)
{
sum += num;
}
} while (num % primecheck == 0 && primecheck != num);
i = sum;
printf("%s%d%s", "Sum = ", i, "\n");
}
One possibility would be to introduce a function which performs the primality check, which could be done by using check divisions by all smaller numbers and terminate the loops as soon as a prime number is found. An implementation can be found following this link; the code can be refactored to the follwing function for primality testing. The function returns 1 if n is prime and 0 otherwise. The implementation uses an explicit while loop as the requirements apparently demands it.
int is_prime(int n)
{
int i=3;
int flag=0;
if (n%2==0)
{
return 0;
}
do
{
if (n%i==0)
{
flag=1;
break;
}
i+=2;
}
while (i*i<=n);
return flag;
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}