C - Wrong printed values on a matrix - c

So I created a program that generates a random 4x4 matrix, with values ranging from 0 to 17. Afterwards, it would calculate and print the sum of each rows and columns. The problems are, (1) values of row sums are incorrect, (2) the last element, which is the m[4][4], seems to double in value, giving an incorrect value for the sum of Column 4 as well. Here is the code:
srand(time(NULL));
printf("Generating matrix... ");
getch();
printf("\n\n");
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 4; j++) {
m[i][j] = rand() % 17;
printf("%d\t", m[i][j]);
if (i == 1) { // Calculation of Row Sums
rSum[1] += m[i][j];
} else if (i == 2) {
rSum[2] += m[i][j];
} else if (i == 3) {
rSum[3] += m[i][j];
} else if (i == 4) {
rSum[4] += m[i][j];
}
if (j == 1) { // Calculation of Column Sums
cSum[1] += m[i][j];
} else if (j == 2) {
cSum[2] += m[i][j];
} else if (j == 3) {
cSum[3] += m[i][j];
} else if (j == 4) {
printf("\n");
cSum[4] += m[i][j];
}
}
}
getch();
printf("\n\n");
for (i = 1; i <= 4; i++) { // Printing of Values
printf("Sum of Row %d: %d\n", i, rSum[i]);
printf("Sum of Column %d: %d\n", i, cSum[i]);
printf("-----------------------------------------------\n");
}
return 0;

Arrays are 0 based in C. You should change all your loops to iterate this way:
for (i = 0; i < 4; i++) {
And also change other parts of your code where you use explicit index values. This part can be simplified drastically.
The arrays rSum and cSum must be initialized to 0. Failure to do it might explain the incorrect values computed by your program.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int m[4][4];
int rSum[4] = { 0 };
int cSum[4] = { 0 };
int i, j;
srand(time(NULL));
printf("Generating matrix... ");
getch();
printf("\n\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
m[i][j] = rand() % 17;
printf("%d\t", m[i][j]);
rSum[i] += m[i][j]; // Calculation of Row Sums
cSum[j] += m[i][j]; // Calculation of Column Sums
}
printf("\n");
}
getch();
printf("\n\n");
for (i = 0; i < 4; i++) { // Printing of Values
printf("Sum of Row %d: %d\n", i, rSum[i]);
printf("Sum of Column %d: %d\n", i, cSum[i]);
printf("-----------------------------------------------\n");
}
return 0;
}

Related

I need help for bubble sort in c

How can I display the input user of this code. I am using bubble sort but I cannot display the input.
Here's my code:
#include <stdio.h>
int main(void) {
int array[100];
int count;
for(int i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &array[i]);
if(array[i] == 0) break;
}
int size = sizeof(array) / sizeof(array[0]);
for(int i = 0; i < size - 1; ++i) {
int swapped = 0;
for(int ctr = 0; ctr < size - i - 1; ++ctr) {
if(array[ctr] > array[ctr + 1]) {
int temp = array[ctr];
array[ctr] = array[ctr + 1];
array[ctr + 1] = temp;
swapped = 1;
}
}
if(swapped == 0) {
break;
}
}
printf("[");
for(int i = 0; i < size; i++) {
if(i == size - 1) {
printf("%d", array[i]);
}
else {
printf("%d, ", array[i]);
}
}
printf("]");
return 0;
}
Here's the output:
Enter·number·1:·1
Enter·number·2:·2
Enter·number·3:·3
Enter·number·4:·4
Enter·number·5:·5
Enter·number·6:·0
[1,·2,·3,·4,·5]
I cannot display the 1 2 3 4 5.... How can I display?
The calculation of the size doesn't work like you did it. sizeof(array) will give you the total amount of of bytes of the array (of all 100 spaces). So your size will allway be 100.
Instead of calculating the size it's easyer to count the inputs like this:
int size=0;
for(int i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &array[i]);
if(array[i] == 0) break;
size++;
}
The user can enter i values in the array due to the break statement within the for loop
for(int i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &array[i]);
if(array[i] == 0) break;
}
So you need to keep this value and use it the following for loops because it can differ from the value of the expression sizeof(array) / sizeof(array[0])

How to transpose a matrix without using another matrix?

Write a program which will accept 2-dimensional square matrix and find out the transpose of it.
Program should not make use of another matrix
Hi I am trying to transpose a 2*2 matrix without using another matrix.
Is there anything wrong with my transpose logic?
I am a newbie
#include <stdio.h>
int main()
{
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1); //i+1 so that it can print 1 row, 2 row, 3 row etc
for (j = 0; j < 2; j++) { //loop inside to loop to get value for a[0][0],a[0][1],a[0][2]
scanf("%d", &mat[i][j]);
}
}
printf("The matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
//transpose logic using same matrix
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
printf("The transpose of the matrix is\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}
EDIT: I found an easier way to do it however I still don't understand why my transpose logic by using this
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
cannot get it to transpose.
Below is my corrected answer
#include <stdio.h>
int main()
{
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1);//i+1 so that it can print 1 row, 2 row, 3 row etc
for (j = 0; j < 2; j++) {//loop inside to loop to get value for a[0][0],a[0][1],a[0][2]
scanf("%d", &mat[i][j]);
}
}
printf("The matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
printf("The transpose of the matrix is\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[j][i]);
}
printf("\n");
}
}
Your program is a good attempt, but transposing the matrix is like reversing an array: you must stop half way to avoid swapping the transposed values twice, leading to the original matrix as you observe.
You should stop the inner loop when j == i, hence change the inner loop to:
for (j = 0; j < i; j++) { // j < i instead of j < 2
Here is a modified version:
#include <stdio.h>
int main() {
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1);
for (j = 0; j < 2; j++) {
if (scanf("%d", &mat[i][j]) != 1)
return 1;
}
}
printf("The matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
//transpose logic using same matrix
for (i = 0; i < 2; i++) {
for (j = 0; j < i; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
printf("The transpose of the matrix is:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
return 0;
}
Your corrected answer does not transpose the matrix at all, it merely outputs the transposed matrix. The matrix mat in memory is unchanged.

Finding the highest frequency of an array and all elements which have that frequency

I'm asked to find the highest frequency from an array of elements and all elements with said frequency. My code seem to work just fine but it seems to have a mistake somewhere when i submit it. Can anyone help me find the error?
Format Input:
The first line contains an integer T stating the number of test cases. For each test case, the first line contains a single integer N which indicate the number of element in the array. The next line contains N integers Xi (1≤i≤N) which indicate ith element in the array.
Format Output:
Consists of T lines where each line has the format “Case #X: Y ”, where X is the test case number starting at 1 and Y is the highest frequency. Next line contains all elements which have that frequency sorted in ascending order.
Constraints:
1 ≤ T ≤ 20 | 2 ≤ N ≤ 20.000 | 1 ≤ Xi ≤ 2 × 10^5
Sample Input:
3
8
1 1 2 2 3 4 5 5
8
5 5 4 3 2 2 1 1
4
1 1 1 3
Sample Output:
Case #1: 2
1 2 5
Case #2: 2
1 2 5
Case #3: 3
1
Here is my code:
#include <stdio.h>
int main() {
int T, N[20];
scanf("%d", &T); getchar();
int A[T][20000];
for (int i = 0; i<T; i++) {
scanf("%d", &N[i]); getchar();
for (int j = 0; j<N[i]; j++) {
scanf("%d", &A[i][j]); getchar();
}
int X = 0;
for (int j = 0; j<N[i]; j++) {
for (int k = j + 1; k<N[i]; k++) {
if (A[i][k]<A[i][j]) {
X = A[i][j];
A[i][j] = A[i][k];
A[i][k] = X;
}
}
}
}
int f[20000];
for (int i = 0; i<T; i++) {
int c = 0, mc = 0;
for (int j = 0; j<N[i]; j++) {
c = 1;
if(A[i][j] != -1) {
for (int k = j+1; k<N[i]; k++) {
if (A[i][j] == A[i][k]) {
c++;
A[i][k] = -1;
}
}
f[j]=c;
}
if (c>mc) {
mc = c;
}
}
printf("Case #%d: %d\n", i+1, mc);
for (int j = 0; j<N[i]; j++) {
if (A[i][j] != -1) {
if (f[j] == mc) {
printf ("%d", A[i][j]);
if (j<N[i]-1) {
printf(" ");
}
}
}
}
printf("\n");
}
return 0;
}
EDIT
So I made another code where instead of inputting all arrays at once and outputting everything at once, this code outputs the frequency and elements after i input the first arrays of numbers. But it seems like the code still have problems and i can't find where... P.s I'm pretty new to this, so i apologise for the lack of efficiency of my codes.
NEW CODE
#include <stdio.h>
int main() {
int T, N;
scanf("%d", &T); getchar();
int A[20000];
for (int i = 0; i<T; i++) {
scanf("%d", &N); getchar();
for (int j = 0; j<N; j++) {
scanf("%d", &A[j]); getchar();
}
int X;
for (int j = 0; j<N; j++) {
for (int k = j + 1; k<N; k++) {
if (A[k]<A[j]) {
X = A[j];
A[j] = A[k];
A[k] = X;
}
}
}
int f[N], c = 0, mc = 0;
for (int j = 0; j<N; j++) {
c = 1;
if(A[j] != -1) {
for (int k = j+1; k<N; k++) {
if (A[j] == A[k]) {
c++;
A[k] = -1;
}
}
f[j]=c;
if (c>mc) {
mc = c;
}
}
}
printf("Case #%d: %d\n", i+1, mc);
for (int j = 0; j<N; j++) {
if (A[j] != -1) {
if (f[j] == mc) {
printf ("%d", A[j]);
if (j<N-1) {
printf(" ");
}
}
}
}
printf("\n");
}
return 0;
}
It took me a couple of days but i finally got how to do this. Apparently, it was not as complicated as i thought... here is the working code. Thanks to everyone who helped :)
#include <stdio.h>
int main() {
int T, N;
scanf("%d", &T);
for (int i = 0; i<T; i++) {
scanf("%d", &N); getchar();
//INPUT elements and counting frequncy for each element
int f[200001] = {0}, E = 0;
for (int j = 0; j<N; j++) {
scanf("%d", &E); getchar();
f[E]++;
}
//find max frequency and how many elements with max frequency
int max = 0, c = 0;
for (int j = 1; j<200001; j++) {
if (f[j] == max) {
c ++;
}
if (f[j]>max) {
max = f[j];
c = 1;
}
}
//OUTPUT result
printf("Case #%d: %d\n", i+1, max);
int counter = 0;
for (int j = 1; j<200001; j++) {
if (f[j] == max) {
counter ++;
if (counter<c){
printf("%d ", j);
} else {
printf("%d\n", j);
}
}
}
}
return 0;
}

How can I print conditional statement in an array

I am trying to identify the prime and composite value from an array. But in conditional statement, it prints only if value not else.
#include <stdio.h>
int main()
{
int a[5], i, j;
for (i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
for (i = 0; i < 5; i++)
{
for (j = 2; j <= a[i] / 2; j++)
{
if (a[i] % j == 0)
{
printf("%d is not a prime number\n", a[i]);
break;
}
else
{
printf("%d is a prime number\n", a[i]);
break;
}
}
}
return 0;
}
The number is prime only if for all for (j = 2; j <= a[i] / 2; j++) the conditional a[i] % j == 0 is false. What you need to do is the following:
#include <stdio.h>
int isNumberPrime(int value){
if(value == 1) return 0;
for (int j = 2; j <= value / 2; j++)
if (value % j == 0)
return 0;
return 1;
}
int main()
{
int a[5];
for (int i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
for (int i = 0; i < 5; i++)
{
if(isNumberPrime(a[i]))
printf("%d is a prime number\n", a[i]);
else
printf("%d is not a prime number\n", a[i]);
}
return 0;
}

doesn't count extra numbers [magic square]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N_MAX 10
#define N_MIN 2
#define TEMPSIZE 1024
float RowSum(float **matrix, int sizearray,int row) {
float sum;
for (int j=0 ; j <= row; j++) {
sum = 0;
for (int i=0 ; i < sizearray; i++) {
sum = sum + matrix[j][i];
}
}
return sum;
}
float ColSum(float **matrix, int sizearray, int col) {
float sum;
for (int j = 0; j <= col; j++) {
sum = 0;
for (int i = 0; i < sizearray; i++) {
sum = sum + matrix[i][j];
}
}
return sum;
}
int RepNum(int arraysize, float **matrix) {
int i, j, counter = 0;
int temparray[N_MAX*N_MAX];
for (i = 0; i < N_MAX*N_MAX; i++) {
temparray[i] = 0;
}
for (i = 0; i < arraysize; i++) {
for (j = 0; j < arraysize; j++) {
temparray[(int)matrix[i][j]]++;
}
}
for (i = 1; i < arraysize*arraysize; i++) {
if (temparray[i] > 1)
counter++;
}
return counter;
}
void PrintArray(float **matrix, int arraysize) {
for (int i = 0; i<arraysize; i++)
{
for (int j = 0; j<arraysize; j++)
printf("%3d ", (int)matrix[i][j]);
printf("\n");
}
}
int CheckInt(float **matrix, int arraysize) {
int counter = 0;
for (int i = 0; i < arraysize; i++) {
for (int j = 0; j < arraysize; j++) {
if (((int)matrix[i][j]) != matrix[i][j])
counter++;
}
}
return counter;
}
void main() {
printf("Hello! this program will help you to find out if you have a magic square!\nPlease enter your matrix order and following it the numbers you'd like to check: \n");
float **matrix;
char input[TEMPSIZE];
int sizear = 0;
float correctsum = 0.0;
int counter = 0, row, column;
fgets(input, TEMPSIZE, stdin);
char* str = strstr(input, " ");
if (str == 0)
return;
str[0] = 0;
str++;
sizear = atof(input);
if (sizear > N_MAX || sizear < N_MIN)
{
printf("ERROR: The matrix size cannot be %d size. \n", sizear);
exit(0);
}
matrix = (float**)calloc(1, sizear * sizeof(float*));
for (column = 0; column < sizear; column++)
{
matrix[column] = (float*)calloc(1, sizear * sizeof(float));
}
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
char* temp = strstr(str, " ");
if (temp == 0) /*gets the last number*/
{
++counter;
matrix[row][column] = atof(str);
goto end;
}
if (atof(temp) <= sizear*sizear && atof(temp) > 0) { /*puts all numbers in matrix*/
temp[0] = 0;
matrix[row][column] = atof(str);
str = temp + 1;
++counter;
}
else {
printf("you cannot enter the number %.3f \n", atof(temp));
exit(0);
}
}
}
end:
if (counter > sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter < sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter == sizear*sizear) {
correctsum = (float)((sizear*(sizear*sizear + 1)) / 2);
float row = RowSum(matrix, sizear, 0);
float coul = ColSum(matrix, sizear, 0);
if (row == coul && row== correctsum && coul==correctsum && RepNum(sizear, matrix) ==0 && CheckInt(matrix,sizear)==0) {
printf("It's a magic matrix!\n");
PrintArray(matrix, sizear);
}
else {
printf("Not a magic square:\n");
if (row != coul && row != correctsum && coul != correctsum) {
printf("* Coloums and rows sum do not match.\n");
}
if (RepNum(sizear, matrix) != 0) {
printf("* There are repeating numbers.\n");
}
if (CheckInt(matrix, sizear) != 0) {
printf("* One of the numbers or more you've entered isn't integer.\n");
}
}
}
for (column = 0; column < sizear; column++)
{
free(matrix[column]);
}
free(matrix);
}
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
The exercise asked to check if the input is a magic square (sum rows=columns=diagonals), making sure there are no duplicates, only int numbers and that I don't enter more or less than sizearrayXsizearray numbers. The input from the user should look like 3 1 2 3 4 5 6 7 8 9 where the first number (here it is 3) is the array size and the rest are the numbers that would be checked as a magic square.
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
Sure, it's simple: the counter is incremented in the loops
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
…
}
}
- the inner statements are run through (at most) sizear × sizear times, so the counter, starting from 0, cannot reach a higher value.

Resources