C program giving extremely wrong answer - c

Program takes an integer input num from the keyboard and computes the sum of square of i for all I from 1 to num (inclusive).
#include <iostream>
#include <math.h>
int main()
{
int num;
int total;
printf("Please enter a number:");
scanf("%d", &num);
for (double i = 1; i <= num; i++) {
total += (i*i);
printf("%d", total);
}
}
The code above compiles correctly, but when inputting 5 it prints 15143055. Why is it doing this?

#include <iostream> is c++. #include <math> is not used. total is uninitialized. Comparing floating point values may not behave the way you want, so using a (unsigned) integer type instead as a loop counter. Loop values by convention start at 0 instead of 1 in c (you could increment i fist thing in the loop to avoid the double (i+1) but this will be optimized out anyways). Also, your loop not run for a negative value so just require unsigned values. As you sum integers the result ought to be an integer, but double would give you a larger range so I left it as such. Missing return:
#include <stdio.h>
int main() {
unsigned num;
printf("Please enter a number: ");
scanf("%u", &num);
double total = 0.0;
for (unsigned i = 0; i < num; i++) {
total += (i+1)*(i+1);
}
printf("%lf\n", total);
return 0;
}
and the resulting output:
Please enter a number: 3
14.000000

Related

How to double digits in number

I am having a problem on how to double digits of any number.
For example, the number: 12345 output would be 1122334455 using functions and loops.
#include <stdio.h>
int main() {
int num;
printf("Please Enter a number");
scanf("%d",&num);
for(int i=0;i<=num%10;i++) {
if(i==num%10)
newNum+=i;
for(int i=1;i<=num%10;i++) {
if(i==num/10%10)
newNum+=i;
I am assuming that you do not have to store the value with duplicated digits, as storing it as int will quickly overflow. If you have to, you can use long long or an array.
Your for loop does not make sense. You have to loop until all intergers have been duplicated. To do so, determine the ones place with mod 10, then divide number by 10. It will loop until number is 0. Try this.
#include <stdio.h>
int main(void) {
int number;
int temp;
printf("Enter an integer: ");
scanf("%d", &number);
while(number) {
temp = number % 10;
printf("%d%d", temp, temp);
number /= 10;
}
return 0;
}

Average of Even Numbers and Product of all Odd Numbers

#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.

Calculating the average of user inputs in c

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.

Simple C Program, Unknown output

Problem Statement
You are given an array of integers of size . You need to print the sum of the elements of the array.
Note: A signed 32-bit integer value uses bit to represent the sign of the number and remaining 31 bits to represent the magnitude. The range of the 32-bit integer is . When we add several integer values, the resulting sum might exceed this range. You might need to uselong long int in C/C++ or long data type in Java to store such sums.
Input Format
The first line of the input consists of an integer. The next lines contain space separated integers describing the array.
Constraints
Output Format
Output a single value equal to the sum of the elements of the array.
Sample Input
5
1000000001 1000000002 1000000003 1000000004 1000000005`
Sample Output
5000000015
My program
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,i;
scanf("%d",&n);
long int a[5],sum;
for(i=0;i<=n-1;i++){
scanf("%ld %ld %ld %ld %ld",&a[1],&a[2],&a[3],&a[4],&a[5]);
}
for(i=0;i<=n-1;i++){
sum = sum + a[i];
}
printf("%ld",sum);
return 0;
}
Error description
Input (stdin):
5
1000000001 1000000002 1000000003 1000000004 1000000005
Your Output (stdout):
140692151765426
Expected Output:
5000000015
Compiler Message:
Wrong Answer
This works fine :
#include <inttypes.h>
int main()
{
int n,i;
scanf("%d",&n);
unsigned long long int a[5];
unsigned long long int sum=0;
for(i=0;i<n;i++)
{
scanf("%llu",&a[i]);
}
for(i=0;i<n;i++)
{
printf("%llu\n",sum);
sum = sum + a[i];
}
printf("\nSum is : %llu",sum);
return 0;
}
Use the ll long-long modifier with the u (unsigned) conversion
You don't basically need an array here. Just
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
long long int a, sum = 0;
while (n--) {
scanf("%lld", &a);
sum += a;
}
printf("%lld", sum);
return 0;
}
The program has following issues:
Array indexing is wrong : Array is of size 5 starting from 0 , you can use only till a[4] , but for scanf() , it tries to read value as &a[5].
No use of for loop when you are using hard coded index a[1],a[2],etc. Instead the below code will be better to get input as follows:
for (i = 0; i < n; i++ ) {
scanf("%ld",&a[i]);
}
Sum includes : sum = sum + a[i];
when i = 0 --> a[0] will have have junk values because input was not taken from user as scanf started from a[1] . Since array is not initialized this is uninitialized auto variable, it might have junk values which will get added in the sum .
sum itself is also not initialized, so it will contain junk value and for very first addition : sum = sum + a[0]; thsi junk value will get added .
Hope this answer your query for unexpected output.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n,i;
cin >> n;
long long int s=0;
long int a[10];
if(n>=1 && n<=10)
{
for(i=0;i<n;i++)
{
cin>>a[i];
s=s+a[i];
}
}
cout<<s;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,i;
scanf("%d",&n);
long int a[10];
long long sum=0;
for(i=0;i<=n-1;i++){
scanf("%ld",&a[i]);
}
for(i=0;i<=n-1;i++){
sum = sum + a[i];
}
printf("%ld",sum);
return 0;
}

How to fix a Segmentation Fault?

Im writing a C program that is supposed to add every number until it hits a sentinel value. Then average it all together.
Im not sure where the problem is but I think it might be that num never actually changes. Any help is appreciated.
#include <stdio.h>
int sentinal = 9999;
int iterations = 0;
int total = 0;
int average;
int num;
int main(void){
do{
printf("Enter a number to add:\n");
scanf("%d\n", num);
total = total + num;
iterations++;
}while (num != sentinal);
average = total/iterations;
printf("%d\n", average;
return 0;
}
Running version
#include <stdio.h>
int main(){
int sentinel = 9999;
int iterations = 0;
int total = 0;
float average;
int num;
while(1){
printf("\nEnter a number to add: ");
scanf("%d", &num);
if (num == sentinel){
break;
}else{
total = total + num;
iterations++;}
}
average = (float) total/iterations;
printf("%f\n", average;
return 0;
}
Your problem is in the line:
scanf("%d\n", num);
scanf requires a memory address of the variable where should put the value the was read. This is done using the operator &. Your code should be:
scanf("%d\n", &num);
scanf() takes a pointer to the value parsed from standard input. You're passing the actual value, not the pointer to the value.
There are many tools in Linux to find out Segmentation and other compilers as well. If you want to really debug where your code is popping segmentation fault , you can use GDB and valgrind .It exactly gives you where you have error in your code .
Provide address i.e. & when storing value using scanf.
Declare average as float, and while calculating average use average = (float) total / iterations and use %f while printing average.
Check your printf when you are printing average, closing bracket is missing.

Resources