Simple C Program, Unknown output - c

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;
}

Related

Perfect numbers representation problem with function

The task is:
Write a program that prints the first n perfect numbers. Checking that the number is perfect should be done in the perfect function.
I did it like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
/*
*/
int perfect_number(long int n)
{
long int sum=0;
for(int j=1;j<n;j++)
{
long int candidate=j;
if(n%candidate==0)
{
sum=sum+candidate;
}
}
if(sum==n)
{
return n;
}
return 0;
}
int main()
{
int n;
printf("Enter how much perfect numbers you want :");
scanf("%d",&n);
while(n<1)
{
printf("Enter how much perfect numbers you want:");
scanf("%d",&n);
}
int counter=0;
for(long int i=1;counter<n;i++)
{
if(perfect_number(i))
{
printf("%ld ",i);
counter++;
}
}
return 0;
}
The problem arises when I type that I want, the first 5 perfect numbers or more. The program will print only 4 and will continue to work, it will search for numbers but will not print anything.
If I type in the first four perfect numbers, they will print 4 and finish the program, they will do everything right.
I thought the problem was in representing the fifth number, so I replaced int with long int, but that didn't help.

C program giving extremely wrong answer

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

decimal to octal conversion in c programming (using code blocks)

Decimal to octal conversion c.using code blocks 16.01.the conversion works until 63.This is my first time posting here
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// conversion of decimal to octal
int main()
{
int num,sum,count,x,y;
printf("enter a number\t");
scanf("%d",&num);
count = 0;
sum = 0;
while (num>0){
x=num%8;
x=x*pow(10,count);
count=count+1;
num=num/8;
sum=sum+x;
}
printf("\n%d",sum);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// conversion of decimal to octal
int main()
{
int num,i,len=0,x[100];
printf("enter a number\t");
scanf("%d",&num);
while (num>0){
x[len]=num%8;
num=num/8;
len++;
}
for(i=len;i>=0;i--)
printf("\n%d",x[i]);
return 0;
}
This will work for the conversion from decimal to octal.
Note: Check the logic works!.Make the sum long int. After 63 your int no longer able to hold the answer.
The problem with the code is actually reported by the compiler if you turn on some warnings, however the problem is that you are implicitly converting from double to int, and depending on the implementation, you'd lose precision. pow returns a double but you're storing it in an int (x)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// conversion of decimal to octal
int main()
{
int num,sum,count,x,y;
printf("enter a number\t");
scanf("%d",&num);
count = 0;
sum = 0;
while (num>0){
x=num%8;
x=x*pow(10,count);
/* ^^^^^^^^^^^^^^^^ problem here */
count=count+1;
num=num/8;
sum=sum+x;
}
printf("\n%d",sum);
return 0;
}
now the fix
Instead of using the library pow, you should implement your own that's integer only (because you KNOW you are using ints only)
/* a trivial implementation */
long pow10(int n) {
long result = 1;
while(n--) {
result *= 10;
}
return result;
}
Now to clean up the program a bit:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long pow10(int n);
/* a trivial implementation */
long pow10(int n) {
long result = 1;
while(n--) {
result *= 10;
}
return result;
}
int main()
{
int num, count;
long sum, x;
printf("enter a number\t");
scanf("%d",&num);
count = 0;
sum = 0;
while (num>0){
x=num%8;
x=x*pow10(count);
count=count+1;
num=num/8;
sum=sum+x;
}
printf("\n%ld",sum);
return 0;
}

Can't find the error in minimum difference between two numbers on array in C

So I'm really new to programming. I need to write a program that, if I give it any array of integers, it'll be able to find the two numbers closest to each other, and then give the difference between those two numbers. Also, the first number must be the number of integers that are going to be in the array.
So for example, I give it 3 1 4 8. The first 3 means that there will be three integers, so it must find the closest two numbers between those three. In this case, it's 4 - 1 = 3, so the output should be 3, but when I write it it gives me 16.
This is what I have, and I don't know what's wrong:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, str[n*n], minimum, c;
/* here I'll make a new array, and its elements will be all the
differences between all the elements of the previous one */
for(a=0;a<n;a++)
for(b=0+a*n;b<n;b++) {
if(st[b-a*n]==st[a])
str[b]=32000;
else
str[b]=abs(st[b-a*n]-st[a]);
}
// here I'll find the smallest element on the last made array
minimum = str[0];
for(c=0;c<n*n;c++)
{
if(str[c]<minimum);
{
minimum=str[c];
}
}
printf("%d", minimum);
return 0;
}
Edit: I tried to fix it with your answers but it still doesn't work.
New code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = st[0];
for(a=0;a<n;a++)
for(b=0;b<n;b++) {
if((st[b] != st[a]) && (abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}
Edit 2: Ok, I fixed it now. Thanks a lot ^^
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int n, i;
printf("write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = INT_MAX;
for(a=0;a<n;a++)
for(b=a+1;b<n;b++) {
if((abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}

ANSI C - Higher element on array

I'm having some issues on my code to get the highest number on an array of 5 elements, this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[4];
int x;
int main() {
for(x=1;x<6;x++) {
printf("Give me the time of runner 1: ");
scanf("%f",timerunner1[x]);
}
return 0;
}
This works perfectly, the output is:
Give me the time of runner 1: 14
Give me the time of runner 1: 3
Give me the time of runner 1: 10
Give me the time of runner 1: 5
Give me the time of runner 1: 2
How can I get the highest and lowest number of the array?
Maybe using a for or if.. How?
Thanks!
It doesn't work actually, you need to use the address of operator '&' to store the value in the array.
scanf("%f", &timerunner1[x]);
Also, your array isn't large enough to store the 6 integers that your loop is requiring and subscripting of an array starts at zero and ends at 5 (for 6 elements).
You can then either have another loop AFTER reading all your values to calculate the maximum or calculate it on the fly as below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[6];
int x;
float maximum = 0.0f;
int main() {
for (x = 0; x < 6; x++) {
printf("Give me the time of runner 1: ");
scanf("%f", &timerunner1[x]);
maximum = maximum > timerunner1[x] ? maximum : timerunner1[x];
}
printf("%f\n", maximum);
return 0;
}
Also, this code only works on positive values because maximum is initialised to zero and will always be larger than any negative value, if you need negative values, you should be able to experiement and figure that out.
Ok, in this program you will have to load the time of each player manually.
/* StackFlow
Find the highest of an array of 5 numbers */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
float timerunner1[ 5 ] ={ 0 };
float highest;
int highestindex, i;
/* Data input*/
for( i = 0; i < 5; i++ ){
printf( "\nEnter the %d element of the array: ", i );
scanf( %f, timerunner1[ i ] );
}
/* Considering that the first generated number is the highest*/
highest = timerunner1[ 0 ];
highestindex = 0;
/* The first element of an array is [0] not [1]*/
for( i = 1; i < 5; i++ ) {
/* if the next element in the array is higher than the previous*/
if ( highest < timerunner1[ i ]){
highest = timerunner1[ i ];
highestindex = i;
}
}
printf("\nThe highest time of the runner %d is: %f \n", highestindex, highest);
return 1;
}

Resources