#include <stdio.
h>
#include <string.h>
#include <stdbool.h>
int main() {
char plaintext[100], ciphertext[100], decrypted[100];
int rails;
printf("Enter the plaintext (no spaces): ");
scanf("%s", plaintext);
printf("Enter number of rails (>=2): ");
scanf("%d", &rails);
if (rails < 2) {
printf("Number of rails must be at least 2.\n");
return 1;
int len = strlen(plaintext);
char rail[rails][len];
// Initialize the matrix with '\n'
for (int i = 0; i < rails; i++)
for (int j = 0; j < len; j++)
rail[i][j] = '\n';
// Fill matrix in a zigzag manner
int row = 0;
bool down = true;
for (int i = 0; i < len; i++) {
rail[row][i] = plaintext[i];
if (row == 0)
down = true;
else if (row == rails - 1)
down = false;
row += down ? 1 : -1;
// Read the matrix row by row to get ciphertext
int index = 0;
for (int i = 0; i < rails; i++)
for (int j = 0; j < len; j++)
if (rail[i][j] != '\n')
ciphertext[index++] = rail[i][j];
ciphertext[index] = '\0';
printf("Encrypted Text: %s\n", ciphertext);
// Decryption
// Step 1: Fill placeholders ('*') in zigzag pattern
for (int i = 0; i < rails; i++)
for (int j = 0; j < len; j++)
rail[i][j] = '\n';
row = 0;
down = true;
for (int i = 0; i < len; i++) {
rail[row][i] = '*';
if (row == 0)
down = true;
else if (row == rails - 1)
down = false;
row += down ? 1 : -1;
// Step 2: Replace '*' with ciphertext characters row by row
index = 0;
for (int i = 0; i < rails; i++)
for (int j = 0; j < len; j++)
if (rail[i][j] == '*' && index < len)
rail[i][j] = ciphertext[index++];
// Step 3: Read in zigzag order to get decrypted text
row = 0;
down = true;
index = 0;
for (int i = 0; i < len; i++) {
decrypted[index++] = rail[row][i];
if (row == 0)
down = true;
else if (row == rails - 1)
down = false;
row += down ? 1 : -1;
decrypted[index] = '\0';
printf("Decrypted Text: %s\n", decrypted);
return 0;