Post your C/C++ Programs Here

Status
Not open for further replies.

swap_too_fast

Broken In
Re: Post ur C/C++ Programs Here

QwertyManiac said:
Here's a simple Stack program I wrote and documented a bit in C long time ago. Surprisingly found it in my programs directory ..

Code:
/* Stack Implementation using Linked Lists */

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

/* Structure Declaration:
    Structure for a Stack (Linked List Structure)
    Requires two elements.
    
    One Element member, holding the value that the stack is to be made of
    One Self-Referring Pointer member for making it a Linked List - Stack. */

    typedef struct stacklink

        {
            int element;
            struct stacklink *next;
        } top ;
        
typedef top stack;

/* Create:
    Initializes the stack with a NULL value. */
    
    void create(stack *s)
        {
                 s=NULL;
        }

/* Push:
    Pushes (Inserts) a node into the Stack, using a new temporary node.
    Stack's Push operation is done only on the top of the stack */

    stack *push(stack *s)
        {
            int a=0;
            stack *temp;
            
            printf("\nEnter the element to push into the stack: ");
            scanf("%d",&a);
            
            temp = (stack *)malloc(sizeof(stack));

            temp->element = a;
            temp->next = s;

            return temp;
        }

/* Pop:
    Pops (Deletes) the top-most element out of the Stack.
    Also checks if the stack is empty or not and pops only when there is an element available. */

    stack *pop(stack *s)

        {
            stack *temp;
            
            if(s->next!=NULL)
                {
                    temp = s;
                    printf("\nPopped element is: %d\n",temp->element);
                    s = s->next;
                    free(temp);
                }
            
            else
                {
                    printf("\nNothing to Pop from the stack.\n");
                }
                
            return s;
        }

/* Display:
    Displays the Stack in a pictorial fashion.
    A sample output of the stack via this would look like:
        The List is:
        4 -> 5 -> 6 -> NULL
    Where, NULL represents the END of stack. For an empty stack too, it shows NULL. */
    
    void display(stack *s)

        {    
            int temp=1;
            
            printf("\nThe Stack is:");
            
            if(s->next==NULL)
                {
                    printf("\b empty");
                }
            
            while(s->next!=NULL)
                {
                    if(temp)
                        {
                            printf("\n");
                            temp=0;
                        }
                    
                    printf("%d --> ",s->element);
                    s=s->next;
                    
                    if(s->next==NULL)
                        {
                            printf("NULL");
                            break;
                        }
                }
                
            printf("\n");
        }
        
/* Main Menu:
    Displays a menu-based access system for various operations on the stack.
    The menu looks like:
        1. Create
        2. Push
        3. Pop
        4. Display
        5. Exit
    Each item in the menu calls the appropriate functions of the Stack. */

    int main()

        {
            int choice, key, loc,throw=0;
            stack *temp;
            
            while(1)
                {
                    printf("\nStacks\n-------\n");
                    printf("1. Create\n2. Push\n3. Pop\n4. Display\n5. Exit");
                    printf("\nEnter your choice: ");
                    scanf("%d",&choice);
                    
                    switch(choice)
                        {
                            case 1:
                            
                                temp=(stack *)malloc(sizeof(stack));
                                
                                create(temp);
                                
                                printf("\nNULL Stack created\n");
                                throw=1;
                                
                                break;
                                
                            case 2:
                                if(throw==1)
                                    {
                                        temp=push(temp);
    
                                        display(temp);
                                    }
                                
                                else
                                    {
                                        printf("\nCreate a stack first ..\n");
                                    }
                                
                                break;
                                
                            case 3:
                                
                                if(throw==1)
                                    {
                                        temp=pop(temp);

                                        display(temp);
                                    }
                                
                                else
                                    {
                                        printf("\nCreate a stack first ..\n");
                                    }
                                    
                                break;
                                
                            case 4:

                                if(throw==1)
                                    display(temp);
                                
                                else
                                    printf("\nCreate the stack first ..\n");
                                    
                                break;
                                
                            case 5:
                            
                                return 0;
                                
                            default:
                            
                                printf("\nInvalid choice ...\n");
                                
                        }
                }
        }

PLz tell me what about this program and what it will do, i know stack but plz explain

I have new idea..!!!!

What about some challenges any one can raised problem, before 2 days my teacher challenge me to do a program to convert given number into binary , octal and hexadecimal. I have found solution but you have to try.

for exercise:

do a program like U have to hide the typed string on screen by" * "

like we do password: **********

nice one haa..
 
Last edited:

QwertyManiac

Commander in Chief
Re: Post ur C/C++ Programs Here

Stack is a simple Last-In First-Out data structure .. Its like this:

*upload.wikimedia.org/wikipedia/commons/2/29/Data_stack.svg|20|
|30|
|40|
----

To add an element to it, we can only push from top and not insert anywhere we like:

So after pushing 10 into the stack, it looks like:

|10| <-- (Pushed on top)
|20|
|30|
|40|
----

Similarly, as its a LIFO system, Popping the stack removes the top most element.

Thus, 10 would be removed on popping:

|20| --> |10| (Popped out and deleted)
|30|
|40|
----

Stack's best application would be the function call. Recursion takes place in stacks format. (And are thus usually avoided)

Read more
 

Zeeshan Quireshi

C# Be Sharp !
Re: Post ur C/C++ Programs Here

xbonez said:
hmm, u use Oxford and Sumita Arora's textbook for C++. they're our course books in XI and XII
Mate i suggest you re-learn C++ using Addison Wesley's Accelerated C++

One of the best Standard C++ books out there that actually teach you how to use STL practically rather than just theory.

btw , i read this in class XI(i'm currently in XII) so ditch your textbook(seriously) and use this .
 

QwertyManiac

Commander in Chief
Re: Post ur C/C++ Programs Here

Isn't that as simple as calling the DOS shutdown function via the system function?

Like system("shutdown /?"); for example.

Why would you wanna do it though ? I smell a prank :D
 

The_Devil_Himself

die blizzard die! D3?
Re: Post ur C/C++ Programs Here

swap_too_fast said:
I have new idea..!!!!

What about some challenges any one can raised problem, before 2 days my teacher challenge me to do a program to convert given number into binary , octal and hexadecimal. I have found solution but you have to try.

That is one helluva program which I made 2-3 months back but my program was not perfect as I used a lot of arrays which took up a lot of memory and more often than not they were never used.I seem to have lost my original program code but will write it and post it in a couple of days or so.

YOu can actually display the given no. in octal,hexadecimal,and binary by just using %o,%x,and(I forgot for binary) instead of %d while displaying.
 

QwertyManiac

Commander in Chief
Re: Post ur C/C++ Programs Here

I don't have a program to do Oct, Hex, Bin, etc in C/C++ but here is my module in Python. It inter-converts between Strings-Binary-Hexadecimal-Octal-Decimals :)

Code:
#/usr/bin/env python

"Base-n tools with String support (Base-n not complete yet, sorry)"

"String to Binary [Returns a spaced out Binary value string]"
def strtobin(a):
	b,c='',0
	for each in a:
		c = ord(each)
		b+=dectobin(c)+' '
	return b[:-1]

"String to Decimal [Returns a spaced out Decimal value string]"
def strtodec(a):
	b=''
	for each in a:
		b+=str(ord(each))+' '
	return b[:-1]

"String to Octal [Returns a spaced out Octal value string]"
def strtooct(a):
	b=''
	for each in a:
		b+=dectooct(strtodec(each))+' '
	return b[:-1]

"String to Hexadecimal [Returns a spaced out Hexadecimal value string]"
def strtohex(a):
	b=''
	l=strtodec(a).split(' ')
	for each in l:
		b += hex(int(each)) + ' '
	return b[:-1]

"Hexadecimal to Binary [Returns a Binary value string]"
def hextobin(a):
	return dectobin(hextodec(a))

"Hexadecimal to Decimal [Returns a Decimal value]"
def hextodec(a):
	return int(a,16)

"Hexadecimal to Octal [Returns an Octal value string]"
def hextooct(a):
	return oct(hextodec(a))

"Hexadecimal to String [Returns a string corresponding to each Decimal ASCII value of the Hexadecimal value]"
def hextostr(a):
	b=""
	l=[a.split(" ")]
	for each in l[0]:
		b+=chr(hextodec(each))
	return b

"Octal to Binary [Returns an Octal value string]"
def octtobin(a):
	return dectobin(octtodec(a))

"Octal to Decimal [Returns a Decimal value]"
def octtodec(a):
	return str(int(str(a),8))

"Octal to Hexadecimal [Returns a Hexadecimal value string]"
def octtohex(a):
	a = int(a,8)
	return dectohex(octtodec(a))

"Octal to String [Returns a string based on the Decimal value of the Octal number]"
def octtostr(a):
	return dectostr(octtodec(a))

"Decimal to Binary [Returns a Binary valued string]"
def dectobin(a):
	a,b,c=int(a),'',0
	while(a>0):
		c = a%2
		b+=str(c)
		a=a/2
	return b[::-1]

"Decimal to Octal [Returns a Decimal]"
def dectooct(a):
	return oct(int(a))

"Decimal to Hexadecimal [Returns a Hexadecimal value string]"
def dectohex(a):
	return hex(int(a))

"Decimal to String [Returns a string]"
def dectostr(a):
	if int(a)<256:
		return chr(int(a))
	return None

"Binary to Decimal [Returns a Binary valued string]"
def bintodec(a):
	c=i=0
	a=a[::-1]
	for each in a:
		if each!=None:
			c+=int(each)*pow(2,i)
			i+=1
	return c

"Binary to Octal [Returns an Octal value string]"
def bintooct(a):
	return dectooct(bintodec(a))

"Binary to Hexadecimal [Returns a Binary valued string]"
def bintohex(a):
	return dectohex(bintodec(a))

"Binary to String [Returns a string]"
def bintostr(a):
	b=''
	for each in a.split(' '):
		if dectostr(bintodec(each))!=None:
			b+=dectostr(bintodec(each))+' '
	return b[:-1]

if __name__=='__main__':
	print 'Try calling any function here'
 

aditya.shevade

Console Junkie
Re: Post ur C/C++ Programs Here

A bulls and cows game.I am still working on this. Trying to add some more functionality.

I know the variable names are quite big. But I think that makes it easier to understand the program without comments.

I am new to C++. So, if you can suggest any improvements, then please do so.

One more thing, from my experience, Indian authors tend to provide knowledge based on TurboC which sucks. So, anyone going for a C++ course, please get a book suggested above, and then be sure to read professional C++ by Solter and Kleper (Wrox international). It rocks.

Aditya

Code:
/*  Project Name :- Bulls and Cows.
	Project Version :- 2.1.0.
	Project Author :- Aditya Shevade.
	Time Started :- 5th of June 2007, 08:07 pm.
	Time Finished :- 5th of June 2007, 09:21 pm.
	Built Using :- Anjuta 1.2.4a.
*/
	
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

class BullsAndCows
{
	private:
		
		int ComputerNumber, UserNumber;
		int ComputerReminderUnits, ComputerReminderTens, ComputerReminderHundreds, ComputerReminderThousands;
		int UserReminderUnits, UserReminderTens, UserReminderHundreds, UserReminderThousands;
		int PositionsCorrect, DigitsCorrect;
			
	public:
		
		void NumberInitialisation();
		void InitialiseComputerValues();
		void InitialiseUserValues();
		void UserInput();
		void Calculations();
		void NoOfPositionsCorrect();
		void NoOfDigitsCorrect();
		void CheckWin();
	
		int RandomNumber();
	
};

BullsAndCows x;

main()
{
	cout << "\n\n\t\tWelcome to Bulls and Cows.";
	cout << "\n\t\t\tVersion 2.1.0";
	cout << "\n\n\t\tPress Enter to continue";
	
	getchar();
	
	x.NumberInitialisation();
	
	return 0;
	
}

void BullsAndCows::NumberInitialisation()
{
	do
	{
		srand(time(NULL));
    	ComputerNumber = (rand () % 10000);
		
	}while (ComputerNumber > 10000 || ComputerNumber < 1000);
	
	x.InitialiseComputerValues();
	
}

void BullsAndCows::InitialiseComputerValues()
{	
	ComputerReminderUnits = ComputerNumber % 10;
	ComputerReminderTens = ((ComputerNumber - ComputerReminderUnits) / 10) % 10;
	ComputerReminderHundreds = ((ComputerNumber - (ComputerNumber % 100)) / 100) % 10;
	ComputerReminderThousands = ((ComputerNumber - ComputerNumber % 1000) / 1000);
	
	if (ComputerReminderUnits == ComputerReminderTens || ComputerReminderUnits == ComputerReminderHundreds || ComputerReminderUnits == ComputerReminderThousands || ComputerReminderTens == ComputerReminderHundreds || ComputerReminderTens == ComputerReminderThousands || ComputerReminderHundreds == ComputerReminderThousands)
		x.NumberInitialisation();
	
	else
		x.UserInput();

}

void BullsAndCows::UserInput()
{
	cout << "\n\n\t\tPlease Enter Your Choise.\n\n\t\t\t";
	cin >> UserNumber;
	
	while (UserNumber > 10000 || UserNumber < 1000)
	{
		cout << "\n\n\t\tPlease Enter Valid Values.\n\n\t\t\t";
		cin >> UserNumber;
	}
	
	x.InitialiseUserValues();
	x.Calculations();
	
}

void BullsAndCows::InitialiseUserValues()
{
	PositionsCorrect = 0, DigitsCorrect = 0;
	
	UserReminderUnits = UserNumber % 10;
	UserReminderTens = ((UserNumber - UserReminderUnits) / 10) % 10;
	UserReminderHundreds = ((UserNumber - (UserNumber % 100)) / 100) % 10;
	UserReminderThousands = ((UserNumber - UserNumber % 1000) / 1000);
	
}

void BullsAndCows::Calculations()
{
	x.NoOfPositionsCorrect();
	x.NoOfDigitsCorrect();
	
	cout << "\n\n\t\tNumber of Digits Correct :-" << DigitsCorrect;
	cout << "\n\n\t\tNumber of Positions Correct :-" << PositionsCorrect;
	
	x.CheckWin();
	
}

void BullsAndCows::NoOfPositionsCorrect()
{
	if(UserReminderUnits == ComputerReminderUnits)
		PositionsCorrect++;
	if(UserReminderTens == ComputerReminderTens)
		PositionsCorrect++;
	if(UserReminderHundreds == ComputerReminderHundreds)
		PositionsCorrect++;
	if(UserReminderThousands == ComputerReminderThousands)
		PositionsCorrect++;
	
}

void BullsAndCows::NoOfDigitsCorrect()
{
	if(ComputerReminderUnits == UserReminderUnits || ComputerReminderUnits == UserReminderTens || ComputerReminderUnits == UserReminderHundreds || ComputerReminderUnits == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderTens == UserReminderUnits || ComputerReminderTens == UserReminderTens || ComputerReminderTens == UserReminderHundreds || ComputerReminderTens == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderHundreds == UserReminderUnits || ComputerReminderHundreds == UserReminderTens || ComputerReminderHundreds == UserReminderHundreds || ComputerReminderHundreds == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderThousands == UserReminderUnits || ComputerReminderThousands == UserReminderTens || ComputerReminderThousands == UserReminderHundreds || ComputerReminderThousands == UserReminderThousands)
		DigitsCorrect++;
	
}

void BullsAndCows::CheckWin()
{
	if(PositionsCorrect == 4 && DigitsCorrect == 4)
	{
		char Answer;
		
		cout << "\n\n\t\tCongeratulations, You won!";
		cout << "\n\n\t\tDo you wish to play again?(y/n)";
		cin >> Answer;
		
		while (Answer != 'Y' && Answer != 'y' && Answer != 'N' && Answer != 'n')
		{
			cout << "\n\n\t\tDo you wish to play again?(y/n)";
			cin >> Answer;
		}
		
		if (Answer == 'Y' || Answer == 'y')
			x.NumberInitialisation();
				
		if (Answer == 'N' || Answer == 'n')
		{
			cout << "\n\n\t\tThank You for playing this Game.";
			exit(0);
		}
	
	}
	
	else
		x.UserInput();
	
}
 

The_Devil_Himself

die blizzard die! D3?
Re: Post ur C/C++ Programs Here

I don't know python but dude the program seems to just display the no. in corresponding number system.But here we were talking about actually converting the no. so that we can even use them in arithmetic operations.

The c equivalent of your program is(I am just writing the necessary part):

Printf("Enter the decimal no.:");
scanf("%d",&n);
printf("The equivalent octal no. is:%o\n\n The equivalent hexadecimal no. is %x",n,n);
getch();


The trick is just to replace %d by %o and %x while displaying.
I didn't check it but hope this works.

@qwerty please pardon me if I was unable to interpret your python program properly.BTW I am also planning to learn python very soon.So how is compared to C(I am good at c).
 

Sykora

I see right through you.
Re: Post ur C/C++ Programs Here

@qwerty : A few observations,
-- Use ''.join or (' '.join in your case) instead of string += something. It's faster.
For example,
Code:
def strtodec(a) :
    return ' '.join((ord(i) for i in a))
and likewise.
-- Put your docstrings below the function def, not above them.
That's all I can get from the first few of them.

Why do you find converting ASCII to hex and octal necessary?

@The_Devil_Himself :
The internal representation of numbers in most languages is in decimal. In C/C++ you can perform arithmetic in octal and hex by prefixing a 0 or 0x to an int declared variable. However, for other bases, you will have to define your own class and overload your own operators to make it work as seamlessly as you'd like.

Python is a much more elegant language than C. It is a dynamically typed language, and heavily object oriented. It also has one of the largest standard libraries. It pays for all this in a severe lack of speed on most number crunching applications.
 

QwertyManiac

Commander in Chief
Re: Post ur C/C++ Programs Here

Sykora said:
@qwerty : A few observations,
-- Use ''.join or (' '.join in your case) instead of string += something. It's faster.
For example,
Code:
def strtodec(a) :
    return ' '.join((ord(i) for i in a))
and likewise.
-- Put your docstrings below the function def, not above them.
That's all I can get from the first few of them.

Why do you find converting ASCII to hex and octal necessary?

Oh ok, I've just started off actually, am not so strong in it. I'll keep that point in mind. And about the usefulness, I don't know, I just wrote something huge .. practising stuff.
 

Sykora

I see right through you.
Re: Post ur C/C++ Programs Here

QwertyManiac said:
And about the usefulness, I don't know, I just wrote something huge .. practising stuff.
Oh, that's ok then. :D
 

xbonez

NP : Crysis
Re: Post ur C/C++ Programs Here

swap_too_fast said:
What about some challenges any one can raised problem, before 2 days my teacher challenge me to do a program to convert given number into binary , octal and hexadecimal. I have found solution but you have to try.

here's the prog. had created it for my class XI practicals

Code:
#include <iostream.h>
#include <conio.h>
#include <math.h>
int BtoD(long int n);
int BtoO(long int n);
long int DtoB(long int n);
int DtoO(long int n);
long int OtoB(long int n);
int OtoD(long int n);
void main()
{
	clrscr();
	int ch;
	long int n;
	cout<<"\n1.Binary to Decimal";
	cout<<"\n2.Binary to Octal";
	cout<<"\n3.Decimal to Binary";
	cout<<"\n4.Decimal to Octal";
	cout<<"\n5.Octal to Binary";
	cout<<"\n6.Octal to Decimal";
	cout<<"\nEnter the choice -->   ";
	cin>>ch;

	cout<<"\nEnter the number -->   ";
	cin>>n;

	switch (ch)
	{
		case 1:
			cout<<"\nDecimal = ";
			cout<<BtoD(n);							      
			break;
		case 2:
			cout<<"\nOctal = ";
			cout<<BtoO(n);
			break;
		case 3:
			cout<<"\nBinary = ";
			cout<<DtoB(n);
			break;
		case 4:
			cout<<"\nOctal = ";
			cout<<DtoO(n);
			break;
		case 5:
			cout<<"\nBinary = ";
			cout<<OtoB(n);
			break;
		case 6:
			cout<<"\nDecimal = ";
			cout<<OtoD(n);
			break;
		default:
			cout<<"You have entered the wrong choice";
	}
	getch();
}

int BtoD(long int n)
{
	int deci=0;
	int b,p=0;

	while (n>0)
	{
		b=n%10;
		n=n/10;
		deci=deci+b*pow(2,p++);
	}
	return deci;
}

int BtoO(long int n)
{
	int deci=0,oct=0;
	int b,c,p=0,r=0;

	while (n>0)
	{
		b=n%10;
		n=n/10;
		deci=deci+b*pow(2,p++);
	}

	while (deci>0)
	{
		c=deci%8;
		deci=deci/8;
		oct=oct+c*pow(10,r++);
	}
	return oct;
}

long int DtoB(long int n)
{
	long int bin=0;
	int b,p=0;

	while (n>0)
	{
		b=n%2;
		n=n/2;
		bin=bin+b*pow(10,p++);
	}
	return bin;
}

int DtoO(long int n)
{
	int oct=0;
	int b,p=0;

	while (n>0)
	{
		b=n%8;
		n=n/8;
		oct=oct+b*pow(10,p++);
	}
	return oct;
}



long int OtoB(long int n)
{
	long int bin=0;
	int deci=0,b,c,p=0,r=0;

	while (n>0)
	{
		b=n%10;
		n=n/10;
		deci=deci+b*pow(8,p++);
	}

	while (deci>0)
	{
		c=deci%2;
		deci=deci/2;
		bin=bin+c*pow(10,r++);
	}
	return bin;
}

int OtoD(long int n)
{
	int deci=0;
	int b,p=0;

	while (n>0)
	{
		b=n%10;
		n=n/10;
		deci=deci+b*pow(8,p++);
	}
	return deci;
}
 

Desi-Tek.com

In the zone
Re: Post ur C/C++ Programs Here

My java programs
license (desi! download it, use it, change it sale it no restriction)
Mini web server
*thakur.dheeraj.googlepages.com/MiniWebServer.zip
with source code and binary.

check ur gmail email
*thakur.dheeraj.googlepages.com/TriggerMail.zip

send email through gmail smtp in jsp
*desi-tek.org/blog/2007/09/01/jsp-code-to-send-email-through-google-gmail-smtp.html

reusable postgresql database connection class
/**
*
*/
package ocricket.bean;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
* @author Dheeraj
*
*/
public class Postgre_Connection {
public Connection conn = null;

public Postgre_Connection() {
try {
System.setProperty("file.encoding", "ISO8859-1");
//InitialContext ic = new InitialContext();
String host = "localhost"; // server ip
String port = "5432"; // port
String database = "ocricket"; // database name
String user = "dheeraj"; // database user
String pass = "123456"; // database password
start("org.postgresql.Driver", "jdbc:postgresql://" + host + ":" // postgresql database connection class
+ port + "/" + database + "?autoReconnect=true", user, pass); // Context-Params
} catch (NamingException e) {
e.printStackTrace();
}

}

public void start(String dbdriver, String dburl, String name,
String password) {
try {
Class.forName(dbdriver).newInstance();
conn = DriverManager.getConnection(dburl, name, password);
}

catch (Exception e) {
e.printStackTrace();
System.err.println(" Error: " + e);
}

}
}
how to reuse it?

Postgre_Connection post = new Postgre_Connection();
PreparedStatement ps = post.conn.prepareStatement("your sql querie");
ResultSet rs = ps.executeQuery();
you can use it with any database by doing small modification :)
 
Last edited:

praka123

left this forum longback
Re: Post ur C/C++ Programs Here

what abt licenses of all these codes ;) :D :)) GPL? Open Source License with credit given to Original authors.I'd love to post,but what am weak in Math :(
 

shady_inc

Pee into the Wind...
Re: Post ur C/C++ Programs Here

aditya.shevade said:
A bulls and cows game.I am still working on this. Trying to add some more functionality.

I know the variable names are quite big. But I think that makes it easier to understand the program without comments.

I am new to C++. So, if you can suggest any improvements, then please do so.

One more thing, from my experience, Indian authors tend to provide knowledge based on TurboC which sucks. So, anyone going for a C++ course, please get a book suggested above, and then be sure to read professional C++ by Solter and Kleper (Wrox international). It rocks.

Aditya

Code:
/*  Project Name :- Bulls and Cows.
	Project Version :- 2.1.0.
	Project Author :- Aditya Shevade.
	Time Started :- 5th of June 2007, 08:07 pm.
	Time Finished :- 5th of June 2007, 09:21 pm.
	Built Using :- Anjuta 1.2.4a.
*/
	
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

class BullsAndCows
{
	private:
		
		int ComputerNumber, UserNumber;
		int ComputerReminderUnits, ComputerReminderTens, ComputerReminderHundreds, ComputerReminderThousands;
		int UserReminderUnits, UserReminderTens, UserReminderHundreds, UserReminderThousands;
		int PositionsCorrect, DigitsCorrect;
			
	public:
		
		void NumberInitialisation();
		void InitialiseComputerValues();
		void InitialiseUserValues();
		void UserInput();
		void Calculations();
		void NoOfPositionsCorrect();
		void NoOfDigitsCorrect();
		void CheckWin();
	
		int RandomNumber();
	
};

BullsAndCows x;

main()
{
	cout << "\n\n\t\tWelcome to Bulls and Cows.";
	cout << "\n\t\t\tVersion 2.1.0";
	cout << "\n\n\t\tPress Enter to continue";
	
	getchar();
	
	x.NumberInitialisation();
	
	return 0;
	
}

void BullsAndCows::NumberInitialisation()
{
	do
	{
		srand(time(NULL));
    	ComputerNumber = (rand () % 10000);
		
	}while (ComputerNumber > 10000 || ComputerNumber < 1000);
	
	x.InitialiseComputerValues();
	
}

void BullsAndCows::InitialiseComputerValues()
{	
	ComputerReminderUnits = ComputerNumber % 10;
	ComputerReminderTens = ((ComputerNumber - ComputerReminderUnits) / 10) % 10;
	ComputerReminderHundreds = ((ComputerNumber - (ComputerNumber % 100)) / 100) % 10;
	ComputerReminderThousands = ((ComputerNumber - ComputerNumber % 1000) / 1000);
	
	if (ComputerReminderUnits == ComputerReminderTens || ComputerReminderUnits == ComputerReminderHundreds || ComputerReminderUnits == ComputerReminderThousands || ComputerReminderTens == ComputerReminderHundreds || ComputerReminderTens == ComputerReminderThousands || ComputerReminderHundreds == ComputerReminderThousands)
		x.NumberInitialisation();
	
	else
		x.UserInput();

}

void BullsAndCows::UserInput()
{
	cout << "\n\n\t\tPlease Enter Your Choise.\n\n\t\t\t";
	cin >> UserNumber;
	
	while (UserNumber > 10000 || UserNumber < 1000)
	{
		cout << "\n\n\t\tPlease Enter Valid Values.\n\n\t\t\t";
		cin >> UserNumber;
	}
	
	x.InitialiseUserValues();
	x.Calculations();
	
}

void BullsAndCows::InitialiseUserValues()
{
	PositionsCorrect = 0, DigitsCorrect = 0;
	
	UserReminderUnits = UserNumber % 10;
	UserReminderTens = ((UserNumber - UserReminderUnits) / 10) % 10;
	UserReminderHundreds = ((UserNumber - (UserNumber % 100)) / 100) % 10;
	UserReminderThousands = ((UserNumber - UserNumber % 1000) / 1000);
	
}

void BullsAndCows::Calculations()
{
	x.NoOfPositionsCorrect();
	x.NoOfDigitsCorrect();
	
	cout << "\n\n\t\tNumber of Digits Correct :-" << DigitsCorrect;
	cout << "\n\n\t\tNumber of Positions Correct :-" << PositionsCorrect;
	
	x.CheckWin();
	
}

void BullsAndCows::NoOfPositionsCorrect()
{
	if(UserReminderUnits == ComputerReminderUnits)
		PositionsCorrect++;
	if(UserReminderTens == ComputerReminderTens)
		PositionsCorrect++;
	if(UserReminderHundreds == ComputerReminderHundreds)
		PositionsCorrect++;
	if(UserReminderThousands == ComputerReminderThousands)
		PositionsCorrect++;
	
}

void BullsAndCows::NoOfDigitsCorrect()
{
	if(ComputerReminderUnits == UserReminderUnits || ComputerReminderUnits == UserReminderTens || ComputerReminderUnits == UserReminderHundreds || ComputerReminderUnits == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderTens == UserReminderUnits || ComputerReminderTens == UserReminderTens || ComputerReminderTens == UserReminderHundreds || ComputerReminderTens == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderHundreds == UserReminderUnits || ComputerReminderHundreds == UserReminderTens || ComputerReminderHundreds == UserReminderHundreds || ComputerReminderHundreds == UserReminderThousands)
		DigitsCorrect++;
	if(ComputerReminderThousands == UserReminderUnits || ComputerReminderThousands == UserReminderTens || ComputerReminderThousands == UserReminderHundreds || ComputerReminderThousands == UserReminderThousands)
		DigitsCorrect++;
	
}

void BullsAndCows::CheckWin()
{
	if(PositionsCorrect == 4 && DigitsCorrect == 4)
	{
		char Answer;
		
		cout << "\n\n\t\tCongeratulations, You won!";
		cout << "\n\n\t\tDo you wish to play again?(y/n)";
		cin >> Answer;
		
		while (Answer != 'Y' && Answer != 'y' && Answer != 'N' && Answer != 'n')
		{
			cout << "\n\n\t\tDo you wish to play again?(y/n)";
			cin >> Answer;
		}
		
		if (Answer == 'Y' || Answer == 'y')
			x.NumberInitialisation();
				
		if (Answer == 'N' || Answer == 'n')
		{
			cout << "\n\n\t\tThank You for playing this Game.";
			exit(0);
		}
	
	}
	
	else
		x.UserInput();
	
}

How do i play this game.What do I do after pressing Enter the first time??
 

aditya.shevade

Console Junkie
Re: Post ur C/C++ Programs Here

^^It is a standard bulls and cows game. The computer selects a number. A 4 digit number. There are no repeated digits in the number. Each digit is unique.

here
Code:
This is a single player game. The computer selects a 4 digit number at random and then you have to guess that number. Remember that each digit in the number selected by the computer will be unique. Then when you enter your choice, the computer will give an output which will be telling you the total number of digits and positions of those which are correct.

Suppose the computer has selected the number 2156, and you enter your guess as 1234. Here the numbers 1 and 2 are correct. The positions of those numbers are, however, not correct. So the output will be:-

                2 Numbers Correct.

                0 Positions Correct.

Now if you enter 2134 then the output will be:-

 2 Numbers Correct.

             2 Positions Correct.

Now if you enter 2156 as your number, then all four numbers as well as their positions  are correct, so the output will be:-

           The number Selected By the computer was 2156
 

Abhishek Dwivedi

TechFreakiez.com
Re: Post ur C/C++ Programs Here

i've heard ders a program to curupt da HDD....its a 3 line code....and same program can make HDD workin again...does ne one know it??
 

The_Devil_Himself

die blizzard die! D3?
Re: Post ur C/C++ Programs Here

Abhishek nothing can corrupt your hard disk what can a program can maximally do is format your hard disk.
 

QwertyManiac

Commander in Chief
Re: Post ur C/C++ Programs Here

You can write programs to corrupt drives, but I don't know of a 3 line method. It sounds ineffective and lazy. I've heard of virii damaging the firmware of your HDD rather than doing something to the HDD itself, that's clever. Though accessing the firmware is a big job!
 
Status
Not open for further replies.
Top Bottom