So my program reads numbers until the value 0 then it calculates the sum of numbers. Then I have to write a function which displays the sum. Also, my program read a number "y" from keyboard and I need to find the result of the sum/y.For example if the result of the sum is 10 and I enter y=3 the function result should return the result of 10/3.
So after the program display the result of the sum it asks me to enter again values until 0 value then it closes.
#include <stdio.h>
// Shows a message with what the program is doing.
void ShowIntroduction(void)
{
printf("My program finds a sum etc");
}
// find the sum of the numbers enter until 0 value
int sum(void)
{
int s=0,n;
do
{
scanf("%d",&n);
if (n > 0)
s=s+n;
}
while(n != 0);
return s;
}
// show the result
void sumResult(int a)
{
printf("The sum is %d", a);
}
// find the result of sum/y
double result(int s,int y)
{
double res;
res=s/(double)(y);
return res;
}
int main()
{
int y;
scanf("%d",&y);
ShowIntroduction();
sumResult(sum());
result(sum(),y);
return 0;
}
I am pretty sure I don't call a function in a correct way.
The program displays the sum but not the result of the sum / y
You are calling sum() twice, one for displaying the sum and one for displaying the average result. But because you let the users enter their values inside of sum() you see the behavior you describe.
Just run your program as is and enter two times the same sequence of numbers. Then you should see both the sum and the average. This is just to make you understand your program.
The solution is to store the sum returned by sum() in a variable and give its value to sumResult() and result().
Related
#include <stdio.h>
int even_numbers_sum(){
int d;
for(d=0;d<=100;d++){
if(d%2==0){
printf("\n this is even number loop %d",d);
}
}
int sum;
sum=sum+d;
printf("\n the value of total sum of the loop %d",sum);
return sum;
}
int main(){
even_numbers_sum();
}
my main aim is to calculate the sum of all the elemets of for loop i took a for loop and described its value and put a equation (if) to pass anynumber if its only even other wise it will not work and i have to add all those even number till 100 how do i do it
Initialised sum to 0 at the beginning. Changed the return type of the function to void as int was unnecessary. Sum has to be incremented in the if statement.
#include <stdio.h>
void even_numbers_sum(){
int d;
int sum=0;
for(d=0;d<=100;d++){
if(d%2==0){
printf("\n this is even number loop %d",d);
sum=sum+d;
}
}
printf("\n the value of total sum of the loop %d",sum);
}
int main(){
even_numbers_sum();
}
look the following code. I've written this code for any number if you want to change the upper bound instead of 100 , you just have to pass the integer to the function i.e. if you want to get the sum of all even integers from 0 to 100, you have to pass 100 while calling the function.
#include <stdio.h>
void even_numbers_sum(int i){
int d;
int sum=0;
for(d=0;d<=i;d+=2){
printf("\n this is even number loop %d",d);
sum=sum+d;
}
}
printf("\n the value of total sum of the loop %d",sum);
}
int main(){
even_numbers_sum(100);
return 0;
}
1.first change is here in function declaration and definition you have to write int i in the parentheses.
void even_numbers_sum(int i)
2.Secondly there is no need to put the condition if you want to start from 0. it can be done by simply increment d by 2.
for(d=0;d<=i;d+=2)
3.Your main method has return type int so there should be some integer returned.
return 0;
I hope this will help you to solve your problem. If there is anything which you want to ask I'll be glad to help you.
Firstly, you should initialize sum as 0 at begin. sum may be not 0 without initialization.
Secondly, in your code, sum will be only add with the final even number (100), not add each each even number from 0 to 100.
A correct example as below:
#include <stdio.h>
int even_numbers_sum()
{
int d, sum = 0; // initialize sum as 0
for (d = 0; d <= 100; d++) {
if (d % 2 == 0) {
printf("\n this is even number loop %d", d);
sum = sum + d; // add each even number to sum
}
}
// sum=sum+d; // This line code will add final even number and sum
printf("\n the value of total sum of the loop %d", sum);
return sum;
}
int main()
{
even_numbers_sum();
}
I am writing a program that calculates the value of e^x, according to the expansion formula.I need to print the answer so that it is correct upto 10 decimal places. I have tried to do it using, for, while and do while loop , however I cannot figure out where to terminate the loop , which condition to use to terminate the loop. i have written the code as follows:
#include<stdio.h>
#include<math.h>
int factorial(int x);
int main()
{
int x,n;
float sum,d_1;
printf("Enter the value of power :");
scanf("%d",&x);
n=1;sum=1;
while(sum <= %.10f)
{
d_1=pow(x,n)/factorial(n);
sum=sum+d_1;
n++;
}
printf("Answer is %f",sum);
return 0;
}
int factorial(int y)
{
int fact=1,i;
for(i=1;i<=y;i++)
{
fact=fact*i;
}
return(fact);
}
and i am getting the error message expected expression before %.
Please help.
You want to terminate the loop when the current term is smaller than some value. Also you want the loop to execute at least once, so a do-while loop is preferable:
n = -1;
do {
n++;
d_1 = pow(x, n) / factorial(n);
sum = sum + d_1;
} while (d_1 > epsilon);
As mentioned in the comments, there are other issues with the code when it comes to precision and overflow but that is a different story.
I am trying to work with binary numbers AND logical operator without using &. When I entered the example 1111 and 1000, a floating point exception (core dumped) occurred. I am waiting this code same length two binary numbers and after print for example print:1001 and 1111 = 1001
#include<stdio.h>
int length(int a,int b);
int andop(int a,int b);
int main(){
int first,sec;
do{
printf("First integer: ");
scanf("%d",&first);
printf("\nSecond integer: ");
scanf("%d",&sec);}
while(andop(first,sec)==0);
printf("\n%d AND %d= %d",first,sec,andop(first,sec));
return 0;
}
int andop(int a,int b){
int a_1,b_1;
int result=0;
a_1=a;
b_1=b;
while(a_1>1){/*Checking if first is binary or not,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (a_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
a_1=a_1/10;
}
while(b_1>1){/*Checking if first is binary ,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (b_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
b_1=b_1/10;
}
while (length(a,b)>0){
result=result+(a%10)*(b%10);
a=a/10;
b=b/10;
if(length(a,b) == 0){
break;
}
result=result*10;
}
return result;
}
int length(int a,int b){
if(a == 0 || b == 0){
return 0;
}
int temp_a,temp_b;
int length_a=0,length_b=0;
temp_a=a;/*i assign the number into the temporary variable _a and _b*/
temp_b=b;
while(temp_a>0){//checking how many digit a is
temp_a=temp_a/10;
length_a++;
}
while(temp_b>0){//checking how many digit b is
temp_b=temp_b/10;
length_b++;
}
if(length_!=length_b){/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
return length_a;
}
The following code is the source of the problem:
while(length_a/length_b!=1){/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
You are using a very strange way to test if two variables (length_a and length_b) are the same! Further, if length_b is zero (as it appears to be, at some stage), then the division will cause the error.
You can just use a simple comparison of the two variables:
if (length_a != length_b) {/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
EDIT: There are a number of other errors in your code but the suggestion I have given will address the specific error you have asked about.
In your program, the floating point exception occurs because of division by zero in function length.
You should check if a or b is 0 before doing anything in length().
Try adding this at the start of length
if(a == 0 || b == 0)
return 0;
Also, check if length() returns 0 before multiplying result by 10 in andop
i.e. change length(a, b) to
if(length(a, b) == 0)
break;
Even after this, your program will print the result in reverse order, so you will have to print the result in reverse order. Try creating a function for that.
I am trying to use "Press 'q' to quit" functionality to exit a do...while loop for calculating the average of a series of user-defined integers. Following several examples I was able to get the exit value to work but it is being included as part of calculating the average.
Example:
quixote#willow:~$ gcc sentinel-borked.c -o sentinel-borked
sentinel-borked.c: In function 'main':
sentinel-borked.c:22:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sum = sum + value;
^
quixote#willow:~$ ./sentinel-borked
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: q
Count is: 3
Average is: 214197589.333333
quixote#willow:~$
I know that the "q" is being treated as an integer, but I'm not sure how to re-write my code to escape it. :(
The simplest workaround that I can think of is to prompt the user for an end point (i.e. "how many integers are you averaging?") and use that, but I would really like to figure this out.
Here is the code I have so far.
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg;
char *value;
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
do {
// Loop through to input values
printf("\nEnter an answer string or q to quit: ");
fgets(value, 10, stdin);
if (value >= 0){
sum = sum + value;
count = count + 1;
}
else {
printf("\nValue must be positive");
}
} while (value[0] != 'q');
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
return 0;
}
EDIT: Replaced screenshot with plain-text inside of a code block. Original image still located at: https://i.stack.imgur.com/qza1N.png
Try this:
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg=0;
char value[10]="";//make value an array or allocate memory for it using malloc and also null initiate it
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
fgets(value,10,stdin);
if(value[strlen(value)-1]=='\n'){//if the user enters a string less than 10 chars a newline will also be stored inside the value array
value[strlen(value)-1]='\0';//you need to remove that \n and replace it with null
}
else{
while((getchar())!='\n');//just removing any extra chars left(when the user enters a string greater than 10 chars)
}
while(value[0]!='q'){//beware it will only check for the first char of the array to be q, anything else will still proceed the loop
sum+=strtol(value,NULL,10);//use this to convert integers inside the array to long ints(many other ways exists)
count++;
fgets(value,10,stdin);//overwrite value each time to get input
if(value[strlen(value)-1]=='\n'){
value[strlen(value)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
if(count==0){
printf("\nAverage is: %lf\n", avg);
}
else{
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
}
return 0;
}
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}