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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alireza6485
    New Member
    • Jan 2009
    • 19

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

    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:( )
    [code=c#]
    using System;
    public class YourName
    {
    public static void Main(string[] arg)
    {
    Console.WriteLi ne("Enter the word you want to be Encoded?");
    string name = Console.ReadLin e();
    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' };
    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' };
    char[] lastArray = encode;
    int len = name.Length;
    Console.Write(" Encoded word :");
    for (int i = 0; i < len; i++)
    {
    for (int j = 0; j < 26; j++)
    {
    if (name[i] == original[j])
    {
    Console.Write(e ncode[j]);
    encode[j] = lastArray[i];
    }
    }
    }
    Console.WriteLi ne();
    for (int m = 0; m < len; m++)
    {
    for (int n = 0; n < 26; n++)
    {
    if (lastArray[m] == encode[n])
    {
    Console.Write(o riginal[n]);
    }
    }
    }
    }
    }
    [/code]
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    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

    Comment

    Working...