This my first post on here. I'd like to ask about a problem that I am trying to do for homework.
I'm supposed to be constructing a for loop for the "first 5 factorials" and display results as a table. I followed an example in the book, and I have my for loop and my operations set up, but I don't know what to do to produce the loop in the table. Here is my program:
#include <stdio.h>
int main(void) {
//Problem: Display a range for a table from n and n^2, for integers ranging from 1-10.
int n, factorialnumber, i;
printf("TABLE OF FACTORIALS\n");
printf("n n!\n");
printf("--- -----\n");
for (n = 1; n <= 10; n++) {
factorialnumber = factorialnumber * n;
printf("\n %i = %i", factorialnumber, n);
}
return 0;
}
I know the printf here is wrong. What would I type?
BTW, I'm using codeblocks.
The problem is that you didn't initialize the variables (e.g. factorialnumber). If it has an initial value of 6984857 let's say, the whole algorithm would be messed up.
Try this :
#include <stdio.h>
int main(void) {
//Problem: Display a range for a table from n and n^2, for integers ranging from 1-10.
int i, factorialnumber = 1;
int n = 10; // Max number to go through
printf("TABLE OF FACTORIALS\n");
printf("i i!\n");
printf("--- -----\n");
for (i = 1; i <= n; i++) {
factorialnumber *= i;
printf("%d! = %d\n", i, factorialnumber);
}
return 0;
}
Related
I am writing a program that will take any number of integers. The program will end when the terminal 0 has been entered. It will then output the number closest to 10 (except for the terminal character). If there are several numbers closest to 10 then it should output the last number entered.
My current code does read the numbers from the input stream, but I don't know how to implement the logic so that the program will give me the number that is closest to 10.
I know, that I need to keep track of the minimum somehow in order to update the final result.
#include <stdio.h>
int main() {
int n = 1;
int number = 1;
int numberArray[n];
int resultArray[n];
int min;
int absMin;
int result;
int finalResult;
while (number != 0) {
scanf("%d", &number);
numberArray[n] = number;
n++;
}
for (int i = 0; i < n; i++) {
min = 10 - numberArray[i];
if (min < 0) {
absMin = -min;
}
else {
absMin = min;
}
resultArray[i] = absMin;
result = resultArray[0];
if (resultArray[i] < result) {
finalResult = resultArray[i];
}
}
printf("%d\n", finalResult);
return 0;
}
here's a simple code I wrote
One thing I must say is you can't simply declare an array with unknown size and that's what you have done. Even if the no. of elements can vary, you either take input the number of elements from the user OR (like below) create an array of 100 elements or something else according to your need.
#include <stdio.h>
#define _CRT_NO_WARNINGS
int main() {
int n = 0;
int number = 1;
int numberArray[100];
int resultArray[100];
int minNumber;
int *min;
do {
scanf("%d", &number);
numberArray[n] = number;
n++;
}
while (number != 0);
resultArray[0] = 0;
min = &resultArray[0];
minNumber = numberArray[0];
for (int i = 0; i < n-1; i++) {
if(numberArray[i]>=10){
resultArray[i] = numberArray[i] - 10;
}
if(numberArray[i]<10){
resultArray[i] = 10 - numberArray[i];
}
if(resultArray[i] <= *min){
min = &resultArray[i];
minNumber = numberArray[i];
}
}
printf("\n%d",minNumber);
return 0;
}
I have improved your script and fixed a few issues:
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main()
{
int n;
int number;
int numberArray[n];
while (scanf("%d", &number) && number != 0) {
numberArray[n++] = number;
}
int currentNumber;
int distance;
int result;
int resultIndex;
int min = INT_MAX; // +2147483647
for (int i = 0; i < n; i++) {
currentNumber = numberArray[i];
distance = fabs(10 - currentNumber);
printf("i: %d, number: %d, distance: %d\n", i, currentNumber, distance);
// the operator: '<=' will make sure that it will update even if we already have 10 as result
if (distance <= min) {
min = distance;
result = currentNumber;
resultIndex = i;
}
}
printf("The number that is closest to 10 is: %d. It is the digit nr: %d digit read from the input stream.\n", result, resultIndex + 1);
return 0;
}
Reading from the input stream:
We can use scanf inside the while loop to make it more compact. Also, it will loop one time fewer because we don't start with number = 1 which is just a placeholder - this is not the input - we don't want to loop over that step.
I used the shorthand notation n++ it is the post-increment-operator. The operator will increase the variable by one, once the statement is executed (numberArray entry will be set to number, n will be increased afterwards). It does the same, in this context, as writing n++ on a new line.
Variables:
We don't need that many. The interesting numbers are the result and the current minimum. Of course, we need an array with the inputs as well. That is pretty much all we need - the rest are just helper variables.
Iteration over the input stream:
To get the result, we can calculate the absolute distance from 10 for each entry. We then check if the distance is less than the current minimum. If it is smaller (closer to 10), then we will update the minimum, the distance will be the new minimum and I have added the resultIndex as well (to see which input is the best). The operator <= will make sure to pick the latter one if we have more than one number that has the same distance.
I have started with the minimum at the upper bound of the integer range. So this is the furthest the number can be away from the result (we only look at the absolute number value anyway so signed number don't matter).
That's pretty much it.
I'm trying to create a hash table. Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define N 19
#define c1 3
#define c2 5
#define m 3000
int efort;
int h_table[N];
int h(int k, int i)
{
return (k + i*c1 + i*i*c2) % N;
}
void init()
{
for (int i = 0; i < N; i++)
h_table[i] = -1;
}
void insert(int k)
{
int position, i;
i = 0;
do
{
position = h(k, i);
printf("\n Position %d \n", position);
if (h_table[position] == -1)
{
h_table[position] = k;
printf("Inserted :elem %d at %d \n", h_table[position], position);
break;
}
else
{
i += 1;
}
} while (i != N);
}
void print(int n)
{
printf("\nTable content: \n");
for (int i = 0; i < n; i++)
{
printf("%d ", h_table[i]);
}
}
void test()
{
int a[100];
int b[100];
init();
memset(b, -1, 100);
srand(time(NULL));
for (int i = 0; i < N; i++)
{
a[i] = rand() % (3000 + 1 - 2000) + 2000;
}
for (int i = 0; i < N ; i++)
{
insert(a[i]);
}
print(N);
}
int main()
{
test();
return 0;
}
Hash ("h") function and "insert" function are took from "Introduction to algorithms" book (Cormen).I don't know what is happening with the h function or insert function. Sometimes it fills completely my array, but sometimes it doesn't. That means it doesn't work good. What am I doing wrong?
In short, you are producing repeating values for position often enough to prevent h_table[] from being populated after only N attempts...
The pseudo-random number generator is not guaranteed to produce a set of unique numbers, nor is your h(...) function guaranteed to produce a mutually exclusive set of position values. It is likely that you are generating the same position enough times that you run out of loops before all 19 positions have been generated. The question how many times must h(...) be called on average before you are likely to get the value of an unused position? should be answered. This may help to direct you to the problem.
As an experiment, I increased the looping indexes from N to 100 in all but the h(...) function (so as not to overrun h_table[] ). And as expected the first 5 positions filled immediately. The next one filled after 3 more tries. The next one 10 tries later, and so on, until by the end of 100 tries, there were still some unwritten positions.
On the next run, all table positions were filled.
2 possible solutions:
1) Modify hash to improve probability of unique values.
2) Increase iterations to populate h_table
A good_hash_function() % N may repeat itself in N re-hashes. A good hash looks nearly random in its output even though it is deterministic. So in N tries it might not loop through all the array elements.
After failing to find a free array element after a number of tries, say N/3 tries, recommend a different approach. Just look for the next free element.
I need to generate a modified Fibonacci series and it must be completely dynamic. Here f0 and f1 will be given, i.e f0=1 and f1=3 after generating the series. I should print the resulting value at a particular index.
Ex: f0 = 1, f1 = 3, testcase(n) = 3 (This can change not a particular value)
t1 = 4 t2 = 8 t3 = 11 and so on. Series should be generated for 11 elements by adding current element and previous element using: f[i] = f[i-1] + f[i-2]
It can be represented as:
0=>1
1=>3
2=>4
3=>7
4=>11
5=>18
6=>29
7=>47
8=>76
9=>123
10=>199
11=>322
I should print the values at indices 4,8 and 11 (which must be the output of my program), i.e. 11 76 322.
Input Format:
f0,f1 and n (where n is the no of indices)
where ti=[t1,t2,....tn-1] (which specifies the index for R-Fibonacci series).
Output Format:
Print the values from the R-fibonacci series based on the given indices.
Sample Input:
1 3 3 4 8 11
Sample Output:
11 76 322
I have the code that generates the Fibonacci series for the above program but I want to display the value at 4,8,11 indices. Here is the code:
int fib(int n)
{
int f[n+1];
int i;
f[0]=1;
f[1]=3;
for(i=2;i<=n;i++)
{
f[i]=f[i-1]+f[i-2];
}
return f[n];
}
int main()
{
int n=11
printf("%d ",fib(n));
getchar();
return 0;
}
Like this? The array is defined in main and passed to the function as an argument. The function fills in the array, returns nothing, and then in main you can print the elements you want.
You will need a loop to do that, with another dynamic array holding the indices you are asked to print.
#include <stdio.h>
void fib(int n, int *f)
{
int i;
f[0] = 1;
f[1] = 3;
for(i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}
}
int main()
{
int n = 11;
int f[n+1];
fib(n, f);
printf("%d ", f[8]);
printf("%d ", f[11]);
printf("\n");
getchar();
return 0;
}
Program output:
76 322
I will leave you some code to write, but suppose you make a dynamic array of the index values required, such as
int index[m];
index[0] = 4;
index[1] = 8;
index[2] = 11;
you can print the series term with such as
printf("%d ", f[ index[i] ]);
If I understand correctly, this question really has little to do with fibonacci and is about scope in C. You are declaring and defining an array in a function, fib, and filling it within that function (and returning a single element value). What you want is to have access to the entire array from the caller.
A straightforward way of doing this is to declare the array in the calling method, and pass a pointer to it to the fib function:
#include <stdio.h>
int fib(int f[], int n)
{
int i;
f[0]=1;
f[1]=3;
for(i=2;i<=n;i++)
{
f[i]=f[i-1]+f[i-2];
}
return f[n];
}
int main()
{
int n=11;
int f[12];
fib(f, n);
printf("%d ", f[4]);
printf("%d ", f[8]);
printf("%d ", f[11]);
getchar();
return 0;
}
Here is a code to generate a set of fibonacci numbers less than a given number N using recursive algorithm :
#include<stdio.h>
int fibo(int n)
{
if(n<2)
return n;
else
return (fibo(n-1)+fibo(n-2));
}
void main()
{
int n,i;
printf("\n Enter number : ");
scanf("%d",&n);
printf("\n Fibonacci series is : ");
for(i=0;i<n;i++)
printf("\n %d",fibo(i));
}
I'm trying to write a program that will print the factorial of a given number in the form:
10!=2^8 * 3^4 * 5^2 * 7
To make it quick lets say the given number is 10 and we have the prime numbers beforehand. I don't want to calculate the factorial first. Because if the given number is larger, it will eventually go beyond the the range for int type. So the algorithm i follow is:
First compute two’s power. There are five numbers between one and ten that two divides into. These numbers are given 2*1, 2*2, …, 2*5. Further, two also divides two numbers in the set {1,2,3,4,5}. These numbers are 2*1 and 2*2. Continuing in this pattern, there is one number between one and two that two divides into. Then a=5+2+1=8.
Now look at finding three’s power. There are three numbers from one to ten that three divides into, and then one number between one and three that three divides into. Thus b=3+1=4. In a similar fashion c=2. Then the set R={8,4,2,1}. The final answer is:
10!=2^8*3^4*5^2*7
So what i wrote is:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
while(n%ara[i]==0)
{
count++;
n=n/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
and the output is (2^3) (3^2) (5^1) (7^1).
I can't understand what's wrong with my code. Can anyone help me, please?
Much simpler approach:
#include <stdio.h>
int main(int argc, char const *argv[])
{
const int n = 10;
const int primes[] = {2,3,5,7};
for(int i = 0; i < 4; i++){
int cur = primes[i];
int total = 0;
while(cur <= n){
total += (n/cur);
cur = cur*primes[i];
}
printf("(%d^%d)\n", primes[i], total);
}
return 0;
}
Your code divides n when it is divisible for some prime number, making the n jumps.
e.g. when n = 10 and i = 0, you get into while loop, n is divisible by 2 (arr[0]), resulting in n = 5. So you skipped n = [9..5)
What you should do is you should use temp when dividing, as follows:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
int temp = n;
while(temp%ara[i]==0)
{
count++;
temp=temp/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
For finding factorial of a no pl. try this code:
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
I have looked through various questions on the site and I haven't managed to find anything which implements this by the following reasoning (so I hope this isn't a duplicate).
The problem I'm trying to solve via a C program is the following:
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.
After looking around online to find how others have solved it, I found the following example applied with pennies, nickels and dimes:
Which I tried to base my code upon. But first of all, my code isn't halting, and secondly, I'm not sure if I'm incorporating the caching element mentioned in the rubric above. (I'm not really sure how I need to go about that part).
Can anyone help find the flaws in my code?
#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 -1;
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((i>=0) && (a[i]< min))
min = a[i];
}
return min;
}
Any assistance will be greatly appreciated.
OP's supplied Change() algorithm incurs lots of recursion, even with the if(v < 0) return INT_MAX; correction. So much recursion that even small-ish values take millions of recursive calls.
A simple improvement is to "cache" the best solution found so far. Then when an intermediate solution is already worse than the best, no need to continue that path.
int computeChange(int cur[], int v, int n, int count_now, int *bestcount) {
if (count_now >= *bestcount) {
return INT_MAX;
}
if (v < 0) {
return INT_MAX;
}
if (v == 0) {
*bestcount = count_now;
return 0;
}
int min_count = INT_MAX;
for (int i = 0; i < n; i++) {
int count = computeChange(cur, v - cur[i], n, count_now+1, bestcount);
if (count < min_count) {
min_count = count + 1;
}
}
return min_count;
}
int bc = INT_MAX;
computeChange(cur, v, n, 0, &bc));
A secondary improvement is to attempt using large coins first
// int count = computeChange(cur, v - cur[i], n, count_now+1, bestcount);
int count = computeChange(cur, v - cur[n-i-1], n, count_now+1, bestcount);
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 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.
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;
}
if you have the sum of say x and the coins of denominations say a1, a2, a3, a4..(in decreasing order)
then the answer is simply->
x/a1+(x%a2)/a3+((x%a2)%a3)/a4+...
This should hopefully give the answer