Thanks for all helped me before. But I still have some questions about the program. How to generate a new random number while the new random number is equal to the previous random number? Also how to transpose the matrix?
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
int _tmain(int argc, _TCHAR* argv[])
{
int num2 = 0;
int num=0, i, j;
int mtx[9][9] = {0};
while (num < 3 || num > 9) {
printf("Enter an integer (3-9): ");
scanf("%d", &num);
}
do
{
srand(time(NULL));
switch (num)
{
case 3: num2 = rand() % 8;
break;
case 4: num2 = rand() % 15;
break;
case 5: num2 = rand() % 24;
break;
case 6: num2 = rand() % 35;
break;
case 7: num2 = rand() % 48;
break;
case 8: num2 = rand() % 63;
break;
case 9: num2 = rand() % 80;
break;
}
for (i=0; i < num; ++i)
for (j=0; j < num; ++j)
mtx[i][j] = num2;
}
while ( num2 == num2);
for (i=0; i < num; ++i) {
for (j=0; j < num; ++j)
printf("%i ", mtx[i][j]);
printf("\n");
}
return 0;
}
Update:
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
int _tmain(int argc, _TCHAR* argv[])
{
int prevNum2 = 0;
int num2 = 0;
int num = 0, i, j; // Added initializers and loop counters
int mtx[9][9] = {0}; // Reserve enough space for the worst-case scenario
while (num < 3 || num > 9) { // Added input validation loop
printf("Enter an integer (3-9): ");
scanf("%d", &num);
}
srand(time(NULL));
do{
prevNum2 =num2;
switch (num)
{
case 3: num2 = rand() % 8;
break;
case 4: num2 = rand() % 15;
break;
case 5: num2 = rand() % 24;
break;
case 6: num2 = rand() % 35;
break;
case 7: num2 = rand() % 48;
break;
case 8: num2 = rand() % 63;
break;
case 9: num2 = rand() % 80;
break;
}
// Loop through the matrix elements we want, filling each with a random number
for (i=0; i < num; ++i)
for (j=0; j < num; ++j)
mtx[i][j] = num2;
}
while (num2 == prevNum2);
/* Do something with the matrix here (display it, etc) */
for (i=0; i < num; ++i) {
for (j=0; j < num; ++j)
printf("%i ", mtx[i][j]);
printf("\n");
}
return 0;
}