C Programming Help #3: Arrays - Adding them up. (Update!)

GEC: Discuss gaming, computers and electronics and venture into the bizarre world of STGODs.

Moderator: Thanas

User avatar
Soontir C'boath
SG-14: Fuck the Medic!
Posts: 6817
Joined: 2002-07-06 12:15am
Location: Queens, NYC I DON'T FUCKING CARE IF MANHATTEN IS CONSIDERED NYC!! I'M IN IT ASSHOLE!!!
Contact:

C Programming Help #3: Arrays - Adding them up. (Update!)

Post by Soontir C'boath »

I have to write a program where two arrays must be added together but I'm having trouble in how to treat each one as an integer as I have no idea.
Write a program that begins by defining the arrays
int integer1 [ 5 ];
int integer2 [ 5 ];
int sum [ 6 ];
The program asks for five single-digit integers (selected form {0, 1, …, 9}, repetitions
allowed). As the program reads the digits, it stores each in one of integer1's cells.
Next, the program asks for and stores in integer2 five more single-digit integers. The
program then treats each array as if it represented a single integer. For example, if we
read 2, 3, 0, 3, 5 into integer1, the integer1 is interpreted as the fine-digit integer
23,035. The program adds the five-digit integers integer1 and integer2 and stores the
sum in the array sum. (The array sum has one more cell than do the other two so that it
can hold a carry.)
This is what I have so far and was done on MS Visual Studio 05 in C++ settings:

Code: Select all

#include "stdio.h"
#include "math.h"

void main()
{ int integer1[5];
int integer2[5];
int sum[6];
int i, j;
	

for(i=0;i<=4;i++){
		printf("Type in a digit from 0-9 for the first five digit number.\n");
		scanf("%d", &integer1[i]);
	}

for(j=0;j<=4;j++){	
	printf("Type another digit from 0-9 for the second five digit number\n");
	scanf("%d", &integer2[j]);
	}

sum[i+1]=integer1[i]+integer2[j];

printf("The sum is %d\n", sum[i+1]);

}
Last edited by Soontir C'boath on 2007-11-30 06:17pm, edited 1 time in total.
I have almost reached the regrettable conclusion that the Negro's great stumbling block in his stride toward freedom is not the White Citizen's Counciler or the Ku Klux Klanner, but the white moderate, who is more devoted to "order" than to justice; who constantly says: "I agree with you in the goal you seek, but I cannot agree with your methods of direct action"; who paternalistically believes he can set the timetable for another man's freedom; who lives by a mythical concept of time and who constantly advises the Negro to wait for a "more convenient season."
User avatar
InnocentBystander
The Russian Circus
Posts: 3466
Joined: 2004-04-10 06:05am
Location: Just across the mighty Hudson

Post by InnocentBystander »

Just iterate through the array, for each element in the int1 and int2 array, sum them up and put their sum into sum[], if the number exceeds 9 carry a 1 over into the next iteration of the loop.
User avatar
Chris OFarrell
Durandal's Bitch
Posts: 5724
Joined: 2002-08-02 07:57pm
Contact:

Post by Chris OFarrell »

Off the top of my head, there might be a cheap way of doing it.

Take the complete array then create a string, call something like ToString() (I think thats the function, I know Java has a whole heap of class functions that return strings from almost anything) then cast that string back into a normal, non array int and do your stuff on it.

EDIT.

Here is sort of what you are looking for. The function is 'itoa'. Not exactly sure if its going to work on an array, but you might want to try it.

Of course its probably easier just to do the manual addition code which is probably what they are testing you for anyway. And even though its often in stlib, it may not be a standard function, I can't remember.

Code: Select all

#include <stdlib.h>	// for itoa() call
#include <stdio.h>	// for printf() call

int main() {
	int num = 123;
	char buf[5];

	// convert 123 to string [buf]
	itoa(num, buf, 10);

	// print our string
	printf("%s\n", buf);

	return 0;
}
Image
User avatar
Beowulf
The Patrician
Posts: 10619
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

Easiest is just the manual addition code. After getting the arrays initialized, iterate over both of them, add the elements, and stuff the result in the sum. Remember to carry. The actual code for this is like 5 lines.

atoi and itoa are standard library functions, but it'll take more code to use them, and be more complicated, then manual addition.
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Coalition
Jedi Master
Posts: 1237
Joined: 2002-09-13 11:46am
Contact:

Post by Coalition »

Do you have to actually add the arrays, or can you do the addition outside the arrays? If outside, you can convert them to ordinary integers, add them, then reverse the process to stuff the result in sum. (aka Beowulf's solution)

If inside, go with Innocent Bystander's solution.

Of course, the fun part is if your teacher 'accidentally' types in a letter to crash your program. Do you need error-checking on it? The other fun is to make your your fields are initialized properly. Again, just iterate through the three arrays, putting a zero in each location.

The third option would be to allow for if your teacher tells you to add a third digit to the addition sequence. You'd have to add integer1[a], integer2[a], and integer3[a] together, and put the ones digit in sum[a]. From there, you check to see if integer1[a] plus integer2[a] plus integer3[a] is greater than ten. If it is, you divide the total by ten, dropping the remainder, and adding that to sum[a-1]. This way instead of just adding one each time, you are allowing for expansion to the program with minimal coding change.
User avatar
Pu-239
Sith Marauder
Posts: 4727
Joined: 2002-10-21 08:44am
Location: Fake Virginia

Post by Pu-239 »

Code: Select all

#include "stdio.h"
#include "math.h"

void main(){ 
	char integer1[5];
	char integer2[5];
	char sum[6]={0,0,0,0,0,0};
	int i;
   

	for(i=0;i<=4;i++){
		printf("Type in a digit from 0-9 for the first five digit number.\n");
		scanf("%d", &integer1[i]);
	}

	for(i=0;i<=4;i++){   
   		printf("Type another digit from 0-9 for the second five digit number\n");
   		scanf("%d", &integer2[j]);
   	}
	/*
	 * Start w/ least sig digit
	 * Add sum to existing contents of sum array, which should be filled w/ carry by previous 
	 * iteration, or 0 if no carry was performed.
	 * Set next array cell to carry.
	 */	
	for(i=4; i >= 0; i--){
		int sum = integer1[i]+integer2[i]; 
		sum[i+1]=sum%10+sum[i+1];
		sum[i]=sum/10;	
	}	

	printf("The sum is ");
	for(i=0;i<=5;i++){
		printf("%d",sum[i]);
	}
	printf(".\n");
}

ah.....the path to happiness is revision of dreams and not fulfillment... -SWPIGWANG
Sufficient Googling is indistinguishable from knowledge -somebody
Anything worth the cost of a missile, which can be located on the battlefield, will be shot at with missiles. If the US military is involved, then things, which are not worth the cost if a missile will also be shot at with missiles. -Sea Skimmer


George Bush makes freedom sound like a giant robot that breaks down a lot. -Darth Raptor
User avatar
phongn
Rebel Leader
Posts: 18487
Joined: 2002-07-03 11:11pm

Post by phongn »

Posting complete code is not going to help him.
User avatar
Darth Wong
Sith Lord
Sith Lord
Posts: 70028
Joined: 2002-07-03 12:25am
Location: Toronto, Canada
Contact:

Post by Darth Wong »

Isn't it cheating to get people to help you with your programming homework?
Image
"It's not evil for God to do it. Or for someone to do it at God's command."- Jonathan Boyd on baby-killing

"you guys are fascinated with the use of those "rules of logic" to the extent that you don't really want to discussus anything."- GC

"I do not believe Russian Roulette is a stupid act" - Embracer of Darkness

"Viagra commercials appear to save lives" - tharkûn on US health care.

http://www.stardestroyer.net/Mike/RantMode/Blurbs.html
User avatar
Soontir C'boath
SG-14: Fuck the Medic!
Posts: 6817
Joined: 2002-07-06 12:15am
Location: Queens, NYC I DON'T FUCKING CARE IF MANHATTEN IS CONSIDERED NYC!! I'M IN IT ASSHOLE!!!
Contact:

Post by Soontir C'boath »

Darth Wong wrote:Isn't it cheating to get people to help you with your programming homework?
Information such as from Pu-239's would count as cheating since he basically gave me the darn thing but hints on where to go next is fine because I'd still have to figure out how to implement the code.
I have almost reached the regrettable conclusion that the Negro's great stumbling block in his stride toward freedom is not the White Citizen's Counciler or the Ku Klux Klanner, but the white moderate, who is more devoted to "order" than to justice; who constantly says: "I agree with you in the goal you seek, but I cannot agree with your methods of direct action"; who paternalistically believes he can set the timetable for another man's freedom; who lives by a mythical concept of time and who constantly advises the Negro to wait for a "more convenient season."
User avatar
Beowulf
The Patrician
Posts: 10619
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

Darth Wong wrote:Isn't it cheating to get people to help you with your programming homework?
Only if they write the damn thing for you. Giving design hints helps, but still requires the programmer to figure out how to write it. It's like someone being stumped on their physics homework, and telling them "Oh, use the Lorentz transformation." I've always tried to only give hints. Rule of thumb: if you see actual code, it's probably too much help.

---

Oh, and my solution is identical to IB's solution. I'm disclaiming trying to stringify, then integerize, add, then undo. It's too complicated, and there's cases where it won't work (big integers)
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Jaepheth
Jedi Master
Posts: 1055
Joined: 2004-03-18 02:13am
Location: between epsilon and zero

Post by Jaepheth »

I'd just add them component wise and backward (i start at 5 i-- until 1). just like you learn to add in grade school. then just add the integer arrays mod 10 into your sum array, and if it's >=10 then add 1 to sum(i-1)
Children of the Ancients
I'm sorry, but the number you have dialed is imaginary. Please rotate the phone by 90 degrees and try again.
User avatar
Durandal
Bile-Driven Hate Machine
Posts: 17927
Joined: 2002-07-03 06:26pm
Location: Silicon Valley, CA
Contact:

Post by Durandal »

Just remember, in C, things are bytes. You can't cast an array down to an integer and have it just work, because all you're doing is taking a block of bytes in the array and saying "Okay, I want these bytes to be an integer now". (In the case of a stack-allocated array, you'll be treating the least-significant bytes as an integer, so the last sizeof(int) bytes of the array's space get stuffed into an integer.)

You can do stuff like that in Perl or any number of interpreted languages though because they're very weakly typed. But this is C, and bytes are bytes are bytes.
Damien Sorresso

"Ever see what them computa bitchez do to numbas? It ain't natural. Numbas ain't supposed to be code, they supposed to quantify shit."
- The Onion
User avatar
Coalition
Jedi Master
Posts: 1237
Joined: 2002-09-13 11:46am
Contact:

Post by Coalition »

I relooked at my pseudocode, and you might want to doublecheck your program by running it a few times. From the looks of it, my code would add 52478 to 36211 and get 886890.

Still, if you do it correctly, it should make no difference adding left to right, or right to left. That would be a fun stunt to show the teacher, adding left to right (i.e. the ten-thousands place, then the thousands, etc).
User avatar
Braedley
Jedi Council Member
Posts: 1716
Joined: 2005-03-22 03:28pm
Location: Ida Galaxy
Contact:

Post by Braedley »

I have a feeling the intention of this exercise is to use the modulus operator. Although probably not the simplest solution, it feels like the most elegant to me. Goes something like this:

enter values into arrays
convert arrays into single numbers
add numbers into temp_variable
i=0
while(temp_variable != 0){
result=temp_variable mod 10
temp_variable=temp_variable/10
i++
}
reverse result array
Image
My brother and sister-in-law: "Do you know where milk comes from?"
My niece: "Yeah, from the fridge!"
User avatar
Soontir C'boath
SG-14: Fuck the Medic!
Posts: 6817
Joined: 2002-07-06 12:15am
Location: Queens, NYC I DON'T FUCKING CARE IF MANHATTEN IS CONSIDERED NYC!! I'M IN IT ASSHOLE!!!
Contact:

Post by Soontir C'boath »

Thanks for all the help on that problem.

Now I have another and it's pissing me off!

Basically, I have a two dimensional array consisting of zeros and ones. All the zeros stay zero. Ones that do not have a zero adjacent to it turns into a zero while those that do have zeros adjacent stays as ones.

The before and after looks like this.

Code: Select all

0 0 0 0 0 0 0 => 0 0 0 0 0 0 0
0 0 1 1 1 0 0 => 0 0 1 1 1 0 0
0 1 1 1 1 1 0 => 0 1 0 0 0 1 0
0 0 1 1 1 0 0 => 0 0 1 1 1 0 0
0 0 0 0 0 0 0 => 0 0 0 0 0 0 0
My problem is, my code converts every single "1" into "0" even though the if-else statements should get it to print them correctly.

My friend did it a different way where he multiply the adjacent values but that hasn't worked for him either.

I have a feeling it's definitely something intrinsic about C#/++ that I don't know about. Arg!

Code: Select all

/*30/11/07*/

#include "stdio.h"
#include "math.h"

void main()
{	int ray1[5][7]={{0,0,0,0,0,0,0},{0,0,1,1,1,0,0},{0,1,1,1,1,1,0},{0,0,1,1,1,0,0},{0,0,0,0,0,0,0}};
	int ray2[5][7];
	int a, b;
/*line 10*/
for (a=0; a<5; a++)
	{for (b=0;b<7;b++)
		{ ray2[a][b]=0;
		}/*Gives values to ray2[a][b]*/
	}
for (a=1;a<4;a++)
{	for (b=1;b<6;b++)
{	
if (ray1[a][b]=0){
	ray2[a][b]=0; 
	printf("%d\n", ray2[a][b]);}
	else if (ray1[a][b]=1)
		
           { if (ray1[a+1][b]=0){
			ray2[a][b]=ray1[a][b];
			printf("%d\n", ray2[a][b]);
			}
		else if (ray1[a-1][b]=0){
			ray2[a][b]=ray1[a][b];  printf("%d\n", ray2[a][b]);}
		
                else if (ray1[a][b-1]=0){
			ray2[a][b]=ray1[a][b];
				printf("%d\n", ray2[a][b]);}
		else if (ray1[a][b+1]=0)
		{
			ray2[a][b]=ray1[a][b];
			printf("%d\n", ray2[a][b]);}
		
               else ray2[a][b]=0; 
		printf("%d\n", ray2[a][b]);}
		else ray2[a][b]=0; printf("%d\n", ray2[a][b]);
	}
}

/*for (a=0;a<5;a++)
{for(b=0;b<7;b++){
	printf("%d", ray2[a][b]);}
	printf("\n");}*/


}
Edit: Removed my name and ID number from the code.
Last edited by Soontir C'boath on 2007-11-30 09:11pm, edited 1 time in total.
I have almost reached the regrettable conclusion that the Negro's great stumbling block in his stride toward freedom is not the White Citizen's Counciler or the Ku Klux Klanner, but the white moderate, who is more devoted to "order" than to justice; who constantly says: "I agree with you in the goal you seek, but I cannot agree with your methods of direct action"; who paternalistically believes he can set the timetable for another man's freedom; who lives by a mythical concept of time and who constantly advises the Negro to wait for a "more convenient season."
User avatar
Beowulf
The Patrician
Posts: 10619
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

You're going to whack yourself for this:
= != ==
Get it?
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Soontir C'boath
SG-14: Fuck the Medic!
Posts: 6817
Joined: 2002-07-06 12:15am
Location: Queens, NYC I DON'T FUCKING CARE IF MANHATTEN IS CONSIDERED NYC!! I'M IN IT ASSHOLE!!!
Contact:

Post by Soontir C'boath »

Beowulf wrote:You're going to whack yourself for this:
= != ==
Get it?
Actually, I had done that. It gave me warnings that it was redundant. Even then, I am still getting zeros...
I have almost reached the regrettable conclusion that the Negro's great stumbling block in his stride toward freedom is not the White Citizen's Counciler or the Ku Klux Klanner, but the white moderate, who is more devoted to "order" than to justice; who constantly says: "I agree with you in the goal you seek, but I cannot agree with your methods of direct action"; who paternalistically believes he can set the timetable for another man's freedom; who lives by a mythical concept of time and who constantly advises the Negro to wait for a "more convenient season."
User avatar
Beowulf
The Patrician
Posts: 10619
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

Soontir C'boath wrote:
Beowulf wrote:You're going to whack yourself for this:
= != ==
Get it?
Actually, I had done that. It gave me warnings that it was redundant. Even then, I am still getting zeros...
I tried it on my machine, and got the correct answer. If you use "=" in a comparison, it will still set the left side to the value of the right side, then use that value to determine true/falseness. If the value on the right is 0, then the left side will be set to 0, and then the condition will be false.
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Soontir C'boath
SG-14: Fuck the Medic!
Posts: 6817
Joined: 2002-07-06 12:15am
Location: Queens, NYC I DON'T FUCKING CARE IF MANHATTEN IS CONSIDERED NYC!! I'M IN IT ASSHOLE!!!
Contact:

Post by Soontir C'boath »

Oh, in the comparison! Yes, it works now!

God, I hate it when it's just things as simple as that fucks up the program.

I do want to whack myself now. I spent at least an hour combing it over and even changing the code around to see if it'll work. :banghead:

Thanks, Beowulf.
I have almost reached the regrettable conclusion that the Negro's great stumbling block in his stride toward freedom is not the White Citizen's Counciler or the Ku Klux Klanner, but the white moderate, who is more devoted to "order" than to justice; who constantly says: "I agree with you in the goal you seek, but I cannot agree with your methods of direct action"; who paternalistically believes he can set the timetable for another man's freedom; who lives by a mythical concept of time and who constantly advises the Negro to wait for a "more convenient season."
User avatar
Beowulf
The Patrician
Posts: 10619
Joined: 2002-07-04 01:18am
Location: 32ULV

Post by Beowulf »

Sometimes single stepping through the function will be the best thing you can do.
"preemptive killing of cops might not be such a bad idea from a personal saftey[sic] standpoint..." --Keevan Colton
"There's a word for bias you can't see: Yours." -- William Saletan
User avatar
Sarevok
The Fearless One
Posts: 10681
Joined: 2002-12-24 07:29am
Location: The Covenants last and final line of defense

Post by Sarevok »

A general C++ question regarding what Destructionator has been saying...

Does it make you a bad programmer if you are debugging the same code a lot more than witting new code ?

Is good programming really 90 % debugging and 10 % typing ?
I have to tell you something everything I wrote above is a lie.
User avatar
Durandal
Bile-Driven Hate Machine
Posts: 17927
Joined: 2002-07-03 06:26pm
Location: Silicon Valley, CA
Contact:

Post by Durandal »

Sarevok wrote:A general C++ question regarding what Destructionator has been saying...

Does it make you a bad programmer if you are debugging the same code a lot more than witting new code ?

Is good programming really 90 % debugging and 10 % typing ?
Generally, no. 90/10 might be a bit high, but the lion's share of time writing software is spent debugging. That's a general rule for any language. But C++ is a special case in that it's a god-awful language, so a 90/10 ration would be understandable.
Damien Sorresso

"Ever see what them computa bitchez do to numbas? It ain't natural. Numbas ain't supposed to be code, they supposed to quantify shit."
- The Onion
User avatar
phongn
Rebel Leader
Posts: 18487
Joined: 2002-07-03 11:11pm

Post by phongn »

Normally about 10-20% of a software engineer's time is spend actually writing code, the rest in testing, debugging, planning, etc.
User avatar
HRogge
Jedi Master
Posts: 1190
Joined: 2002-07-14 11:34am
Contact:

Post by HRogge »

You need 90% of your time to write your code... and then 90% of your time to debug it.
Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
---------
Honorary member of the Rhodanites
darthbob88
Jedi Knight
Posts: 884
Joined: 2006-11-14 03:48pm
Location: The Boonies

Post by darthbob88 »

HRogge wrote:You need 90% of your time to write your code... and then 90% of your time to debug it.
The old 90-90 rule? I've understood it to be the case that debugging code is twice as difficult as writing it. So, if you write your code to the best of your abilities, you are not smart enough to debug it.
This message approved by the sages Anon and Ibid.
Any views expressed herein are my own unless otherwise noted, and very likely wrong.
I shave with Occam's Razor.
Post Reply