Enter N to print a matrix of n X N on the screen, using dynamic memory to allocate int * * num

Source: Internet
Author: User
Tags first row

Input 3:

Output:

1 2 3

8 9 4

7 6 5

The code is as follows:

#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
	int N;
	int i,j;
	int count,m;
	int **num;
	cout<< "Please enter the value of N:";
	cin>>n;
	num= (int * *) malloc (sizeof (int *) *n);
	for (i=0;i<n;i++)
	{		
		num[i]= (int *) malloc (sizeof (int) *n);
	}
	Count=1;
	M=1;
	for (i=0;i<n;i++)//First row
	{
		num[0][i]=m++;
	}
	for (j=n-1;j>=n/2;j--)
	{for
		(i=count;i<=j;i++)//Last column
		{
			num[i][j]=m++;
		}
		for (i=j;i>=count;i--)//The bottom line
		{
			num[j][i-1]=m++;
		}
		for (i=j-1;i>=count;i--)//Leftmost column
		{
			num[i][count-1]=m++;
		}
		for (i=count;i<j;i++)//above the second row
		{
			num[count][i]=m++;
		}
		count++;
	}
	for (i=0;i<n;i++)
	{
		for (j=0;j<n;j++)
		{
			printf ("%3d  ", Num[i][j]);
		}
		cout<<endl;
	}
	return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.