By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 663 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

Help Please...Sub Cipher C#...Arrays and nested for loops

P: 19
I am a C# begginer.I have to write a program that asks the user to enter a word,then it encodes it and after encoding it ,it decodes it again(by using Arrays to make sure that weget the right answer).
my code runs the encoding part ,but the decoding it outputs is not the same as what user enters ,Can you please fix the code for me(I have been working on it for 2 days now ,and no results:( )
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. public class YourName
  3. {
  4.     public static void Main(string[] arg)
  5.     {
  6.         Console.WriteLine("Enter the word you want to be Encoded?");
  7.         string name = Console.ReadLine();
  8.         char[] original ={ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
  9.         char[] encode ={ 't', 'm', 'e', 's', 'f', 'k', 'j', 'a', 'x', 'n', 'o', 'v', 'l', 'u', 'c', 'h', 'z', 'g', 'y', 'b', 'w', 'p', 'd', 'r', 'i', 'q' };
  10.         char[] lastArray = encode;
  11.         int len = name.Length;
  12.         Console.Write("Encoded word  :");
  13.         for (int i = 0; i < len; i++)
  14.         {
  15.             for (int j = 0; j < 26; j++)
  16.             {
  17.                 if (name[i] == original[j])
  18.                 {
  19.                     Console.Write(encode[j]);
  20.                     encode[j] = lastArray[i];
  21.                 }
  22.             }
  23.         }
  24.         Console.WriteLine();
  25.         for (int m = 0; m < len; m++)
  26.         {
  27.             for (int n = 0; n < 26; n++)
  28.             {
  29.                 if (lastArray[m] == encode[n])
  30.                 {
  31.                     Console.Write(original[n]);
  32.                 }
  33.             }
  34.         }
  35.     }
  36. }
  37.  
Feb 12 '09 #1
Share this Question
Share on Google+
1 Reply


Plater
Expert 5K+
P: 7,872
Edit: I take that back, you have all kindsa problems

This line:
encode[j] = lastArray[i];

You are overwriting the value of encode with lastArray, I think you want it the other way around?

This line:
char[] lastArray = encode;
You are not actually creating a new array, you are making lastArray and encode point to the same 26 element character array. If your user typed a word with more then 26 letters, you would get index out of bounds exceptions.
You should create lastArray with the same amount of elements as there are characters in the string name
Feb 12 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.