Sue Hak Sengh
Sue Hak Sengh

Reputation: 11

C- programming array assignment issues

I am doing this program for an assignment. The code is to decrypt a ciphertext based on the frequency of letters in the text. The problem arises when I am trying to change the ciphertext letter to its plaintext letter. For some reason the ciphertext letter is changed to a random letter.

I tried to see what was wrong so I added print statement to the code that does the swap. I noticed that for each letter, the code swaps it two times before making its last assignment. here is a snippet of the code:

//decryption
for (j = 0, k = strlen(cipher); j < k; j++) {


    for (c = 0 ; c < 26; c++){


       if (cipher[j] == freqCounts[c].letter){//checks if the ciphertext letters match

              //use the following line of code to see how the swap is being handled
               /* 
               printf("f[%d] = %c and c[%d] =  %c\n", c, freqCounts[c].pletter, j, cipher[j]);
               */
        cipher[j] = freqCounts[c].pletter;//swaps with plaintext letter here

           }
        }
   }

Could you please provide with some insight as to why it's making the additional swaps per letter.

Upvotes: 0

Views: 62

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Suppose that freqCounts[0].letter=='a', freqCountes[0].pletter=='b', freqCountes[1].letter=='b'.

In this case, cipher[j] == freqCounts[c].letter becomes true at c=0, and it becomes true again at c=1.

I think adding break; after cipher[j] = freqCounts[c].pletter; may work.

Upvotes: 1

Related Questions