Array representation using Row Major and Column Major order in C.

A

If you are a computer science student or wants to start learning Data structure using practical hands-on then you are landing in the right place. This practice is part of the Data structure subject taught in GTU (Gujarat Technological University) Diploma course, but it is not limited to this. You can use this tutorial to have a better understanding of detail explanations. if you like to get more out of this practice then I highly recommend you to do code follow along is a best possible way. To know more about Author please visit here

Let’s take a brief about what is going to solve/code and design out solution step by step


Unit 1
Practical 2: Represent 2 D Matrix into Row Major and Column Major (1 D) order.

/*
* @Author: abdulkaiyum
* @Date:   2019-07-15 07:53:23
* @Last Modified by:   abdulkaiyum
* @Last Modified time: 2019-07-17 11:40:07
*/
// Implement array using row major and column major order.

#include <stdio.h>
#include <stdlib.h>

// Globle declaration
int rowCount,colCount;
int *Matrix; // 1D pointer for 2D array 

void getRowColSize()
{
	printf("%s\n", "Enter Matrix row size");
	scanf("%d",&rowCount);

	printf("%s\n", "Enter Matrix column size");
	scanf("%d",&colCount);

	// init Matrix 
	Matrix = (int *) malloc(rowCount * colCount * sizeof(int *));
}

void RowMajor()
{
	int i,j;

	printf("%s\n", "Enter elements");
	for (i = 0; i < rowCount; i++)
	{
		for (j = 0; j < colCount; j++)
		{
			scanf("%d", (Matrix + i * rowCount + j));
		}
	}
}

void ColumnMajor()
{
	int i,j;

	printf("%s\n", "Enter elements");
	for (i = 0; i < rowCount; ++i)
	{
		for (j = 0; j < colCount; ++j)
		{
			scanf("%d", (Matrix + i + colCount * j));
		}
	}
}

void Show()
{
	int i,j;
	for (i = 0; i < rowCount; i++)
	{
		for (j = 0; j < colCount; j++)
		{
			printf("[%d][%d](%d):",i,j,(i*rowCount+j));

			printf("%d \n", *(Matrix));
			Matrix++;
		}
	}
}

int main(int argc, char const *argv[])
{
	int option;
	getRowColSize();
	printf("%s\n", "Choose option");
	printf("%s\n", "1. Row Major");
	printf("%s\n", "2. Column Major");

	scanf("%d",&option);

	switch(option)
	{
		case 1: 
		// calling Row major 
		RowMajor();
		Show();

		break;

		case 2: 
		// calling Column major
		ColumnMajor();
		Show();
		break;
		default:
		printf("%s\n", "Are you sure about the option! I don't think so");
	}

	return 0;
}

Add comment

Recent Posts

Recent Comments

Archives

Categories

Email Subscriber