1st question on StackOverflow...I have 2 programs, one in C and one in Pascal, that should give me the same output but they don't.
Pascal:
program ssgf108;
uses crt;
var n,q,r,s,i:integer;
var a:array[1..10] of integer;
begin
a[1]:=3;
a[2]:=-5;
a[3]:=12;
a[4]:=7;
a[5]:=-4;
a[6]:=-3;
a[7]:=2;
a[8]:=8;
a[9]:=4;
a[10]:=10;
readln(n);
q:=0;
r:=0;
s:=1;
for i:=1 to n do
begin
q:=i*a[i];
r:=i+a[i];
s:=s+q*r;
end;
writeln(q,' ',r,' ',s);
end.
C:
#include <stdio.h>
int main(){
int a[10],n,q,r,s,i;
scanf("%d",&n);
a[0]=3;
a[1]=-5;
a[2]=12;
a[3]=7;
a[4]=-4;
a[5]=-3;
a[6]=2;
a[7]=8;
a[8]=4;
a[9]=10;
q=0;
r=0;
s=1;
for (i=0;i<=n-1;i++){
q=i*a[i];
r=i+a[i];
s=s+q*r;
}
printf("%d %d %d",q,r,s);
return 0;
}
Upon entering 5 as n, Pascal outputs -20 1 871 while C outputs -16 0 567. Where's the error? Background for this question: I'm doing a problem solving competition at my school, next challenge is close, some questions require programming, I've done the first 2 challenges with Bash and Pascal, now I'm learning C so I'd like to do them in C. But I MUST avoid wrong results, since they mean lost points. This is a training on the competition's site, to convert pseudocode into code.
The values
q = i * a[i];
r = i + a[i];
depend on the values of i inside the loop, which are different between one-based and zero-based indexing loops. You need to do arithmetic with i+1 inside the C loop:
for (i = 0; i < n; i++) {
int i1 = i + 1;
q = i1 * a[i];
r = i1 * a[i];
s += q * r;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With