Iterating through a two dimensional array column wise in c - c

Please can someone explain to me how to iterate through a two dimensional array column wise i.e keeping the row constant until we reach the end of the column?
Thanks.
I'm writing a program to calculate scores of some subjects in a class of students. It calculates the total marks obtained by each student and also the highest mark in each subject.
The tricky part i'm having difficulty is calculating the lowest mark in each subject. This will require to iterate downwards each column and change the row only after getting the highest score in that column(subject)
The code (also - http://pastebin.com/FmP4yX59 ):
#include <stdio.h>
#include <stdlib.h>
#define MAX_ST 3
#define MAX_SU 3
int main() {
int student[MAX_ST][MAX_SU];
int total_mark[MAX_ST];
printf("\n_________________PRESS TAB KEY TO SHIFT A COLUMN_________________\n");
printf("\nRoll_NO subject1 subject2 subject3\n");
printf("________________________________________________________________\n");
for(int i = 0; i < MAX_ST; i++) {
printf("%d\t|\t",i+1);
for(int j = 0; j < MAX_SU; j++){
scanf("%d",&student[i][j]);
}
}
//total marks obtained by each student
printf("\nTOTAL MARKS\n");
for(int i = 0; i < MAX_ST; i++) {
total_mark[i] = 0;
for(int j = 0; j < MAX_SU; j++) {
total_mark[i] += student[i][j];
}
printf("Student %d = %d\n",i+1, total_mark[i]);
}
//highest total mark
int overRoll = 0;
int high_S = 0;
for(int i = 0; i < MAX_ST; i++) {
if(high_S <= total_mark[i]) {
high_S = total_mark[i];
overRoll = i;
}
}
printf("Highest total marks is %d for Student %d\n", high_S,overRoll + 1);
//highest mark in each subject
//where the problem lies
int highest_mark[MAX_SU];
int highest_sudent[MAX_SU];
for(int i = 0; i < MAX_SU;i++){
for(;j = t;) {
Highest_mark[i] = 0;
if(student[i][j] > highest_mark[i]) {
highest_mark[j] = student[][j];
highest_student[i] = i;
}
}
printf("the highest");
}
}

Typically you'd do something like this:
typedef void action_t (int*);
void traverse_matrix ( size_t col,
size_t row,
int matrix[col][row],
action_t* action )
{
for(size_t x=0; x<col; x++)
{
for(size_t y=0; y<row; y++)
{
action(&matrix[x][y]);
}
}
}

#define rows 5
#define columns 4
int matrix[rows][columns];
int r, c;
for (c = 0; c < columns; c++)
{
for (r = 0; r < rows; r++)
{
matrix[r][c]; \\ the data
}
}

thanks guys for helping me figure it out
int highest_mark[MAX_SU];
int highest_student[MAX_SU];
int curr_sub;
for(int i = 0; i < MAX_SU; i++)
{
highest_mark[i] = 0;
for(int j = 0; j < MAX_ST; j++)
{
if(student[j][i] > highest_mark[i])
{
highest_mark[i] = student[j][i];
highest_student[i] = j+1;
curr_sub = i+1;
}
}
printf("the highest score subject %d is %d by student %d\n", curr_sub, highest_mark[i],highest_student[i]);
}

Related

Arranging columns in a matrix lexicographically

I've been trying to sort columns in a matrix (the dimensions are m,n <= 10) via the lexicographical order (if the columns share the same element, then we compare the elements in the row beneath etc.) with some additional conditions. I need to use functions to print the matrix, input random integers up to 5 as its elements and finally arrange the matrix. I think I got the printing and random inputs correctly but I can't figure out the sorting. Plus I can't use global variables which I have no idea how to do, since I haven't been shown. An example matrix would be :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n;
int mat[10][10];
void print_matrix()
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
for (k = i + 1; k < m; ++k)
{
if (mat[i][j] < mat[k][j])
{
a = mat[i][j];
mat[i][j] = mat[k][j];
mat[k][j] = a;
}
}
}
}
}
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int(mat[m][n]);
print_matrix(mat[m][n]);
arrange(mat[m][n]);
print_matrix(mat[m][n]);
return 0;
}
Try this solution(will work for input 0-8 only), also used global variables:
There have multiple solutions. but is the easiest one.
I have converted each of the columns as an integer value. then bubble sorted the integers. After sorting. I have then converted the integer value to digits. (You have to know how to convert individual digits to multiple digit integer and multiple digit integers to single-digit.
Note I have added one(1) with each digit. Because the input can be zero(0). if you convert 0 0 2 1 to an integer will be only 21. the first two digits lost. So I have added 1. so 0 0 2 1 will be converted to 1132. I have done (added 1) for each input(deducted 1 after sorting). so it will not affect other inputs. Be careful input have to be from(0 to 8)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m, n;
int mat[10][10];
int generatedNumber[10];
void print_matrix()
{
printf("The matrix is:\n");
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
int number = 0;
for (i = 0; i < m; ++i)
{
number = number * 10 + mat[i][j] + 1;///Adding one for avoiding zero(0)
}
generatedNumber[j] = number;
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( generatedNumber[j] > generatedNumber[j+1])
{
// swap the elements
int temp = generatedNumber[j];
generatedNumber[j] = generatedNumber[j+1];
generatedNumber[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)///columwise
{
int generatedColumnvalue = generatedNumber[i];
for(j = m -1; j>= 0; j--)///row wise and fro last vaue to first
{
mat[j][i] = (generatedColumnvalue%10)-1;///removing extra added 1
generatedColumnvalue/=10;
}
}
}
int main()
{
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int();
print_matrix();
arrange();
print_matrix();
return 0;
}

I am trying to find the duplicate of elements in an array

Can someone help me to figure out why my code is unable to accurately find the duplicate of elements?
#include <stdio.h>
int main() {
int array[10];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = i + 1; j < 10; j++) {
if (array[i] == array[j]) {
count++;
break;
}
}
}
printf("The duplicates are : %d ", count);
}
I'm a beginner at this language so any advice and suggestions to help me solve this exercise will be much appreciated.
First of all the first loop runs 10 times even if the user enters less numbers. You can fix that by doing:
for (int i = 0; scanf_s("%d", &array[i]) == 1 && i < 10; i++);
Then the logic of the other two loops is wrong. I initially got wrong what you meant. I thought you wanted to know how many times a number is duplicated. So I wrote the wrong program and then modified it for your purposes. Here is your program:
#include <stdio.h>
int main() {
int n[10];
int dupes[5], d = 0;
int flag = 1, omg;
for ( omg = 0; scanf("%d", &n[omg]) == 1 && omg < 10; omg++);
for (int i = 0; i < omg; i++) {
for (int j = i+1; j < 10; j++) {
if( n[i] == n[j] ) {
if( d > 0 ) {
for(int k = 0; k < d; k++) {
if( n[i] == dupes[k] ) {
flag = 0;
break;
}
}
}
if( flag ) {
dupes[d] = n[i];
++d;
break;
}
else {
flag = 1;
break;
}
} // end outer if
}
}
printf("There are %d numbers that have at least one dupe\n", d);
return 0;
}
I named a variable omg out of desperation, writing this program was a nightmare. (Because it came from the ashes of a previous program)
Your code correctly determines the number of duplicate entries in the array.
If instead you want to determine the number of duplicated values, you must modify the algorithm:
#include <stdio.h>
int main() {
int array[10] = { 0 };
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (array[i] == array[j]) {
if (i < j)
count++;
if (i != j)
break;
}
}
}
printf("There are %d duplicate values\n", count);
return 0;
}
I use a structure 'Number' which contains the number and its duplicate, then I fill the array and I put it in ascending order then I calculate the number of duplicate of each number and I fill in the strecture like this :
my code:
#include <stdio.h>
#define size 10
typedef struct Number
{
int number;
int duplicate;
}Number;
int main()
{
int array[size];
Number array2[size];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
int temp=size;
int temppppp=0;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(array[i]>array[j])
{
temppppp=array[i];
array[i]=array[j];
array[j]=temppppp;
}
}
}
printf("\n\n");
for (int i = 0; i < size; i++)
{
printf("[%d]",array[i]);
}
printf("\n\n");
int i=0;
int j=0;
while(i<size)
{count=1;
while(i<(size-1)&&array[i]==array[i+1])
{
count++;
i++;
}
if(count>=2)
{
array2[j].number=array[i-1];
array2[j].duplicate=count;
j++;
}
i++;
}
int p=0;
while(p<j)
{
printf("\n[%d] has duplicated %d times !\n",array2[p].number,array2[p].duplicate);
p=p+1;
}
printf("\n\n");
printf("\nThere are %d duplicate values\n", j);
}

printing a matrix adress instead of values | C

I wrote a code that tries to multiply two matrices and put them in another result matrix. The code is working (I think) but it prints a very strange output .. I think it has to do with one of the functions pointing to something diffrent than the values, not sure though.
I tried checking each function in separete, also inizialzing each matrix with {0}.
#include <stdio.h>
#define SIZE 5
//#pragma warning(disable:4996)
//#define _CRT_SECURE_NO_WARNINGS
void read_mat(int mat[][SIZE])
{
int i, j, k = 0;
char s[100]; // assign input str to 's'
fgets(s,25,stdin); // recieving only the first 25 numbers
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (s[k] == '\0') { //if the string is just \0 -- the end of the string
mat[i][j] = 0;
}
else { // is there are values in s
if (s[k] != '0') { // binary matrix -- only 0 or 1
mat[i][j] = 1;
k++;
}
else {
mat[i][j] = 0;
++k;
}
}
}
}
}
void mult_mat(int mat_a[][SIZE], int mat_b[][SIZE], int result_mat[][SIZE])
{
int i, j, k;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
for (k = 0; k < SIZE; k++) {
result_mat[i][j] += mat_a[i][k] * mat_b[k][j]; // by definition of matrix multiplication
k++;
}
}
}
}
void print_mat(int mat[][SIZE])
{
int i, j, k = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%3d", &(mat[i][j])); // printing each value with a 3*space
}
printf("\n");
}
}
int main()
{
int mat_a[SIZE][SIZE] = {0}, mat_b[SIZE][SIZE] = {0}, result_mat[SIZE][SIZE] = {0}; // initializing matricies to {0}
printf("Please Enter Values For Matrix 1\n");
read_mat(mat_a);
printf("Please Enter Values For Matrix 2\n");
read_mat(mat_b);
mult_mat(mat_a, mat_b, result_mat);
printf("The First Matrix Is :- \n");
print_mat(mat_a);
printf("The Second Matrix Is :- \n");
print_mat(mat_b);
printf("The Resultant Matrix Is :- \n");
print_mat(result_mat);
return 0;
}
the outout I am getting:
enter image description here
thanks!
improve your print function
void print_mat(int mat[][SIZE])
{
int i, j, k = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("(%3d), ", &(mat[i][j])); // printing each value with a 3*space
}
printf("\n");
}
}

Writing values in a 2 dimensional array in c

Being new to C, and this website, I'm unfamiliar with this problem I'm having. I have a 2 dimensional array with [8][8] elements. I'm trying to get the user to enter numbers into the array until finished. The program is far from finished, but I'm stuck on this problem before I can move on. Basically I use a for loop to let the user enter into each element. However, when the first row is complete, it overwrites it's last value onto the first column second row element spot. How can I prevent this from happening: Here's my code:
#include <stdio.h>
#include <string.h>
int Check_rules();
void Print_Array(int array[][8], int size)
{
int i, j;
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
{
printf("%d ",array[i][j]);
}
}
printf("\n\n");
}
int main()
{
int size = 8;
int i, j;
int fullArray[size][size];
int grid1[3][3];
int grid2[3][3];
int grid3[3][3];
int grid4[3][3];
int grid5[3][3];
int grid6[3][3];
int grid7[3][3];
int grid8[3][3];
int grid9[3][3];
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
fullArray[i][j] = 0;
}
printf("Want to play a game? Enter values 1-9 starting in row 1 column 1, \nand we will work our way from there. Here's the playing board.\nIt's Sudoku, so follow the rules of the game.\n\n");
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
printf("%d ",fullArray[i][j]);
}
printf("\n\n");
int tmp;
char *keeper = (" ");//space for marker
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
{
printf("Enter first value(press 0 and ENTER to skip a box, \nand -1 to cancel game): ");
scanf("%d", &tmp);
if(tmp == -1)
return 0;
fullArray[i][j] = tmp;
Print_Array(fullArray,size);
}
}
return 0;
}
If you run this you'll see my problem when you enter the last value in row 1. It overwrites the second row first column element spot?
Everywhere you have <= size, you actually want < size. This is because C uses 0-based indexes. That means if you have an array with 5 elements, the indexes are 0, 1, 2, 3, 4. In a loop like for (int i = 0; i <= 5; i++), i would get the values 0, 1, 2, 3, 4, 5. That last one is an invalid index into the array. Using i < 5 fixes the problem (ensures i stops before it reaches 5).
Fixed and cleaned up version of your code:
#include <stdio.h>
#include <string.h>
void printArray(int size, int array[][size]) {
for (int i = 0; i < size; i++) {
printf("\n");
for (int j = 0; j < size; j++) {
printf("%d ", array[i][j]);
}
}
printf("\n\n");
}
int main() {
int size = 8;
int fullArray[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
fullArray[i][j] = 0;
}
}
printf("Enter values in row 1 column 1, and we will work our way from there. Here's the playing board. \n\n");
printArray(size, fullArray);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter first value (press 0 and ENTER to skip a box, or -1 to cancel game): ");
int number;
scanf("%d", &number);
if(number == -1) {
return 0;
}
fullArray[i][j] = number;
printArray(size, fullArray);
}
}
return 0;
}
EDIT
To clarify, this is fixed version of the original code in the question. The new code is a bit different, but I think the issue is the same.

C programming with functions

I have got some more problems with the code. This program ask the user to specify the nr of throws then it throws 3 dices and add these 3 dices to sum.
Then another function sorts the sum form the smallest to the largest with a bubble sorting algorithm.
the first two functions seems to work but the program does not print out the result of the 3rd sorting function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100
//This function ask the user for the amout of throws
int numberofthrows() {
int throws
printf("Type in the number of throws");
scanf("%d", &throws);
return throws;
}
//This function makes the random throws of 3 dices with regard to the number of throws
int filler(int thrownr, int dice1[MAX], int dice2[MAX], int dice3[MAX], int sum[MAX]) {
int i, nr;
srand(time(NULL));
for(i = 0; i <= thrownr; i++) {
nr = rand()%6;
dice1[i] = nr + 1;
nr = rand()%6;
dice2[i] = nr + 1;
nr = rand()%6;
dice3[i] = nr + 1;
sum[i] = dice1[i] + dice2[i] + dice3[i];
}
int j;
for(j = 0; j <= thrownr; j++) {
printf("%d ", dice1[j]);
printf("%d ", dice2[j]);
printf("%d ", dice3[j]);
printf("%d\n", sum[j]);
}
}
//This function sorts the result in form the sum array
int sorter(int thrownr, int sum[MAX], int sortsum[MAX]) {
int tmp, i, j, k, m;
for(i = 0; i <= thrownr; i++) {
sortsum[i] = sum[i];
}
for(m = 0; m <= 10; m++) {
for(j = 0; j <= thrownr; i++) {
if (sortsum[j] > sortsum[j+1]) {
tmp = sortsum[j];
sortsum[j] = sortsum[j+1];
sortsum[j+1] = tmp;
}
}
}
for(k = 0; k <= thrownr; k++) {
printf("%d\n", sortsum[k]);
printf("%d\n", sum[k]);
}
}
int main(void) {
srand(time(NULL));
int dice1[MAX];
int dice2[MAX];
int dice3[MAX];
int sum[MAX];
int sortsum[MAX];
int numberofthrows2;
numberofthrows2 = numberofthrows();
filler(numberofthrows2, dice1, dice2, dice3, sum);
sorter(numberofthrows2, sum, sortsum);
return 0;
}
The code for sorting is a bit wrong. Change
for(m = 0; m <= 10; m++)
To
for(m = 0; m <= thrownr-1; m++)
And
for(j = 0; j <= thrownr; i++)
To
for(j = 0; j < thrownr-m-1; i++)
To fix it. Also, call srand once at the start of main. Don't call it more than once in a program or you might get the same "random" numbers everytime you run your program.

Resources