科目名稱:C++
Programming |
開課系所:
Dept. of CSIE |
考試日期 | 2014.3.26 | ||
系所別: |
年級: |
學號: |
姓名: |
考試時間 | 18:10-20:00 |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 |
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Magic Square
// Increment Operator (P.74)
#include <iostream>
using std::cout;
int main()
{
const int N = 5;
int a[N][N] = { 0 };
int i = N / 2, j = 0;
for (int k=1; k <= N * N; k++)
{
a[i][j] = k;
if (( i > 0 && j > 0 && a[i-1][j-1] > 0) || (i==0 && j == 0) ) ++j;
else
{
if (--i < 0) i += N;
if (--j < 0) j += N;
}
}
for (i=0; i<N; i++)
{
for (j=0; j<N; j++)
cout << a[i][j] << '\t';
cout << std::endl;
}
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Substitution Cipher
#include <iostream>
int main()
{
char ciphertext[] = "DNAURUISVROPSQY";
char password[] = "NETHERLANDS";
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char mapping[26];
char reverse[26];
char c;
unsigned short i, j, k;
for (k=0, i=0; (c=password[i]) != '\0'; i++) // Preparing the mapping table
{
if (alphabet[ c - 'A' ] != 0)
{
mapping[k++] = c;
alphabet[ c - 'A' ] = 0;
}
}
for (j=0; k<26; )
{
while (alphabet[j] == 0) j++;
mapping[k++] = alphabet[j++];
}
// mapping[k] = '\0';
// std::cout << "DEBUG - " << mapping << std::endl;
for (i=0; i<26; i++)
reverse[ mapping[i] - 'A' ] = 'A' + i;
for (i=0; (c=ciphertext[i]) != '\0'; i++)
std::cout << reverse[ c - 'A' ];
std::cout << std::endl;
return 0;
}
// Transposition Cipher
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
int main()
{
const unsigned short N = 3;
char matrix[N * N + 1];
char plaintext[] = "Wtoh eads amVdilir t Piwunanntte? xA";
char ciphertext[ sizeof(plaintext) ];
char *p = plaintext;
unsigned i, j;
while (p < plaintext + strlen(plaintext) )
{
for (i=0; i<N; i++)
for (j=0; j<N; j++)
{
matrix[i*N + j] = *p ? *p : 'A';
++p;
}
for (j=0; j<N; j++)
for (i=0; i<N; i++)
cout << matrix[i*N + j];
}
cout << endl;
return 0;
}