Build arrays A & B, add values in both, and display in array C

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 10163 Views - Last Post: 28 October 2007 - 07:30 AM Rate Topic: -----

#16 Binary_Ninja  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 24-October 07

Re: Build arrays A & B, add values in both, and display in array C

Posted 27 October 2007 - 09:11 AM

Option 1, should keep me bussy for a little while, I will go try it.Thanx mate
Was This Post Helpful? 0
  • +
  • -

#17 CrazyJ  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 51
  • Joined: 15-October 07

Re: Build arrays A & B, add values in both, and display in array C

Posted 27 October 2007 - 12:18 PM

Hi, thanks so much for the reply! Had it only come a little earlier :^: ! But I finally scoped out these issues that you covered, and got the program running successfully. I am new to C#, and programming in general except for QBasic, so it was a great "AHA!" moment for me to realize that arrayA and arrayB were allocated, but were not actually being filled with the values :blink: ! Thanks again, you guys are so helpful. Perhaps one day, through many long hours of discovery, I will also be able to help on this forum!

CrazyJ

View Postguahguahmonster, on 26 Oct, 2007 - 07:56 PM, said:

A crucial problem you shall have to address here is the length of the arrays and what to do if they are not equal. If Array A has 8 elements and Array B has only 7, arrayC[7] = arrayA[7] + arrayB[7]; won't make you happy. I notice you have defined behavior that if one array is longer, the longer values are kept on the end of the array. Ok.

I would write code to find which array is longer, then copy it to another array. Then, loop through elements of the shorter array and add them one by one to the corresponding element of the longer array.

How's that sound?

-----

Please also note the following code that you posted:
			Console.WriteLine("Array A: ");
			ii = 0;
			while (ii < m)
		   {
				randomDigit = randomNumber.Next(minValue, maxValue);
				Console.Write(randomDigit + " ");

			ii++;

			}  // while
//		  ===========
			Console.WriteLine();
//		  ====================
			Console.WriteLine("Array B: ");
			jj = 0;
			while (jj < n)
			{
				randomDigit = randomNumber.Next(minValue, maxValue);
				Console.Write(randomDigit + " ");

				jj++;

			}  // while



To me, it looked you wanted to set those values in Array A and B, but this is ineffective, for you do not set these values in array A nor B. In fact, you do not even HAVE an array A or B. Sure, your inputA and inputB methods return an int array, but you do not assign anything to the return value, so it just gets lost in nowhere. In addition, that code probably won't run because you did not declare the type of randomDigit (And while I'm here, why is it a randomDigit? what if minValue=10 and maxValue=99? Then they're not digits...)



I finally got it to work! Although I feel like it was accomplished through some messy hacks that I discovered would make it work. Perhaps you can take a look and tell me what you would have done differently for future reference?
using System;
using System.Collections.Generic;
using System.Text;

namespace SumArrays_3
{
	class Program
	{
		static void Main(string[] args)
		{
			int m;
			int n;
			int [] arrayA;
			int [] arrayB;
			string numString;

			Console.WriteLine("This program will accept input from the user which will ");
			Console.WriteLine("be used to build 2 arrays.");
			Console.WriteLine();
			Console.WriteLine("The 1st integer entered will determine the number of");
			Console.WriteLine("elements in array A.");
			Console.WriteLine();
			Console.WriteLine("The 2nd integer entered will determine the number of");
			Console.WriteLine("elements in array B.");
			Console.WriteLine();
			Console.WriteLine("A Minimum and a Maximum number must then be entered");
			Console.WriteLine("signifying the range of random numbers used to fill");
			Console.WriteLine("arrays A and B.");
			Console.WriteLine();
			Console.WriteLine("===============================================");
			Console.WriteLine("Array C will display the sum of arrays A and B.");
			Console.WriteLine("===============================================");
			Console.WriteLine();
//		  ===================
			arrayA = MyMethods.InputA(out m);
			arrayB = MyMethods.InputB(out n);
			
//		  ====================
			int ii;
			int jj;
			int randomDigit;
//		  ==========================
			Random randomNumber = new Random();
//		  ===================================
			Console.WriteLine("Enter the minimum number: ");
			numString = Console.ReadLine();
			int minValue = int.Parse(numString);
//		  ====================================
			Console.WriteLine("Enter the maximum number: ");
			numString = System.Console.ReadLine();
			int maxValue = int.Parse(numString);
			Console.WriteLine();
//		  ====================

			Console.WriteLine("Array A: ");
			ii = 0;
			while (ii < m)
			{
				randomDigit = randomNumber.Next(minValue, maxValue);
				arrayA[ii] = randomDigit;
				Console.Write(randomDigit + " ");

				ii++;

			}  // while
//		  ====================
			Console.WriteLine();
//		  ====================
			Console.WriteLine("Array B: ");
			jj = 0;
			while (jj < n)
			{
				randomDigit = randomNumber.Next(minValue, maxValue);
				arrayB[jj] = randomDigit;
				Console.Write(randomDigit + " ");

				jj++;

			}  // while

			Console.WriteLine();

			MyMethods.ArrayC(m, n, arrayA, arrayB);

//		  ===========
			Console.ReadLine();
//		  ===================
		 
		}// Main 
//	  ========
	}//class Program
//  ================
}// namespace SumArrays_3


using System;
using System.Collections.Generic;
using System.Text;

namespace SumArrays_3
{
	class MyMethods
	{
	
		public static int[] InputA(out int m)
		{
			Console.Write("Please enter the size for Array A: ");
			m = int.Parse(Console.ReadLine());
			int[] arrayA = new int[m];
			Console.WriteLine();
			return arrayA;
			
		}// method InputA
//	  =================

		public static int[] InputB(out int n)
		{
			 Console.WriteLine("Please enter the size for Array B: ");
			 n = int.Parse(Console.ReadLine());
			 int[] arrayB = new int[n];
			 Console.WriteLine();
			 return arrayB;

		}// method InputB
//	  =================
		public static void ArrayC(int m, int n, int[] arrayA, int[] arrayB)
		{
			int large;
			if (n > m)
			{
				large = n;

			}
			else
			{
				large = m;
			}


			int[] arrayC = new int[large];
//		  ==============================
			if (m == large)
			{

				for (int ii = 0; ii < n; ii++)
					arrayC[ii] = arrayA[ii] + arrayB[ii];


				for (int ii = n; ii < large; ii++)
					arrayC[ii] = arrayA[ii];
			}
			else
			{

				for (int ii = 0; ii < m; ii++)
					arrayC[ii] = arrayA[ii] + arrayB[ii];


				for (int ii = m; ii < large; ii++)
					arrayC[ii] = arrayB[ii];

				Console.WriteLine("Array C: ");
				for (int ii = 0; ii < large; ii++)
				Console.Write(arrayC[ii] + " ");
				Console.WriteLine();
			}	   
		}
		
	}//class MyMethods
//  ==================
}// namespace SumArrays_3




Thanks so much! :D

CrazyJ

View Postbaavgai, on 27 Oct, 2007 - 04:36 AM, said:

You still not done with this? Please, post when you get it, I'm curious. There aren't enough C# posts, anyway. ;)

A foreach is a complete red herring, ignore it. You shouldn't use one in any form of solution for this problem.

With the code I posted before, you're about ten lines away from solution. The fundamental problem is understanding arrays and loops.

I answered the first part of the problem, arrays filled with random numbers of a given length. guahguahmonster gave an overview of the second part, filling a third array by combining the values of two others.

Another hint, initializing arrayC should look something like:
int [] arrayC = new int[(arrayA.Length()>arrayB.Length()) ? arrayA.Length() : arrayB.Length()];


Ok, that's probably overly quirky syntax; figure out better. So, where are you stuck?

Was This Post Helpful? 0
  • +
  • -

#18 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5944
  • View blog
  • Posts: 12,874
  • Joined: 16-October 07

Re: Build arrays A & B, add values in both, and display in array C

Posted 27 October 2007 - 03:54 PM

Excellent job, CrazyJ. I'm glad you got it.

To be fair, I'll offer my solution, with the reasoning behind it and comments relating to your project. With the hope it will make your next project easier. ;)

Ultimately, you are collecting four pieces of information from the user. For testing, we'll assume you already have those pieces and are ready to work. How many times did you type at the console for this program? Yeah, not the fun part. You avoid it by making a method that you can plug numbers into. When you get to accepting user input, you just plug in what they supply.

public void DisplayResults(int sizeA, int sizeB, int valueMin, int valueMax) {
	int [] arrayA = GetRandomFilledArray(sizeA, valueMax, valueMin);
	int [] arrayB = GetRandomFilledArray(sizeB, valueMax, valueMin);
	int [] arrayC = GetMergedArray(arrayA, arrayB);
	DisplayArray("Array A: ", arrayA);
	DisplayArray("Array B: ", arrayB);
	DisplayArray("Array C: ", arrayC);
}



This is the final call, DisplayResults. I've offered one of the methods, GetRandomFilledArray. Obviously I need to write a couple more. A note here on using out in C#; dont. There is never a reason to use out. It will get you into bad habits. I've never had to use it. Why is it there? Blame C programmers.

I'm going to skip GetMergedArray, the heart of the problem, for the moment. On to DisplayArray

private void DisplayArray(string label, int[] array) {
	Console.Write(label);
	for (int i = 0; i < array.Length; i++) {
		Console.Write(array[i] + " ");
	}
	Console.WriteLine();
}



Yes, it's simple. You did the same thing. But look again how it's used. Rather than rewriting code like this for each of my three arrays, it's used once. If I screw the code up, I screw it up in one place.

And now, the big one, GetMergedArray.
private int [] GetMergedArray(int [] arrayA, int [] arrayB) {
	int [] arrayLarge;
	int [] arraySmall;

	if (arrayA.Length > arrayB.Length) {
		arrayLarge = arrayA;
		arraySmall = arrayB;
	} else {
		arrayLarge = arrayB;
		arraySmall = arrayA;
	}

	int [] arrayOut = new int[arrayLarge.Length];

	for(int i=0; i<arraySmall.Length; i++) {
		arrayOut[i] = arraySmall[i] + arrayLarge[i];
	}

	for(int i=arraySmall.Length; i<arrayLarge.Length; i++) {
		arrayOut[i] = arrayLarge[i];
	}
	return arrayOut;
}


You also did a similar thing. However, note that by placing this code in a method we isolated it from the rest of our logic and make it easy to change.

That's basically the whole answer. However, if you're saying, "Yeah, sure, but I had to take user input." I wrote a user input example to. It's included in the full example and called GetUserInput


using System;

class BaavgaiArrayTestMethods {
	private int [] GetRandomFilledArray(int arraySize, int valueMax, int valueMin) {
		int valueRange = valueMax - valueMin;
		Random rnd = new Random();
		int [] newArray = new int[arraySize];
		for(int i=0; i<arraySize; i++) {
			newArray[i] = rnd.Next(valueRange) + valueMin;
		}
		return newArray;
	}

	private int [] GetMergedArray(int [] arrayA, int [] arrayB) {
		int [] arrayLarge;
		int [] arraySmall;
		
		if (arrayA.Length > arrayB.Length) {
			arrayLarge = arrayA;
			arraySmall = arrayB;
		} else {
			arrayLarge = arrayB;
			arraySmall = arrayA;
		}
		
		int [] arrayOut = new int[arrayLarge.Length];
		
		for(int i=0; i<arraySmall.Length; i++) {
			arrayOut[i] = arraySmall[i] + arrayLarge[i];
		}
		
		for(int i=arraySmall.Length; i<arrayLarge.Length; i++) {
			arrayOut[i] = arrayLarge[i];
		}
		
		return arrayOut;
	}
	
	private void DisplayArray(string label, int[] array) {
		Console.Write(label);
		for (int i = 0; i < array.Length; i++) {
			Console.Write(array[i] + " ");
		}
		Console.WriteLine();
	}


	public void DisplayResults(int sizeA, int sizeB, int valueMin, int valueMax) {
		int [] arrayA = GetRandomFilledArray(sizeA, valueMax, valueMin);
		int [] arrayB = GetRandomFilledArray(sizeB, valueMax, valueMin);
		int [] arrayC = GetMergedArray(arrayA, arrayB);
		DisplayArray("Array A: ", arrayA);
		DisplayArray("Array B: ", arrayB);
		DisplayArray("Array C: ", arrayC);
	}
	

	private int GetIntFromUser(string label) {
		Console.Write(label);
		int n = int.Parse(Console.ReadLine());
		Console.WriteLine();
		return n;
	}
	
	public void GetUserInput() {
		int sizeA = this.GetIntFromUser("Please enter the size for Array A: ");
		int sizeB = this.GetIntFromUser("Please enter the size for Array B: ");
		int valueMin = this.GetIntFromUser("Enter the minimum number: ");
		int valueMax = this.GetIntFromUser("Enter the maximum number: ");
		this.DisplayResults(sizeA, sizeB, valueMax, valueMin);
	}

	static void Main(string[] args) {   	
		BaavgaiArrayTestMethods arrayManager = new BaavgaiArrayTestMethods();
		arrayManager.DisplayResults(7,10,1,10);
	}

}



Again, in GetUserInput, note how using another method, GetIntFromUser allows less code to be written and the logic of what's going on to be clear.

Hopefully some of this advise does help and I didn't come off as a know it all twit. ;) Best of luck with the next project.
Was This Post Helpful? 0
  • +
  • -

#19 gogole  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 17-July 07

Re: Build arrays A & B, add values in both, and display in array C

Posted 28 October 2007 - 07:30 AM

having trouble adding the values in array A and B and storing them in array C eh?.things would have been much easier if they all had the same length.this code should solve your problem (i think) ,i have not tested it yet (didn't have time) .hope it works or inspires you to write better code.
 AddArrays(int array1,int array2)
{ 
  
  int arrLength1 = array1.length;
  int arrLength2 = array2.length;
  int maxLength,min;
  if(arrLength1-arrLength2 < 0)
   {
	maxLength = arrLength2;
	min = arrLength1;
   }
  else
   {
	maxLength = arrLength1;
	min = arrLength2;
   }
   int [] array3 = new int [maxLength];
   int i = 0;
   while(i < min)
   {
	array3[i] = array1[i] +array2[i];
	++i;
   }
   int j = 1;
   if(maxLength == arrLength1)
   {
	int arr3Add = min +j;
	while(arr3Add < maxLength)
	  {
	   array3[arr3Add] = array1[arr3Add];
	   ++arr3Add;
	  }
   }
   if(maxLength == arrLength2)
   {
	int arr3Add = min +j;
	while(arr3Add < maxLength)
	  {
	   array3[arr3Add] = array2[arr3Add];
	   ++arr3Add;
	  }
   }   
	 return array3;
}  


This post has been edited by gogole: 28 October 2007 - 07:33 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2