Hello im new to C programming and this is my C Quiz question.
I tried really hard but i cant find the solution or whats wrong with my code.
This equation block cant work.
Any help will be appreciated
Write a C program that displays the below menu and performs the
corresponding operation, according to the selected menu item.
Write separate functions for each menu item and call the related function according to the
selection.
The menu:
(1) Calculate fibonacci value of the entered number,
(2) Calculate the equation (Get value of R from the user),
(3) Get four numbers from the user, sort them in ascending order
Enter your choice:
When the user enters a number (1, 2 or 3) corresponding function will be called
to perform the operation.
The user will enter -1 if he wants to continue and the
menu will be appeared on the screen again.
Question Equation Pic
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int numForFibonacci)
{
int i = 0;
int j = 1;
int k = 1;
for (int b = 1; b <= numForFibonacci; b++)
{
k = i + j;
printf("%d \n", i);
i = j;
j = k;
printf("%d ", k);
}
printf("\n");
return k;
}
float theEquation(float numR)
{
float multipl, result = 1;
for (int i = 1; i <= numR; i++)
{
multipl = (2i + 4) / (i * i);
result *= multipl;
}
printf("Result is %f", result);
return result;
}
int ascending(int n)
{
int k = 0, i = 0, j = 0, number[4];
for (int w = 0; w < n; w++)
scanf("%d", &number[w]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
k = number[i];
number[i] = number[j];
number[j] = k;
}
}
}
for (i = 0; i < n; ++i)
printf("\n%d \n", number[i]);
return i;
}
int main()
{
int choice, choiceFibo;
float choiceR;
do
{
printf("[1]Fibonacci calculation\n");
printf("[2]calculating the equation: (2k+4)/(k*k)\n");
printf("[3]sorting numbers in ascending order\n");
scanf("%d", &choice);
if (choice == 1)
{
printf("enter a number for fibonacci\n ");
scanf("%d", &choiceFibo);
fibonacci(choiceFibo);
}
else if (choice == 2)
{
printf("[2]enter a number for (2k+4)/(k*k)\n");
scanf("%f", &choiceR);
theEquation(choiceR);
}
else
{
printf("[3]enter four numbers to sort them in ascending order\n");
ascending(4);
}
printf("If you want to do another calculation enter '-1'.\n");
scanf("%d", &choice);
} while (choice == -1);
return 0;
}
TL;DR: Two main issues:
<integer>i in GNU C represents a complex number, not multiplication.
integer division is not what you'd expect
Your issue lies on this line:
multipl = (2i + 4) / (i * i);
You might think that 2i would evaulate as 2 * i, but in C, 2i is a complex int.
This can be seen here:
#include <stdio.h>
int main()
{
int i=1;
printf("%d", 2i);
return 0;
}
You would expect this to print 2, but instead we get a warning.
Compiled with onlinegdb:
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘complex int’
Second issue: Integer division. The other answer already covered it pretty well, but for the sake of self-contained answers:
In C, integer division finds the integer solution and discards the remainder.
2/5 = 0
6/5 = 1
10/5 = 2
10/4 = 2
10.0 / 4 = 2.5
(double)10/4 = 2.5
You need to "type coerce" one of the values in your numerator or denominator to a float/double, which will coerce the entire fraction to a float/double.
You can do this either with 2.0*i or (double)2*i. Either one works, but the second one is more explicit for readability.
To fix the issue, simply change 2i to (double)2*i.
There are only three edits required to get a clean compile:
Change int main() to int main(void)
Change (2i + 4) / (i * i) to (2*i + 4) / (i * i)
Change int ... number[4]; to int ... number[4]={0};
If you did not see something similar to the following upon your compile, then turn on all warnings:
> s0_15.c - 4 warnings
> 28, 28 warning: implicit conversion discards imaginary component: '_Complex int' to 'float'
> 45, 17 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 54, 27 warning: variable 'number[i]' may be uninitialized when used here
> 38, 5 note: variable 'number' is declared here
> 58, 5 warning: function declaration isn't a prototype.
To ensure accurate calculations, see integer division addressed in another answer under your post.
Related
Program not working, not giving output, I don't know what to do, where the problem is.
I'm trying to find out the largest palindrome made from the product of two 3-digit numbers.
#include <stdio.h>
main() {
int i, k, j, x;
long int a[1000000], palindrome[1000000], great, sum = 0;
// for multiples of two 3 digit numbers
for (k = 0, i = 100; i < 1000; i++) {
for (j = 100; j < 1000; j++) {
a[k] = i * j; // multiples output
k++;
}
}
for (i = 0, x = 0; i < 1000000; i++) {
// for reverse considered as sum
for (; a[i] != 0;) {
sum = sum * 10 + a[i] % 10;
}
// for numbers which are palindromes
if (sum == a[i]) {
palindrome[x] = a[i];
x++;
break;
}
}
// comparison of palindrome number for which one is greatest
great = palindrome[0];
for (k = 0; k < 1000000; k++) {
if (great < palindrome[k]) {
great = palindrome[k];
}
}
printf("\ngreatest palindrome of 3 digit multiple is : ", great);
}
What do you mean with "not working"?
There are two things, from my point of view:
1) long int a[1000000], palindrome[1000000]
Depending on you compile configuration you could have problems compiling your code.
Probably the array is too big to fit in your program's stack address space.
In C or C++ local objects are usually allocated on the stack. Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap.
#include <stdio.h>
long int a[1000000], palindrome[1000000], great, sum = 0;
main() {
int i, k, j, x;
2) printf("\ngreatest palindrome of 3 digit multiple is : ", great);
I will change it by :
printf("\ngreatest palindrome of 3 digit multiple is %li: ", great);
Regards.
Compiling and running your code on an on-line compiler I got this:
prog.c:3:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main() {
^
prog.c:34:61: warning: data argument not used by format string [-Wformat-extra-args]
printf("\ngreatest palindrome of 3 digit multiple is : ", great);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
2 warnings generated.
Killed
Both the warnings should be taken into account, but I'd like to point out the last line. The program was taking too much time to run, so the process was killed.
It's a strong suggestion to change the algorithm, or at least to fix the part that checks if a number is a palindrome:
for (; a[i] != 0;) { // <-- If a[i] is not 0, this will never end
sum = sum * 10 + a[i] % 10;
}
I'd use a function like this one
bool is_palindrome(long x)
{
long rev = 0;
for (long i = x; i; i /= 10)
{
rev *= 10;
rev += i % 10;
}
return x == rev;
}
Also, we don't need any array, we could just calculate all the possible products between two 3-digits number using two nested for loops and check if those are palindromes.
Starting from the highest numbers, we can store the product, but only if it's a palindrome and is bigger than any previously one found, and stop the iteration of the inner loop as soon as the candidate become less then the stored maximum. This would save us a lot of iterations.
Implementing this algorithm, I found out a maximum value of 906609.
Help me to find the sum of this series x^1+x^4+x^7+.. to n terms
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
int l=1;
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
printf("x ^ %d + power %d",x,l);
return 0;
}
I think this is what you want :) i've commented the errors
#include<conio.h>
#include<math.h>
int main(int argc, char const *argv[]) {
int n;
float x;
float l=0,i=0;
// initialize n first to determine how far the sum should go
printf(" Enter the value of n :");
scanf("%d",&n);
printf(" Enter the value of x :");
scanf("%f",&x);
for (int i = 0; i <n; i++)
{ //l+= pow(x,(i*3)+1); is equivilant to l= l+ pow(x,i+3); which i assume that's what you wanted to do
// l should be a float as well not int since x is a float
l+= pow(x,(i*3)+1);
if(i!=n-1)printf(" %f^%d +",x,i*3+1);
else printf("%f^%d",x,i*3+1);
}
printf("\nResult of the sum is %f",l);
return 0;
}
There's a problem in this loop:
for (int i = 1; i <=n; i++)
{
l = pow(x,l+3);
}
You set l every time and then in the end it has the value of the last assignment, but you wanted to add them all up. Also, it should be i in the pow call, not l+3, instead you should move that step of 3 to the loop increment. Try this:
int l = 0;
for (int i = 1; i <= n; i+=3)
{
l += pow(x, i);
}
Also make sure that you initialize n, you should probably read it in using scanf, just like you do with x.
Also note that since l is int, it's going to be truncated every time. If you don't want that, you should declare it as float instead, and depending on how precise the result should be, you might even want to consider double.
#include <stdio.h>
#include <math.h>
int main()
{
double x;
unsigned n;
fprintf(stderr, "enter x and n :");
/* enter x as a double and x as an unsigned number, both on the same line, and check 2 values are enter */
if (scanf("%lg %u", &x, &n) != 2)
puts("invalid or missing values");
else {
double r = 0; /* sum initialization */
int p = 1; /* the power to apply, 1 then 4 then 7 etc */
while (n--) { /* have to sum n times */
r += pow(x, p); /* x^1+x^4+x^7+... */
p += 3; /* next power value */
}
printf("%g\n", r);
}
return 0;
}
if I well understand n terms x^y must be added rather than the last pow is x^n, I use double for x and of course the result ( r )
Executions :
enter x and n :1.2 3
6.85678
enter x and n :2 1
2
Check with bc :
% bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=6
1.2 + 1.2^4 + 1.2^7
6.856780
Multiple operations on floating point numbers tend to compound rounding errors very quickly, so if you can minimize the number of operations, always do.
Now if you recognize that your polynomial is a Geometric series (see wikipedia article) with a = x and r = x^3, then we have the following pseudo-code algorithm (note no loops!):
Case 1 (x == 0): Sum == 0 regardless of n.
Case 2 (x == 1): Sum == n.
Case 3 (x any other number): Sum == x*(1-(x^(3*n)))/(1-(x^3)).
Case 4 (n==infinity and -1<x<1): Sum == x/(1-(x^3)).
I trust you can code accordingly.
I need to write a C program which will read a number (in base 10) from user input and output it in any base which is a power of 2. The calculations have to be performed in one function, to_base_n, which takes the parameters num and base and prints the number in the respective base. As a validation check, the program also checks if the base is a power of two with the isPowerofTwo function.
The way the conversion is carried out is by means of long division which carries out the logic in the pseudocode below:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
Which I believe is arithmetically sound. But when I try to, for example, convert 82000 to base 4, I get the following output:
The large digits appearing are even bigger than num itself, so I figured the modulus cannot be entering the array properly (because ∀{x,n}; x mod n < x). I can't seem to find what's wrong with it. The full code is listed below.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
Can anyone help explain what's wrong with it?
The number 82000 in base 4 would be:
110001100
Which is exacly what you get. Your mistake is that:
They are printed backwards.
You are printing more digits than you should, so you print garbage.
You ignore the number of digits extracted with your pseudo code, so you print uninitialised elements of the array.
for (i = 0, i < 15, i++)
print digits[i]
And they are printed in reverse order. I suggest changing it to this
for (i = i - 1, i >= 0, i--)
print digits[i]
and as C code in your function
for(i = i - 1; i >= 0; i--)
printf("%d|",digits[i]);
First of all, I searched and all questions I found are similar but not exactly this one.
This is my first post here, I'm a beginner in programming and currently learning to code in C.
Been struggling with this code for about 5 hours now.
The question is create a program in C, using only loops (and not using pow(), using stdio.h library only).
The question is to get the user to give you two numbers - X and N
the program will print The result of the following equation:
1+2x+3x^2+4x^3+....+nx^(n-1)
For example for the input of - X=2 N=3
1*2^0 + 2*2^1 + 3*2^2
What the program will print is "17"
This is my attempt so far, I got to the Power function but I cant find a way to incorporate into the programm itself.
#include <stdio.h>
int main(void)
{
int i, j=0, b = 0;
float x, n;
double sum = 0, sumt=0;
do{
printf("Please enter two numbers \n");
flushall;
scanf("%f %f", &n, &x);
} while (x <= 0);
for (i = 1; i <= n; i++){
sum = x*x;
}
sumt += sum;
printf("%f", sum);
}
Instead of trying to create an implementation of pow, you will need to take advantage of the relationship between the terms of the expression.
The n-th term is nx^(n-1). The n-1-the term is (n-1)x^(n-2).
If we denote the n-th term as T(n) and denote the n-1-th term as T(n-1),
T(n) = T(n-1)*x*n/(n-1)
Given the starting value of the first term,
T(1) = 1
you can compute the subsequent terms using the above formula.
The following code should work.
// Initialize the values for N=1
term = 1;
sum = 1;
// Iterate starting from 2
for (i = 2; i <= n; i++){
term *= x*i/(i-1);
sum += term;
}
The working Program based on the tips given by the almighty #R_Sahu (And others ;D)
**
#include <stdio.h>
int main(void)
{
int i, j = 0, c = 0;
float x, n, b = 0;
double term, sum;
do {
printf("Enter Two Numbers\n");
flushall;
scanf("%f%f", &n, &x);
} while (x < 0);
for (i = 2; i < n + 2; i++)
{
term = 1;
sum = 1;
for (i = 2; i <= n; i++){
term *= x*i / (i - 1);
sum += term;
}
}
printf("The answer is %.lf ", sum);
}
I will not give you the code, but the reasoning you should follow
First you have to somehow get the data from the user (as a parameter, from stdio... whatever)
x = getFromUser
n = getFromUser
You will then need to init a temporary result
result = 0
How many times do you have to add? -> Exactly n times
for(ii=0;ii<n;ii++) {
result = result + pow((ii*x),(ii-1)) //There is something missing here, I'll let you guess what
}
But wait; you cannot use pow. So you have to program it by yourself (I guess that's the idea of the exercise)
then you need a function, and it has to return an int (actually, it may return even irrational numbers, but I don't think they will require you to do that)
int customPow(int base, int exponent) {
//Put your for in here, and may the pow be with you
}
You need to figure out the code yourself, but the general idea is as follows:
Create your own pow function which returns x*n.
int pow(int x, int n){
//use a for or while loop to calculate x (*x)n times.
//pay attention to the base cases (i.e., when n = 0, or 1 etc)
}
ans = 0;
for(i = 0 to N-1){
ans = ans + pow(x,i-1)*i;
}
This is what I came up with:
#include <stdio.h>
int main (void)
{
int n, i, j;
float e = 1.0, nFact = 1.0;
printf ("please enter the number");
scanf ("%d", &n);
for (i = 1; i <= n ; i++)
{
for (j = 1; j <= i; j++)
{
nFact *= j;
}
e = e + (1.0 / nFact);
}
printf ("The value of 'e' is : %f", e);
return 0;
}
This is what I get from this code.
Input: 3
Output: 2.58333 (which is close to 2.6666...)
But for n=3, e should give 2.6666.. as a value.
Am I doing something wrong here? How can I get the proper output?
You are needlessly calculating the factorial in every iteration. Just replace the inner loop by nFact *= i;.
#include<stdio.h>
int main (void)
{
int n,i,j;
float e=1.0, nFact=1;
printf("please enter the number");
scanf("%d", &n);
for( i =1; i<= n ; i++)
{
nFact*=i;
e = e + (1.0/ nFact);
}
printf("The value of 'e' is : %f", e);
return 0;
}
Am i doing something wrong here?
You have forgotten to set the factorial variable to one. So, your variable is getting smaller quickly. This makes (1.0/nFact) even smaller and that is why you get smaller e.
nFact=1.0; //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1 ; j <= i; j++)
{
nFact *= j;
e = e + (1.0/ nFact);
}
//only single loop is more than enough
You are getting your factorial by O(n) complexity. Why not save the old value and use it in every iteration?(O(1)--->no need the factorial-loop. Just use old value since you are not resetting it. (Just multiply by i)
how can i get the proper output?
After the 11st or 12th iteration, your float would not give enough precision-resolution-minimum step. Double or BıgDecimal seems better if your going for science.
That loop is very inefficient: Note how your inner loop computes the same thing over and over!
Instead, you should keep a running term and update it:
double term = 1;
double result = term;
for (unsigned int i = 1; i != n; ++i)
{
term /= i;
result += term;
}
printf("With %u steps we compute %f.\n", n, result);