Attempting to print in C when creating functions - c

I am running this code, and the print commands are not actually resulting in any printing. Can anyone please advise? I do have a couple of comments at the end that will preface my two other functions, but for now, I am just interested in knowing why the prints aren't appearing even though my code doesn't show any errors.
Thanks!
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
return len;
printf("Length: %d", len);
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
return charsnum;
printf("First 2 digits: %ld", charsnum);
}
//Length & character count congruity
//Checksum

A function is terminated immediately after the return statement.
Your printing statement is after the return statement in those functions. That is why, they don't appear when you run the code.
So, put them before the return statement and you should be able to see them in the output. Moreover, for some clean output, do use \n inside those printf.
Then, inside your main function, look at these statements:
int length(long number);
int start_chars(long number);
Those are function declarations and not how functions are called in C. Store the return value in a variable. Since you just want to see those printf statements get executed, change that to:
length(number);
start_chars(number);

when you use return in your functions they will end immediately.
and so your printf line won't be executed.
printf should be before return.

Like the answers above, you made an error in your code where you are printing after the return statement.
Here is the correct code :
# include <cs50.h>
# include <stdio.h>
int length(long number);
int start_chars(long number);
//Main
int main (void)
{
long number = get_long("Number: ");
int length(long number);
int start_chars(long number);
}
//Number length count
int length(long number)
{
int len = 0;
do
{
len ++;
number /= 10;
}
while (number > 0);
printf("Length: %d", len);
return len;
}
//Number first characters
int start_chars(long number)
{
long charsnum = number;
while (charsnum >= 100)
{
charsnum /= 10;
}
printf("First 2 digits: %ld", charsnum);
return charsnum;
}
//Length & character count congruity
//Checksum

Related

Reverse of a number using recursion

The reverse of the number is getting printed many times. How do I print it just once?
For example, if I give input as 1234 then the output is coming out as 4321 4321 4321 4321.
#include <stdio.h>
#include <stdlib.h>
//function declaration
void printReverse(int);
int main()
{
int n;
printf("\n\t\t\t\t\t\tThis program prints reverse of a given number");
printf("\nEnter a number: ");
scanf("%d",&n);
//if someone enters 0
if(n==0)
{
printf("%d",n);
exit(0);
}
//function call
printReverse(n);
return 0;
}
void printReverse(int n)
{
static int rev=0;
//base case
if(n)
{
int rem = n % 10;
rev = rev*10 + rem;
printReverse(n/10);
}
printf("%d ",rev);
}
The way your printReverse function is currently written, the last line (printf("%d ",rev);) will always be executed whenever the function is called, because there is no code path through the function that skips that line. So, when the recursion has reached the point where the given argument is zero, you will get that line being called each time on the 'rewind' of the stacked, recursive calls (once for each digit in the initial n).
To fix this, you can either enclose that printf line in an else block:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
}
else { // Only print the result when we're finished (n = 0):
printf("%d\n", rev);
}
}
Or, accomplishing much the same thing, add a return statement after you make the recursive call:
void printReverse(int n)
{
static int rev = 0;
if (n) {
int rem = n % 10;
rev = rev * 10 + rem;
printReverse(n / 10);
return; // Don't print on the rewind from recursion
}
printf("%d\n", rev);
}
C Program to reverse a given number using Recursive function
based on https://beginnersbook.com/2014/06/c-program-to-reverse-a-given-number-using-recursive-function/
#include <stdio.h>
int sum=0, rem;
int reverse_function(int num) {
if(num) {
rem=num%10;
sum=sum*10+rem;
reverse_function(num/10);
}
else
return sum;
return sum;
}
int main() {
int num,reverse_number;
//Take the number as an input from user
printf("Enter any number:");
scanf("%d",&num);
//Calling user defined function to perform reverse
reverse_number=reverse_function(num);
printf("The reverse of entered number is :%d",reverse_number);
return 0;
}
Output:

Create function to find the maximum digit in integer X

I'm a student, and my task is "An integer X is given, find the maximum of the numbers included in its composition." For example X is 786534, so maximum number is "8". The task have to be done with function on c. I make some notes but it doesn't work correctly. There are two functions.
First function is for input number a check it for right size.
The second is for the calculating the max digit.
I have a problem with calling the function.
What is my mistake?
#include <conio.h>
#include <stdio.h>
#define MAX_N 999999999999
int inputNumber()
{
int number;
printf("Input number:\n");
scanf_s("%d", &number);
while (number = 0 && number > MAX_N)
{
// Number is not equal 0
printf("Repeat input:\n");
scanf_s("%d", &number);
}
return number;
}
int findMax(int number)
{
int max_number; //intermediate variable
int a = number;
max_number = a % 10;
a = a / 10;
while (a > 0)
{
if (a % 10 > max_number)
max_number = a % 10;
a = a / 10;
}
return max_number;
}
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
Okay, let's look at this:
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
inputNumber returns an int, but you don't store it somewhere. So this might work better for you:
int number = inputNumber();
findMax expects an argument, so this might work better:
int max_number = findMax(number);
That should get you further.
You need to save the return value of inputNumber() to a variable and pass that as the parameter to findMax(); variables such as "max_number" are limited by function scope.
I hope this helps!

Why does my FirstFactorial program keep looping back to while condition even after the condition is not met

Here's the code snippet, this when run with number 4 outputs 2424242448484848288288288288576576576576. Not sure as to why would the execution would jump back to while loop after exiting the function code. Any help will be appreciated. Thank you in advance.
#include <stdio.h>
#include <string.h>
int result = 1;
void FirstFactorial(int);
void FirstFactorial(int num) {
// code goes here
while (num > 0) {
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
int main(void) {
int var;
// keep this function call here
printf ("Enter your no.\n");
scanf("%d", &var);
FirstFactorial(var);
return 0;
}
Within the function
void
FirstFactorial(int num)
{
// code goes here
while(num > 0)
{
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
each its iteration calls itself num times and all iterations together output the global variable result.
So for example in the first call of the function the function calls itself in the while loop for the range of values [num, 1].
Remove the while loop and do not use the global variable.
Here is a demonstrative program.
#include <stdio.h>
unsigned long long int factorial( unsigned long long int n )
{
return n < 2 ? 1 : n * factorial( n - 1 );
}
int main(void)
{
printf( "%llu! = %llu\n", 4llu, factorial( 4 ) );
printf( "%llu! = %llu\n", 20llu, factorial( 20 ) );
return 0;
}
The program output is
4! = 24
20! = 2432902008176640000
Pay attention that the maximum value you may specify is 20.
Either you implement the factorial with a loop or you do it recursively.
Both ways are feasible but your code mixes it up.
Your function mixes iterative and recursive approaches. You can correct it by removing the useless recursion which causes multiple intermediary results to be computed and printed. Defining result as a global variable is also a mistake, especially since you do not reinitialize it before the loop. Using type long long will allow for larger factorials to be computed. Adding a trailing \n after the printf conversion specifier is advisable too.
Here is a corrected version:
#include <stdio.h>
void FirstFactorial(int num) {
long long result = 1;
while (num > 1) {
result = result * num;
num--;
}
printf("%lld\n", result);
}
int main(void) {
int var;
// keep this function call here
printf("Enter your number\n");
if (scanf("%d", &var) == 1)
FirstFactorial(var);
return 0;
}

C program on part of algorithm which focus on finding Armstrong-like number

I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is code, a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

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;
}

Resources