Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Friday, July 24, 2015

C++ Program to Solve the Magic Squares Puzzle without using Recursion

Leave a Comment
The following C++ program, using iteration, finds the magic square for a given odd sized number. A magic square is an arrangement of numbers from 1 to n^2 in an [n x n] matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.


Code:

#include<iostream>
using namespace std;

void magicsq(int, int [][10]);

int main( )
{
    int size;
    int a[10][10];

    cout<<"Enter the size: ";
    cin>>size;
    if (size % 2 == 0)
    {
        cout<<"Magic square works for an odd numbered size\n";
    }
    else
    {
        magicsq(size, a);
    }
    return 0;
}

void magicsq(int size, int a[][10])
{
    int sqr = size * size;
    int i = 0, j = size / 2, k;

    for (k = 1; k <= sqr; ++k)
    {
        a[i][j] = k;
        i--;
        j++;

        if (k % size == 0)
        {
            i += 2;
            --j;
        }
        else
        {
            if (j == size)
            {
                j -= size;
            }
            else if (i < 0)
            {
                i += size;
            }
        }
    }
    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            cout<< a[i][j];
        }
        cout<<endl;
    }
    cout<<endl;
}

Output:

Read More

Thursday, February 12, 2015

Life, the Universe, and Everything

Leave a Comment
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

Example

Input:
1
2
88
42
99

Output:
1
2
88 
 

Solution

#include<iostream>
using namespace std;
typedef struct list{
    int number;
    list *next;
}list;
//prototypes
list* insert(int,list*);
void print(list*);

int main()
{
    list *num=NULL;
    int number;
    while(1)
    {
        cin>>number;
        if(number==42)
            break;
        else
        num=insert(number,num);
    }
    print(num);
return 0;
}

//Definations
list* insert(int numb,list *num)
{
    list *ptr;
    ptr=new list;
    ptr->number=numb;
    ptr->next=NULL;

    if(num==NULL)
    {
        num=ptr;
    }
    else
    {
        list *temp;
        temp=num;
        while(temp->next!=NULL)
        {
            temp=temp->next;
        }
        temp->next=ptr;
    }
    return num;
}
void print(list *num)
{
    list *temp;
    temp=num;
    while(temp!=NULL)
    {
        cout<<temp->number<<endl;
        temp=temp->next;
    }
}




Read More