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.
Related
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.
I wrote the following code to solve the readability lab.
It is compiling well with no problem.
The problem is in the results, as for an unknown reason it always calculates s_avg as zero.
s_avg is the average number of sentences in 100 words.
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
//prototypes
int count_letters (string text);
int count_words(string text);
int count_sent(string text);
int main(void)
{
// get the user to prompt part of the story
string story = get_string("Text: \n");
//variables
int letters = count_letters(story);
int words = count_words(story);
int sentences = count_sent(story);
//show results
printf("%i letter(s)\n",letters);
printf("%i word(s)\n",words);
printf("%i sentence(s)\n",sentences);
// Calculate average number of letters & sentences per 100 words
int l_avg = (letters/words)*100;
int s_avg = (sentences/words)*100;
// Calculate Coleman-Liau index
int index = round(0.0588 * l_avg - 0.296 * s_avg - 15.8);
// check grade level
if(index<1)
{
printf("Before Grade 1\n");
}
else if(index>16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n",index);
}
}
//count the number of letters
int count_letters (string text)
{
int l = 0;
for(int i=0,n=strlen(text); i<n; i++)
{
if((text[i]>=97 && text[i]<=122)||(text[i]>=65 && text[i]<=90))
{
l++ ;
}
}
return l;
}
//count the number of words
int count_words(string text)
{
int w = 1;
for(int i=0,n=strlen(text); i<n; i++)
{
if (text[i]==32)
{
w++ ;
}
}
return w ;
}
//count the number of sentences
int count_sent(string text)
{
int s=0;
for(int i=0,n=strlen(text); i<n; i++)
{
if ((text[i]==46) || (text[i]==33) || (text[i]==63))
{
s++ ;
}
}
return s;
}
I don't know why it keeps calculating int s_avg = (sentences/words)*100; as zero.
I realized that using the debug50 tool.
For calculating average number of letters & sentences, use double type variables instead.
double l_avg = ((double)letters / (double)words)*100;
double s_avg = ((double)sentences / (double)words)*100;
Integer division in C results in an integer, not a float. You have to explicitly cast the dividend and the divisor to float:
int i = 5 / 4;
printf("%d", i); // prints 1
float f = (float)5 / (float)4;
printf("%f", f); // prints 1.250000
So, int s_avg = (sentences/words)*100 should be:
float s_avg = (float)sentences / (float)words * 100;
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;
}
}
*EDITED*
I fixed some issues but i'm still calling it wrong. Somehow when i don't declare with int the GetRand function more than once i get more error messages.
What i want as a final result is to print the array i created and also print the maximum and average of the values of it (only counting every number > -1).
I'm calling the maxavg() function wrong and i'm getting an error message "Error] expected identifier or '(' before '{' token" at the beginning of maxavg which i haven't been able to fix.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int GetRand(int min, int max);
int maxavg();
int main ()
{
int a[21][21], i , j, average, maximum;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
printf("%3d" , a[i][j]);
}
a[2][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("\n");
}
average = maxavg();
maximum = maxavg();
printf("average = %d \n maximum = %d", average, maximum);
return 0;
}
// random seed
int GetRand(int min, int max);
int get ()
{
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
// max and average
int maxavg();
{
int max=INT_MIN, sum=0, count=0, avg, n, m, current;
current = a[i][j];
avg = sum/count;
for(n = 0; n < 21; n++){
for(m =0; m < 21; m++){
if(current > -1){
sum = sum + current;
count = count + 1;
if(current > max){
max = current;
}
}
}
}
return(0);
}
This program will only print the elements of the array a in the for-loop in main. Apart from GetRand, no other function is called, so get and maxavg are never executed, despite being defined. So yes, you should first of all call it from main if you want to see what it does.
There is also a big problem with the logic of your maxavg function though.
Where is the array you're presuming to iterate over? You haven't passed any parameter to maxavg (nor declared and set a local variable). It looks like you're expecting current to contain these array element values, but the reality is you've never set the value of this variable to anything. You should be using the i and j variables as indexes into the array you should add, as in arr[i][j].
A few other notes:
You really should be setting a[2][15], a[10][6] and so on after the loop has finished, not in every single iteration.
You've declared GetRand twice.
maxavg returns an int, yet there is no return statement in your function ("control reaches end of non-void function").
I'm stuck on Euler#4 which is to calculate the highest palindrome number by product of two 3-digit numbers. The answer I'm getting is always 0. Evidently help is required.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j,h=0,m=0,p=0;
clrscr();
for(i=100;i<1000;i++)
{
for(j=100;j<1000;j++)
{
p=i*j;
h=p/100000;
m=p%10;
if(h==m)
{
h=(p/10000)%10;
m=(p/10)%10;
if(h==m)
{
h=(p/1000)%10;
m=(p%1000)/100;
if(h==p)
{
printf("%d\n",p);
}
}
}
}
}
return 0;
}
Its wrong to do this, but still dont make it a habit. I think one can solve first 50 question with ease.
#include <stdio.h>
static int is_palindromic(unsigned int n);
int main(void)
{
unsigned int i, j, max = 0;
for (i = 100; i <= 999; i++) {
for (j = 100; j <= 999; j++) {
unsigned int p = i*j;
if (is_palindromic(p) && p > max) {
max = p;
}
}
}
printf("%u\n", max);
return 0;
}
int is_palindromic(unsigned int n)
{
unsigned int reversed = 0, t = n;
while (t) {
reversed = 10*reversed + (t % 10);
t /= 10;
}
return reversed == n;
}