exit previous recursions when we find the answer - c

I have a question in c programming(may in other languages too)
consider this program:
(I want to write the last input number that is dividable by 3 without using arrays and ... just with recursion)
int func( int n )
{
int a;
if (n==0)
return 0;
scanf("%d",&a);
function(n-1);
if(a%3==0)
{
printf("%d\n",a);
return 1;
}
}
but unfortunately, it prints numbers dividable by 3 in reverse order(I want just the last number dividable by 3)

You have to return the value to print, if it is valid and no other valid value has been returned previously (using -1 as invalid marker, for example)
int func (int n) {
int a;
if (n == 0)
return -1;
scanf("%d", &a);
int ret = func(n-1);
if ((ret == -1) && (a%3 == 0))
ret = a;
return ret;
}
Now you can print the return value of func().
printf("%d\n", func(100)); // For 100 values

Related

Counting the number of zero in an integer

The program would ask the user an integer input.
and it counts how many zero the int has.
constraints: use while loop
ex:
input: 2400
count: 2
now I have no problem in that part, only when the user would input a zero.
supposed it counts 1.
ex:
input 0
count: 1
but then the program returns count 0.
here's the code:
int main(){
int n, counter = 0;
printf("Enter the number: ");
scanf("%d", &n);
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
printf("%d", counter);
return 0;
}
Use functions.
int countZeroes(int x)
{
int result = !x; // if x == 0 then result = 1
while(x)
{
result += !(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("%d\n", countZeroes(0));
printf("%d\n", countZeroes(1000));
printf("%d\n", countZeroes(-202020));
}
https://godbolt.org/z/91hKr46eo
You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0
Here is what I would have done :
int main()
{
int num, count = 0;
scanf("%d",&num);
if (num == 0) {
printf("1");
return 0;
}
while(num != 0) //do till num greater than 0
{
int mod = num % 10; //split last digit from number
num = num / 10; //divide num by 10. num /= 10 also a valid one
if(mod == 0) count ++;
}
printf("%d\n",count);
return 0;
}
Just don't forget to consider everything that can happen with a condition that you set
**Fixed it
A different version that prints the integer as a string, and looks for '0' characters in it. Tested.
#include <stdio.h>
#include <string.h>
int main(void)
{
int input = 0;
int zeroes = 0;
char *foundpos, teststring[100];
scanf("%d", &input);
sprintf(teststring, "%d", input);
foundpos = strchr(teststring, '0');
while (foundpos != NULL) {
++zeroes;
foundpos = strchr(foundpos + 1, '0');
}
printf("%d contains %d zeroes", input, zeroes);
}
Just count the zero digits you get between \n chars.
#include <stdio.h>
int main()
{
int ndigs = 0, c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': ndigs++;
break;
case '\n': printf(" => %d zero digs", ndigs);
ndigs = 0;
break;
}
putchar(c);
}
}
sample output:
$ ./a.out
123001202010
123001202010 => 5 zero digs
^D
$ _
No need to convert digits to a number, to convert it back to decimal digits. You can improve the program counting digits until a nondigit is detected, then output. But there's no need to convert a decimal representation of a number (in base 10) to internal representation to then get the digits you have destroyed (in the conversion) back again to count them.
As earlier mentioned, the problem is with the loop:
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too.
You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way.
Just do as follows:
do{
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
} while( n != 0 );
This should work(if i didnt mess up the braces/semicolumns).

My input in scanf is not working, process is returned and I don't get any output

The Fibonacci series is not obtained on running this program. The whole process terminates after giving input in scanf.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n = 0)
return 0;
else if (n = 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
With scanf you need the give the address of the variable.
scanf("%d",&n); <= need to give the address of the integer
You can find some examples here:
http://www.cplusplus.com/reference/cstdio/scanf/
As you have already been told in Robert's answer, scanf expects an address for each format specifier. So, if format specifier %d is provided, the address of an integer is expected: scanf will write the value there.
If n is the variable containing the integer, &n is its address. Passing something that is not an address causes trouble: it is undefined behavior and will likely cause a segmentation fault.
There are also some problems in your Fibonacci generator. I suppose you want to print the n-th number in the sequence, but you iterate n times calling fibonacci() function (which only returns the last value) always with parameter i, which value is 0.
In fibonacci function you try to check for the exit conditions, but pay attention:
if (n = 0)
return 0;
doesn't check the value of n; it performs an assignment (the value of n will be 0 and the condition will be false). So it will proceed to the next "test"
if (n = 1)
return 1;
It is an assignment as well, 1 is assigned to n so the condition is true and 1 is returned. That's why you see 1 n times.
In order to make it work
correct the scanf issue
pass c to fibonacci()
correct the function so that the value is tested (== instead of =)
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, c;
printf("Print the fibonacci series\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(c));
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
You missed the & sign in the scanf statement, and also , I think you got confused with the assignment operator = and logical equal ==, in the Fibonacci function.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}

C Program - Finding the highest odd integer, stops when input a number less than 1.(Beginner)

I am currently taking programming classes this semester and at the moment we are using C language to program.
For this program it has to find the highest even integer among the values entered by the user. It stops asking values when a value less than 1 has been entered. If there is no even integer it should display "NO ODD INTEGER
at the moment this is what I have
#include<stdio.h>
#include<stdlib.h>
#define MAXNUMBERS 5
int find_maximum(int[], int);
int main()
{
int c, array[MAXNUMBERS], location, maximum, amount_numbers;
clrscr();
amount_numbers = getNumbers(array);
printf("Highest odd integer: ");
for (c = 0 ; c < MAXNUMBERS ; c++)
{
location = find_maximum(array, MAXNUMBERS);
maximum = array[location];
}
printf("%d", maximum);
getch();
}
int find_maximum(int a[], int n) {
int c, max, index;
max = a[0];
index = 0;
for(c = 1 ; c < n ; c++) {
if(a[c] > max && a[c] %1==1) {
index = c;
max = a[c];
}
}
return index;
}
int getNumbers(int arr[])
{
int c;
int n = 0;
printf("You may enter a max. %d numbers, enter a number less than 1 to end.\n", MAXNUMBERS);
for(c = 0 ; c < MAXNUMBERS ; c++)
{
scanf("%d", &arr[c]);
fflush(stdin);
n++;
if(arr[c] < 1)
{
break;
}
}
return n;
}
*Problem has been fixed question can be closed or deleted because of unecessary question
I suggest this approach :
int main()
{
int c, array[MAXNUMBERS], maximum, amount_numbers;
clrscr();
getNumbers(array);
location = find_maximum(array, MAXNUMBERS);
if (location == -1 )
printf("No Even integer");
else {
maximum = array[location];
printf("Highest even integer :%d", maximum);
}
getch();
}
int find_maximum(int a[], int n) {
int c, max, index;
max = -10000; // A very low number
index = -1; // shows that no even integer is found yet.
for(c = 1 ; c < n ; c++) {
if(a[c] > max && a[c] %2 == 0) {
index = c;
max = a[c];
}
}
return index;
}
int getNumbers(int arr[])
{
int c;
printf("You may enter a max. %d numbers, enter a number less than 1 to end.\n", MAXNUMBERS);
for(c = 0 ; c < MAXNUMBERS ; c++)
{
scanf("%d", &arr[c]);
fflush(stdin);
if(arr[c] < 1)
{
break;
}
}
}
You should first scan the array from the user which is what getNumbers function does.
Next you need to find the highest even integer which is what find_maximum funciton does.
this function returns index of the highest event integer in your array. the default value is -1 which indicates that no even value is found ! if it's given any other value means that found the highest even integer.
so now that you have the index you check if it's -1(not found) or it's found (returned index).
There is no sense to define an array for a sequence of numbers with undefined size that to determine the maximum value. When a next number is entered you can compare it with the current maximum value provided that the entered number is even.
The program can look the following way
#include <stdio.h>
int main( void )
{
int max = 0;
int value;
printf("Enter a sequence of integer numbers.\n"
"Enter a number less than 1 to end: ");
while (scanf("%d", &value) == 1 && !(value < 1))
{
if (value % 2 == 0 && max < value) max = value;
}
if (max != 0)
{
printf("Highest even integer: %d\n", max);
}
else
{
puts("No even integer");
}
}
As for your program then this loop is wrong.
for (c = 0 ; c < MAXNUMBERS ; c++)
{
location = find_maximum(array, MAXNUMBERS);
maximum = array[location];
}
For starters the number of entered values can be less than MAXNUMBERS. You have to use at least the variable amount_numbers in the condition.
Moreover the loop is not needed Because it does the same that is it calls several times the function find_maximum and nothing is changed with the function result between iterations of the loop. Moreover you have to check whether the variable location gets value 0 and whether the element with this index is less or greater than 1. Otherwise you can show invalid result.
As commented, you are only required to output the answer so there is no need to store the input in an array. This shows how to do it with a simple loop. The program also ends at non-numeric input (effectively a 0 value).
#include <stdio.h>
int main(void) {
int innum = 0;
int maximum = 0;
while(scanf("%d", &innum) == 1 && innum > 0) {
if(innum % 2 == 0 && maximum < innum) {
maximum = innum;
}
}
if(maximum < 2) {
puts("NO EVEN INTEGER");
}
else {
printf("Highest even integer: %d\n", maximum);
}
return 0;
}
Program session:
3 8 1 5 3 4 -5
Highest even integer: 8

How do I make printf from right to left

I've written this code for converting Decimal numbers to binary but it prints the number vice versa how can I make this work?
Can I use getch command to make it happen we are currently learning getch.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for(;n>0;n=n/2){
int d = n%2;
printf("%d", d);
}
return 0;
}
You can get tricky with this by using a recursive function:
#include <stdio.h>
void print_binary(int n)
{
if (n != 0) {
print_binary(n/2);
printf("%d ", n%2);
}
}
int main() {
int n;
scanf("%d", &n);
print_binary(n);
return 0;
}
By printing after the recursive call returns, the digits print in the reverse order.
Each time print_binary is called, it calls itself with an argument of n/2, then prints the least significant bit. However, each recursive call does the same thing.
Here's what the call stack looks like with n equal to 11 (binary 1011):
main
scanf
print_binary(11)
print_binary(5)
print_binary(2)
print_binary(1)
print_binary(0)
printf("%d ", 1);
printf("%d ", 0);
printf("%d ", 1);
printf("%d ", 1);
You can see that this results in the most significant bit being printed first.
Here is another way, working from most significant bit, with "zero supression". No reversal is needed.
#include <stdio.h>
int main(void) {
int n = 0; // the value
int hadone = 0; // 0 suppression control
int bits = 8 * sizeof n; // assume 8 bits for example
unsigned mask = 1u << (bits-1); // set msb of mask
scanf("%d", &n);
while(mask) {
if(n & mask) { // is it a 1 bit?
putchar('1');
hadone = 1; // cancel 0 suppression
}
else if(hadone || mask == 1) { // ensure a lone `0` goes out
putchar('0');
}
mask >>= 1; // next bit
}
putchar('\n');
return 0;
}
Program session:
42
101010
You can store digits into an array , and reverse it , to get the correct number .
Here's a non-recursive solution:
#include <stdio.h>
int main() {
int n;
char buf[100];
char *bp;
printf("Enter number: ");
fflush(stdout);
scanf("%d", &n);
bp = buf;
// store into array instead of printing [chars will be reversed]
// NOTE: we use "bp == buf" to force output if entered number is zero
for (; n>0 || bp == buf; n=n/2){
int d = n%2;
bp += sprintf(bp, "%d", d);
}
// print array in reverse order
for (bp -= 1; bp >= buf; --bp)
fputc(*bp,stdout);
printf("\n");
return 0;
}

C function return error

I'm writing a function that takes a user input up to a 1000 and then adds each number of the input. So if a user inputs 12 the function outputs 3.
When a user inputs 1000 or over the function will print "That number is to high". I can get the function to print the statement, but it also outputs 14...I do not understand why?
I understand there are probably other bugs in my code but right now this is the one that is killing me. Anything that can help would be great.
Here is my code.
#include <stdio.h>
int SummItAll(int value);
int main ()
{
int userNumber=0, result;
printf("Enter a positive number \n ");
scanf("%d", &userNumber);
result = SummItAll(userNumber);
printf("%d\n", result);
return 0;
}
int SummItAll(int value)
{
int a=value, b, c, d, f, g;
if(a < 100)
{
b = a/10;
c = a%10;
return b+c;
}
else if(a >= 100 && a < 1000)
{
b = a/100;
c = a%100;
d = c/10;
f = c%10;
return b+d+f;
}
else
return printf("That number is to high!\n");
}
printf returns the number of characters printed, so it's telling you that your message was 14 characters long.
Rather than returning the result of printf, you should probably return an invalid value (e.g., -1) to indicate an error:
Since the sum of 3 positive digits can never be a negative number, you can check the result of SumItAll, and then take different action in the case of an error:
#include <stdio.h>
int SummItAll(int value);
int main ()
{
int userNumber=0, result;
printf("Enter a positive number \n ");
scanf("%d", &userNumber);
result = SummItAll(userNumber);
if (result == -1)
{
printf("Please enter a POSITIVE number!\n");
}
else if (result == -2)
{
printf("That number is to high!\n");
}
else
{
printf("%d\n", result);
}
return 0;
}
int SummItAll(int value)
{
int a=value, b, c, d, f, g;
if (a < 0)
{
return -1; // too low!
}
else if(a < 100)
{
b = a/10;
c = a%10;
return b+c;
}
else if(a >= 100 && a < 1000)
{
b = a/100;
c = a%100;
d = c/10;
f = c%10;
return b+d+f;
}
else
{
return -2; // too high!
}
}
Note that -1 and -2 would be considered "magic numbers" in the code above, since they have a special meaning that isn't immediately obvious. It would probably be better to define some symbols to use in the code in place of the integer literals -1 and -2 in order to make the meaning more clear. For example:
#define ERR_NUM_IS_NEGATIVE -1
#define ERR_NUM_IS_TOO_LARGE -2
And then you can use those symbolic names in the code instead of the literals, which should make it more clear.
For your use case, it is better that SummItAll accepts a pointer parameter where both the input and output are passed and return a boolean value to indicate the returned result is valid or not.
bool SummItAll(int *value)
{
if(...) {
*value = ...
return true;
} else if(...) {
..
} else {
return false;
}
}
The printf() function returns an integer which indicates how many characters it has written out.

Resources