I'm trying to create a recursive function to reverse digits of a number in C. This is what I've written. It works fine when used one time but when used multiple times it keeps piling the numbers together. I think the problem can be sorted if the sum is initialized to zero each time the function is called but I'm unable to do it. I've tried declaring sum=0 as a global variable but the result was the same.
Input-
12
23
34
45
Output
21
2132
213243
21324354
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int digit_reverse(int N)
{
int rem;
static int sum=0;
if(N>0)
{
rem=N%10;
sum=sum*10+rem;
digit_reverse(N/10);
}
else
return 0;
return sum;
}
int main()
{
int a[25],i;
for(i=0;i<4;i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for(i=0;i<4;i++)
{
printf("%d\n",digit_reverse(a[i]));
}
}
Maybe you can write your function without using static variables:
void _digit_reverse(int N, int *sum)
{
int rem;
if (N > 0)
{
rem = N % 10;
*sum = *sum * 10 + rem;
_digit_reverse(N / 10, sum);
}
}
int digit_reverse(int N)
{
int sum = 0;
_digit_reverse(N, &sum);
return sum;
}
Or take the sum outside:
int sum = 0;
int digit_reverse(int N)
{
int rem;
if (N > 0)
{
rem = N % 10;
sum = sum * 10 + rem;
digit_reverse(N / 10);
}
else
return 0;
return sum;
}
int main()
{
int a[25], i;
for (i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for (i = 0; i < 4; i++)
{
sum = 0;
printf("%d\n", digit_reverse(a[i]));
}
}
I believe that the static variable gets initialized only once. This is the problem with your approach.
dude everything looks fine to me if the code do not needs to be reusable I can think of several solutions but keep in mind static and or global variables are not best practices unless necessarily required to.
secondly change your
// from static int sum = 0;
// to
static long sum = 0;
// or
static long long sum = 0;
the reason for this error is value overflow
an integer cannot have more than 4 bytes of data in this specific case you definitly needs more.
Related
I am new to programing.
I'm doing an exercise witch the user inserts numbers in an array and the program prints the average of those numbers.
But part of the exercise is making the numbers that the user inserts using a function, and thats where i'm struggling.
my code:
#include <stdio.h>
main() {
int n = 10, i, array1[10];
float sum = 0.0, average;
printf("insert 10 numbers\n");
for (i = 0; i < n; ++i) {
printf("insert digit no%d: ", i + 1);
scanf("%d", &array1[i]);
sum += array1[i];
}
average = sum / n;
printf("average = %.2f", average);
return 0;
}
all the help is much apreciated :)
Here's a small program to show you how functions work:
#include "stdio.h"
void foo(int array[], int size)
{
for (int i = 0; i < size; i++)
scanf("%d", &array[i]);
}
size_t bar(int array[], int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
sum += array[i];
return (sum);
}
int main(void)
{
int array[3] = {0};
int sum;
foo(array, 3);
sum = bar(array, 3);
printf("array sum = %d\n", sum);
return (0);
}
foo and bar are two functions, they both have a return type on the left side, a name (foo/bar), some parameters in the parentheses, and their body declaration between braces.
When you call a function from your main, you'll have to call it with its required parameters. In my exemple, both functions need an integer array, and an integer value as parameters. That's why we called it this way from the main: foo(array, 3); and bar(array, 3).
When we call a function, the given parameters are copied into memory so you can work with those params into the function body as if they were variables.
Some functions have a return type different than void. Those functions are able to (and must) return a value of the return type with the return statement. Those values can be used, assigned etc, as you can see with the instruction sum = bar(array, 3);
Even the main is a function !
If you want to move user input and average calculation into separate methods. It should be done something like this.
#include <stdio.h>
/*
* Takes an array and get input for N items specified
*/
void getUserInputForArray(int array[], int N) {
printf("insert %d numbers\n", N);
for (int i = 0; i < N; ++i) {
printf("insert digit no %d: ", i + 1);
scanf("%d", &array[i]);
}
}
/*
* Calculate average for a given array of size N
*/
float getAverage(int array[], int N) {
// Initialize sum to 0
float sum = 0.0f;
// Iterate through array adding values to sum
for (int i = 0; i < N; i++)
sum += array[i];
// Calculate average
return sum / N;
}
int main() {
int n = 10, array1[10];
// Pass array to method, since arrays in C are passed by pointers.
// So Even if you modify it in method it would get reflected in
// main's array1 too
getUserInputForArray(array1, n);
// Calculate Average by delegating average calculation to getAverage(...) method
float average = getAverage(array1, n);
printf("average = %.2f", average);
return 0;
}
I wanted to write a simple program to calculate the factorial of a given number using C. Yet my code seems to have some logical error that I can't detect. Would be glad for help.
int fact(int n);
int main(void)
{
int num = get_int("Type number: ");
printf("%i\n", fact(num));
}
//define function
int fact(int n)
{
for (int i = 1; i < n; i++)
{
n *= i;
}
return n;
}
You can't use n to calculate.
You have to save total with another variable
int fact(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product = product * i;
}
return product;
}
In mathematics, the factorial of a positive integer N, denoted by N!, is the product of all positive integers less than or equal to N:
N!=N*(N-1)*(N-2)*(N-3)*.......*1
+-------------------------+
notice that this is: (N-1)! <==> So, N! = N*(N-1)!
we can use these mathematical facts to implement the factorial function in 2 different forms, recursive and iterative approaches:
recursive approach
size_t rec_factorial(size_t n)
{
/*Base case or stopping condition*/
if(n==0)
{
/* 0! = 1 */
return 1;
}
/*n! = n * (n-1)!*/
return n * rec_factorial(n-1);
}
iterative approach
size_t factorial(size_t n)
{
size_t j = 1;
size_t result = 1;
while(j <= n){
result *= j; /* n!=n*(n-1)*(n-2)*(n-3)*....1 */
++j;
}
return result;
}
I am new to functions and right now I am trying to understand them so please go easy on me if you see some "noob" mistakes.I would really appreciate some help with this program:
#include <stdio.h>
#include <stdlib.h>
int check(int a[],int n,int i )
{
int j;
for (j=0; j<n ; j++)
{
if(a[i]==j*j)
return 1;
else
return 0;
}
}
int main()
{
int n,a[100],i;
printf("\nThe size:\n");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("\na[%d]=",i);
scanf("%d",&a[i]);
if(check(a,n,i)==1)
printf("%d is a perfect square\n",a[i]);
else
printf("%d is not a perfect square\n",a[i]);
}
return 0;
}
I succeeded in making it run but something isn't right no matter the input (1,4,5,9...) it will always print:" is not a perfect square "
What you need is to pass only a number to the function instead. To do that, you can simply do:
int check(int value, int n)
{
for (int j=0; j<n ; j++)
if(value==j*j)
return 1;
return 0;
}
and call the function like this:
check(a[i], n)
Now, you are not passing the whole array, but only a number, i.e. the i-th number of it.
At this point, you have a function to check one number. Think what you need to do, to check a collection of numbers. How would you apply that check() to every number of your vector?
PS: An important and fundamental note is that you should indent your code, since it makes everything much more readable (for example, curly brackets get aligned).
Appendix:
You could make your initial function work like this:
int check(int a[],int n,int i )
{
int j;
for (j=0; j<n ; j++)
{
if(a[i]==j*j)
return 1;
}
return 0;
}
so that you don't stop looping over when the condition is not mean, but will continue checking the other entries as well.
However, I strongly recommend using my suggestion above.
Write a function to check if its parameter (positive integer) is a perfect square
What is needed is:
bool check_if_perfect_square(unsigned n);
Simple find the integer square root. Integer square root routines are not too hard to code. Maybe:
#include <stdbool.h>
// Square root of t round toward 0
unsigned uisqrt(unsigned t) {
unsigned s, b;
for (b = 0, s = t; b++, s >>= 1) {
;
}
s = 1u << (b >> 1);
if (b & 1) {
s += s >> 1;
}
do {
b = t / s;
s = (s + b) >> 1;
} while (b < s);
return s;
}
If you do not like that advanced approach, code could slowly iterate. No need to iterate to i<n, but to i <= n/i.
unsigned uisqrt(unsigned n) {
unsigned i = 0;
if (n > 0) {
for (i = 1; i <= n/i; i++) {
;
}
i--;
}
return i;
}
Then the check is easily
#include <stdbool.h>
bool check_if_perfect_square(unsigned n) {
unsigned sr = uisqrt(n);
return sr*sr == n);
}
Then apply this function to a vector of positive integers
Armed with a check_if_perfect_square(), simply iterate over the array.
#include <stddef.h>
#include <stdio.h>
void square_root_test_array(unsigned *a, size_t array_length) {
for (size_t i = 0; i<array_length; i++) {
if (check_if_perfect_square(a[i])) {
printf("%u is a perfect square\n",a[i]);
} else {
printf("%d is not a perfect square\n",a[i]);
}
}
}
Sample use
int main() {
printf("\nThe size:\n");
unsigned n = 0;
scanf("%u",&n);
unsigned a[n];
for(unsigned i=0; i<n; i++) {
printf("a[%u] = ",i);
scanf("%d",&a[i]);
}
// Now test array
square_root_test_array(a, n);
return 0;
}
This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.
Earlier I posted a question about the coin vending machine problem (the minimum number of coins required). Turns out the issue was a typo in a for loop, so now the program works. The original question was this:
As the programmer of a vending machine controller your are required to compute the minimum number of coins that make up the required change to give back to customers. An efficient solution to this problem takes a dynamic programming approach, starting off computing the number of coins required for a 1 cent change, then for 2 cents, then for 3 cents, until reaching the required change and each time making use of the prior computed number of coins. Write a program containing the function ComputeChange(), that takes a list of valid coins and the required change. This program should repeatedly ask for the required change from the console and call ComputeChange() accordingly. It should also make use of “caching”, where any previously computed intermediate values are retained for subsequent look-up.
The issue is that the code makes use of recursion, so it takes quite a long time to evaluate large values. Making use of caching should improve the issue, but I have no idea how to go about it. The code can be found below.
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
return 1+min(possible_mins, n);
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
With your existing code:
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
void initChange ();
int change [MAX]; //used for memoization
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
initChange ();
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
void initChange () {
int i =0;
for (i = 0; i < MAX; i++) {
change[i] = INT_MAX;
}
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
if (change[v] == INT_MAX) {
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
change[v] = 1 + min(possible_mins, n); // memoization
}
return change[v];//you return the memoized value
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
I already posted a solution using loops in your previous question. I will post it again here:
So the below is the code snippet for your problem using memoization and dynamic programming. The complexity is O(Val*numTypesofCoins).
In the end, change[val] will give you the min number of coins for val.
int main (void) {
int change [MAX];
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(a)/sizeof(int);
int val; //whatever user enters to get the num of coins required.
printf("Enter a value in euro cents: ");
scanf("%d", &val);
for (i=0; i <= val; i++) {
change[i] = INT_MAX;
}
for (i=0; i < n; i++) { // change for the currency coins should be 1.
change[cur[i]] = 1;
}
for (i=1; i <= val; i++) {
int min = INT_MAX;
int coins = 0;
if (change[i] != INT_MAX) { // Already got in 2nd loop
continue;
}
for (j=0; j < n; j++) {
if (cur[j] > i) { // coin value greater than i, so break.
break;
}
coins = 1 + change[i - cur[j]];
if (coins < min) {
min = coins;
}
}
change[i] = min;
}
}