Study this -> A development process
Then this.
Code:
#include <stdio.h>
#include <string.h>
// Use a fixed sized array to test with before
// adding complications with variable sizes
#define M_ROWS 50
#define M_COLS 10
char *transpose(char *message, char *key);
int main()
{
char sentence[100]="Tqkofeibnx-cr--hu-wo";
char key[100]="jump";
transpose(sentence, key);
/* how it should be read into a matrix(the key is not read into the matrix):
J M P U
T e - h
q i c u
k b r -
o n - w
f x - o
how it should be arranged
J U M P
T h e -
q u i c
k - b r
o w n -
f o x -
then read row by row
*/
return 0;
}
void fill(char matrix[][M_COLS], const char *message, int col_len, int row_len) {
int k=0;
for(int c=0;c<col_len;c++)
{
for(int r=0;r<row_len;r++)
{
matrix[r][c]= message[k++];
}
}
}
void pad(char matrix[][M_COLS], int col_len, int row_len) {
for(int c=0;c<col_len;c++)
{
for(int r=0;r<row_len;r++)
{
if(matrix[r][c]=='-'||matrix[r][c]=='\0')
{
matrix[r][c]=' ';
}
}
}
}
void print(const char matrix[][M_COLS], int col_len, int row_len) {
for(int r=0;r<row_len;r++)
{
for(int c=0;c<col_len;c++)
{
printf("%c ",matrix[r][c]);
}
printf("\n");
}
printf("-----\n");
}
void swap(char matrix[][M_COLS], int row_len, int col1, int col2) {
for(int r=0;r<row_len;r++) {
char temp = matrix[r][col1];
matrix[r][col1] = matrix[r][col2];
matrix[r][col2] = temp;
}
}
char *transpose(char *message, char *key)
{
int message_len=strlen(message);
//column len
int col_len=strlen(key);
//give us the number of rows
int row_len =message_len/col_len;
if(message_len%col_len)
{
row_len++;//increments row_len
}
char matrix[M_ROWS][M_COLS] = { { 0 } };
//creat matrix
fill(matrix, message, col_len, row_len);
//remove padding
pad(matrix, col_len, row_len);
//print matrix above
print(matrix, col_len, row_len);
//columnuar transpose
swap(matrix, row_len, 1, 3);
print(matrix, col_len, row_len);
swap(matrix, row_len, 2, 3);
print(matrix, col_len, row_len);
}
$ gcc foo.c
$ ./a.out
T e h
q i c u
k b r
o n w
f x o
-----
T h e
q u c i
k r b
o w n
f o x
-----
T h e
q u i c
k b r
o w n
f o x
-----