The for loop I wrote to calculate sum of numbers is not working properly.
The program finds the average of the given numbers using a dynamically allocated array.
#include<stdio.h>
main()
{
int no_of_nos;
printf("Enter the number of numbers yuo want to do average : ");
scanf("%d",&no_of_nos);
int x[no_of_nos+1];
int i;
for(i=0;i<no_of_nos;i+=1)
{
printf("Enter the values for the element of the array : ");
scanf("%d",&x[i]);
}
int sum=0,j;
for(j=0;j<no_of_nos;j++)
{
sum = x[j] + x[j+1];
}
printf("The sum of the given numbers = %d \n",sum);
float average = sum / no_of_nos;
printf("The average of the given numbers = %0.2f",average);
}
Your second loop is wrong, it should read:
for( i=0; i<no_of_nos; i++ ) {
sum += x[i];
}
No need for another integer, 'i' will do fine. You could optimise it further by moving the sum up before the first loop then totalise sum as you enter the values. Do you need the array?
int sum = 0;
for( int i=0; i<no_of_nos; i++ ) {
int x;
printf("Enter the values for the element of the array : ");
scanf("%d", x);
sum += x;
}
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
There is no sense to declare the array x with no_of_nos+1 elements instead of no_of_nos elements. So the declaration of the array should look like
int x[no_of_nos];
In fact an array is not required if you need only to calculate the average of entered numbers.
It is better initially to declare the variable sum as having type float or double. Otherwise this expression statement
float average = sum / no_of_nos;
does not make a great sense because the expression sum / no_of_nos evaluates as an integer expression that is in any case the result of the expression is an integer.
However if the variable sum declared like for example float then the expression sum / no_of_nos will have the type float.
For example
float sum = 0;
//...
float average = sum / no_of_nos;
Compare two outputs of the average in the following demonstrative program.
#include <stdio.h>
#define N 2
int main(void)
{
int a[N] = { 1, 2 };
int sum1 = 0;
for ( size_t i = 0; i < N; i++ ) sum1 += a[i];
float average = sum1 / N;
printf( "The first average is equal to %0.2f\n", average );
float sum2 = 0;
for ( size_t i = 0; i < N; i++ ) sum2 += a[i];
average = sum2 / N;
printf( "The second average is equal to %0.2f\n", average );
return 0;
}
The program ooutput is
The first average is equal to 1.00
The second average is equal to 1.50
This loop
for(j=0;j<no_of_nos;j++)
{
sum = x[j] + x[j+1];
}
also does not make sense. It is enough to write
for(j=0;j<no_of_nos;j++)
{
sum += x[j];
}
The program to calculate the Average of given numbers can be written without the use of arrays.
The following program finds the average of given numbers and gives the answer upto two decimal places:
#include<stdio.h>
main()
{
int n,i=0,j;
float sum=0;
printf("Enter the number of elements : ");
scanf("%d",&n);
for(;i<n;i++)
{
printf("Enter the number : ");
scanf("%d",&j);
sum = sum + j;
}
printf("The sum of the given numbers = %0.2f \n",sum);
float average = sum / n;
printf("The Average of the given numbers = %0.2f",average);
}
Related
I am new to programming in C and I am doing some activities for my first year in CS. The following activity consists of calculating the sum of squares of the digits of a user input number and the output should be as follows:
Number: 1234
n=1234; sum=16
n=123; sum=25
n=12; sum=29
n=1; sum=30
Result: 30
I have got it for the most part, the thing that I don't understand is how to store a value in a variable, update said variable and print the result, all whilst being inside a loop.
This is what I came up with:
int main() {
int num,i,sum=0,result,square;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
i=0;
while(num>i)
{
sum=num%10;
square=sum*sum;
printf("\nn=%d; sum= %d",num,square);
num=num/10;
}
result=sum;
printf("\nResult: %d",sum);
return 0;
}
How can I sum the square of the digits all together and print them as the example given?
Write something like the following
int digit = num % 10;
square = digit * digit;
sum += square;
printf("\n=%d; sum= %d", num, sum );
Pay attention to that the variable i is redundant:
i=0;
while(num>i)
just write
while ( num != 0 )
Also introducing the variable result is redundant and does not make sense because it is used nowhere.
You need a variable, keeping track of the input number (num), a variable keeping track of the sum ('sum') and a variable with the current digit (digit). Every iteration, you can calculate the digit, square it and add it to the sum. The a += b operation is equivalent to a = a + b, in case you are wondering. The same is for a /= b. Also a concept you can use (but don't have to), is implicit boolean conversion. When using a comparison (like num != 0 or num > 0) you can replace it with the number itself. In C, 0 equals false and everything else equals true.
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
while (num) { // is equal to num != 0
int digit = num % 10;
sum += digit * digit;
printf(" n=%d; sum= %d\n", num, sum);
num /= 10;
}
printf("Result: %d\n", sum);
return 0;
}
EDIT:
Some people prefer to use num != 0 or num > 0, because it is more readable. You should stick to it too for the start, until you are paid to confuse your coworkers.
I'm trying to add the elements in an array. It's just a simple program to calculate the average of student grades. I know this is probably a rudimentary way to code this, I'm looking to do it more efficiently. However my code is not returning the average. I would greatly appreciate any help. I did try this with a for loop but got the same incorrect answer.
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your five test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
sum = sum + grades[6];
average = sum / 5;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
You should sum all grades and then divide by their amount (in your case it is 6 not 5, because grades array has 6 elements). Here is a code sample:
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your six test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
average = sum / 6;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
I'm trying to add the elements in an array.
This is maybe already a wrong track regarding the title (and the code) where it is about averaging elements in an array.
How you build the array is up to you; I choose the simplest way. An important decisions is: is size of array and number of values the same? That is what n_grades does. The four zeroes in the array initialization illustrate the difference.
An average most likely should be a floating point number.
A nasty problem with averages is the lurking overflow. Very unlikely in this setting, but there is a more robust (and elegant) algorithm. The (double) cast is the un-elegant part, but is needed because the division is between two integers. Still this is the compact core:
for (i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
corresponding to the math formula:
i<n
A = Sum G_i/n
i=0
("Sum" is the big Sigma)
#include <stdio.h>
int main()
{
int grades[] = {10,10,9,10,11,11,0,0,0,0};
int n_grades = sizeof grades / sizeof*grades; // use all elements
//n_grades = 6; // use only first n elements
double aver = 0;
for (int i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
printf("The average of the students test scores is %f (n= %d):\n",
aver, n_grades);
return 0;
}
Now it prints:
The average of the students test scores is 6.100000 (n= 10):
or, uncommented, i.e. limited to 6 grades::
The average of the students test scores is 10.166667 (n= 6):
You're assuming that grades[6] holds the sum of all the values in the grades array, which is wrong of course.
You need something like:
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
Here two somehow similar problems (1.-Sum of uneven numbers until n; 2.-Sum of the series 1/n) to be solved using for-loops.
I chose the shown strategy and while for the 1st problem my loop works as expected, for the 2nd it does not iterate.
I can't see the difference to understand what is wrong in the last case.
----1----- :
int main()
{
// Example: Input=5, Output=1+3+5=9
int i, lastNum ,sumUneven;
printf("Until what n should the uneven numbers be added: ");
scanf("%d", &lastNum);
sumUneven=0;
for (i=1; 2*i-1<=lastNum; i++) {
sumUneven=sumUneven + (2*i-1);
}
printf("Sum of uneven numbers until %d: %d", lastNum, sumUneven);
}
----2------------:
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n, sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++) {
sum = sum + 1/i;
}
printf("Sum of the series until 1/%d: %d", n, sum);
}
The expression 1/i performs integer division (truncating any fractional part) since both operands have type int. So if i is greater than 1 the division will result in 0. The variable sum is also of type int so it can't hold fractional numbers.
Perform the division as 1.0/i, which is floating point division since one argument has type double, and change the type of sum to double. Also use %f to print sum.
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n;
double sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++)
{
sum = sum + 1.0/i;
}
printf("Sum of the series until 1/%d: %f", n, sum);
}
you're using an int to keep track of floats which will not work.
1/n will be a float a simple fix would be
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n;
float sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++) {
sum = sum + 1/i;
}
printf("Sum of the series until 1/%d: %f", n, sum);
}
you could also use the double declaration
hope this was helpful
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.