Home  |  About  | Last |  Submit  |  Contact
AllQuests.com




Previous Question:  Kcron doesnNext Question:  Where is my ACPI Uniprocessor driver?  null
Question Post ur C/C++ Programs Here ( Digit Forum Programming )
Updated: 2008-02-02 08:50:55 (414)
Post ur C/C++ Programs Here

Hi guys n gals,

If you are a good at C/C++ Programming or if you are a programmer or just know this language then post you Programs here. By this way it helps learners a lot. Members can post their programs and get suggestions if there is anything wrong it......

Use this Pattern:

A Program to find the largest of three numbers using nexted if

Code:
#include <stdio.h>
main()
{	
	int	a,b,c,big;
	printf("Enter Three numbers");
	scanf("%d%d%d",&a,&b,&c);
	if(a>b)
		if(a>c)
			big=a;
		else
			big=c;
	else
		if(b>c)
			big=b;
		else
			big=c;
	printf("Largest of %d,%d and %d = %d",a,b,c,big);
return 0;
}
==================================================
List of all the C Programs posted in this thread..
==================================================

A Program to find the largest of three numbers using nexted if.
A program to findcalc area, surface area, volume, total surface area etc. of numerous 2D and 3D figures using functions.
A Program to perform basic calculations.
Program To Reverse a Number
What is this?
A Program that Binary, Decimal, Octal Inter-Conversions
A bulls and cows game
A program that selects a number which is of 4 digits and all are unique numbers.
Write a C Program to sort numbers of an Array using Bubble Sort Method.
Reusable java class to send email through pop3
Simple Switch-Case Example.
Swapping of two numbers without a Temporary variable in 1 line.
A program that creates a vB list out of a file given in a particular format.
Digit Forum URL Bulleted List Generator
Write a C program to find an element from an Array using Binary Search Method.
TOWER OF HANOI Simulator
A Simple C Program to read and print a one-dimensional array
C Program to find the largest element in an array and the position of its occurrence.
A C program to find the maximum and minimum elements in an array having N elements
Program which compares two strings, concatenate them and then gives the length of string.
Program to kill a software /demo version expire in C
Program To arrange numbers in Pyramid Pattern
Program: a simple shop using string, integers, float, & algebraic operators
Character Eater
Program to insert a node in a single linked list.
A C Program to convert decimal number to its Binary Number Equivalent
Introduction to C++ - Stanford Video Tutorials and Other Lectures (Not a program)
A Program to remind that u r using other account
Typedef Example Program
A C Program to check whether a given word is Palindrome or not.
A Simple C Program to Display the number and its square from 1 to 10 using register variable.
A C Program to find the sum of two matrix using two dimensional array.

================================================== =======

Last Update: 06 November 2007

Answers: Post ur C/C++ Programs Here ( Digit Forum Programming )
Post ur C/C++ Programs Here

@ gigacore it executed nicely on devc++. tell me the problm with my program

utsav

Post ur C/C++ Programs Here

And for heaven's sake indent the code like the first post. It's unreadable otherwise.

Sykora

Post ur C/C++ Programs Here

^^ Ow.... those were the shorthand syntaxes..... Alright.... Fine. Understood.

I did not know that bitwise XOR will work bit to bit for every bit.

One last question. What steps did you use to arrive at this logic? I mean, the method used to find out the exact sequence of operations for the change? Did you use any simplification method, like we use k-map or what?

Aditya

aditya.shevade

Post ur C/C++ Programs Here

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

|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

QwertyManiac

Post ur C/C++ Programs Here

Quote:
Originally Posted by xbonez
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 .

Zeeshan Quireshi

Post ur C/C++ Programs Here

does any body had a c++ code to shut down the system

king khan

Post ur C/C++ Programs Here

Quote:
Originally Posted by Intel_Gigacore
I'm using borland Turbo C++, whenever i execute a program, it runs and closes suddenly... it happens in Dev C++ also.. please help
Dev C++ too? Doesn't the output remain in the console box? Anyway for TC++ you need to call getch(); just before the end of the main function ( Before } ) but I guess you'd definitely know that

You mean to say that you get the output but not the final result or does it end abruptly in middle (Segmentation fault?)

QwertyManiac

Post ur C/C++ Programs Here

reusable java class to send email through pop3

Code:
 /*
 * Mail.java
 *
 * Created on January 1, 2003, 1:58 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ocricket.bean;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 
 * @author Dheeraj
 */
public class Mail {

	public  void sendMail(String toemail, String subject, String body)
			throws MessagingException {
		String host = "mail.ofindia.in";
		String user = "ocricket@ofindia.in";
		String pass = "86qx3@i48fg6";
		// Create properties, get Session
		Properties props = System.getProperties();
		props.put("mail.host", host);
		props.put("mail.transport.protocol.", "smtp");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.", "true");
		props.put("mail.smtp.port", "25");
		props.put("mail.smtp.socketFactory.fallback", "false");
		Session mailSession = Session.getDefaultInstance(props, null);
		Message msg = new MimeMessage(mailSession);
		msg.setFrom(new InternetAddress(user));
		InternetAddress[] address = { new InternetAddress(toemail) };
		msg.setRecipients(Message.RecipientType.TO, address);
		msg.setSubject(subject);
		msg.setSentDate(new Date());
		msg.setText(body);
		Transport transport = mailSession.getTransport("smtp");
		transport.connect(host, user, pass);
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();

	}

}

Desi-Tek.com

Post ur C/C++ Programs Here

hi there....if u want to fill an array with random numbers, one can simply use rand() function na...and if at all u need to have upper limit over the range of value,rand()%UPPERLIMIT, does it...and still if u want to have different numbers(without repetition), with some trade off between time and space,define an array like,
Code:
int array[MAX]; //where MAX is upper limit....
//then
while(count<=reqCount)
  { 
     int c=rand();
     if(array[c%MAX]!=c%MAX)
       array[c%MAX]=c%MAX,count++;
  }
guess this does the required task..

cheers

Jove

Post ur C/C++ Programs Here

something like this will work?
Code:
#include <iostream>

using namespace std;

int main()
{
  int i, array[10],randomarray[10];
  cout<<"Enter 10 numbers in any order";
  for (i=0; i<10; i++) {cin>>array[i];randomarray[i]=0;}
  for (i=0;i<10;i++){
    int r=rand()*10;
    if(randomarray[r]<>0
      randomarray[r]=array[i];
    else
      i--;
    }
  for(i=0;i<10;i++) cout<<randomarray[i];
  }

ilugd

Post ur C/C++ Programs Here

Hmm.goto is an easy way to get from anywhere to anywhere in a program.But I guess it's always better to use break; to get outta loops.
As for the random numbers part, I think I wasn't vey clear in the first post.Suppose I have 5 fixed random values,say 1,3,8,3,7 and I want to put them in array, how would I do it.??rand() function will select any 5 random values generated from it's algorithm and fill them in array.That's not what I want ..

shady_inc

Post ur C/C++ Programs Here

Quote:
Originally Posted by shady_inc
Code:
#include <iostream>
using namespace std;
int main()
{ xyz:
  float asc[10],num,sub;
  int i,j,p;
  cout<<"Enter 10 numbers in any order:\n";
  for(i=0;i<10;i++)
  { cin>>asc[i];}
  cout<<"Enter the number to be searched:"<<endl;
  cin>>p;
  for(j=0;j<10;j++)
  { sub=asc[i]-p;
    if(sub==0)
    cout<<"The number is at"<<i<<"th position.";
    else
    cout<<"Number not found.";
    cin.get();
  } 
  goto xyz;
}
Pay attention to comparators

(BTW, why do TWO proceses to match an item? Just one check would do right? Why subtract to 0, and then deduct if its a right result or wrong, when you could just directly check input with each in the array and say the same?)

As for random numbers, use the cstdlib provided rand() and srand() functions to generate random numbers.

Code:
#include <cstdlib> 
#include <iostream>

using namespace std;

int main() 
{ 
    int random_integer = rand(); 
    int a[10];
    for (int i=0;i<10;i++)
        a[i]=rand();
    for (int i=0;i<10;i++)
        cout<<a[i]<<endl; 
    return 0;
}
Edit: Wait, I ran your code, its bad. Your logic is sorta flawed in the loops, check it. And please, never ever use goto.

Here, try this:
Code:
#include<iostream>

using namespace std;

int main()
{
	int a[10],i,j,check;
	
	cout<<"Enter 10 values: ";
	for (i=0;i<10;i++)
		cin>>a[i];
	
	cout<<"Enter the number to check: ";
	cin>>check;
	
	for (i=0;i<10;i++)
	{
		if(a[i]==check)
		{
			cout<<"Number found at "<<i+1<<"th position.";
			break;
		}
		else if(i==9)
			cout<<"Number not found.";
	}
	
	return 0;
}

QwertyManiac

Post ur C/C++ Programs Here

Is there any way to fill an array with random numbers using loops.??For example if I have to write table of 7 the program wll be:

int i,array[10];
for(i=0;i<10;i++)
{ array[i]=i*7+7;}

But this will print out multiples of seven.What if I want to fill the array with random numbers like 4,77,665,34 etc.??Is adding each data to array the only option here.??

Also, why is this program not working.??

Code:
#include <iostream>
using namespace std;
int main()
{ xyz:
  float asc[10],num,sub;
  int i,j,p;
  cout<<"Enter 10 numbers in any order:\n";
  for(i=0;i<10;i++)
  { cin>>asc[i];}
  cout<<"Enter the number to be searched:"<<endl;
  cin>>p;
  for(j=0;j<10;j++)
  { sub=asc[i]-p;
    if(sub=0)
    cout<<"The number is at"<<i<<"th position.";
    else
    cout<<"Number not found.";
    cin.get();
  } 
  goto xyz;
}

shady_inc

Post ur C/C++ Programs Here

I forgot this thread... anyway nice discussion going on

Gigacore

Post ur C/C++ Programs Here

Guys pls post some simple games developed in c\c++ ......

i need it for my Software engineering lab....

pls guys help me out

arun_cool

Post ur C/C++ Programs Here

Quote:
please this is urgent as i have to submit a project in school
Thanks for saving us the trouble of finding out if it was homework...

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by Sykora
Thanks for saving us the trouble of finding out if it was homework...
amen

T159

Post ur C/C++ Programs Here

^ thanks buddy.

i'll try it

Gigacore

Post ur C/C++ Programs Here

its gcc buddy
gcc is a c compiler and g++ is a c++ comiler
trust me, its something awesome. try it and feel its real strength.

in TurboC++ compiler, color scheme is decided by textcolor in text mode.......if in graphics mode, settextstyle is used.

set the logic according to the output and use the above functions. i think it will do the job

timemachine

Post ur C/C++ Programs Here

how to use different colors for different letters, while the program is executed.
for example, if i input GIGACORE, it should show all those each every letters in the word GIGACORE with different colors

Gigacore

Post ur C/C++ Programs Here

Yeah got that

QwertyManiac

Post ur C/C++ Programs Here

and which is the best C compiler for linux platform. i've heard about GC++ or something that sounds like that. is it good?

Gigacore

Post ur C/C++ Programs Here

In linux you can use command line ANSI escape sequences, I don't know about windows though.

Sykora

Post ur C/C++ Programs Here

It isn't sticky yet

I don't want this as sticky, cause no one would look at it then, as is the case with most stickies. I'd rather vote for a new Programming section

QwertyManiac

Post ur C/C++ Programs Here

Quote:
Originally Posted by srikanth.9849671439
3)print the numbers in pyramid shape.......
1
2 2
3 3 3
4 4 4 4
I dont know how to do the first 2 and the 4th one. Here is the answer to the 3rd:
Code:
#include <stdio.h>
#include <conio.h>

void main()
{
 int i,j;
 for(i=1;i<=4;i++)
  {
    for(j=1;j<=i;j++)
    printf("%d\t" , i);
    printf("\n");
  }
 getch();
}

nvidia

Post ur C/C++ Programs Here

Quote:
Originally Posted by sandeep9796
hmmmmmmmmmm

i m tryin to make and application tht will generate a listin of files in a directory and display them????

anyone knows how to do it???
I guess this should help http://minnie.tuhs.org/UnixTree/V7/u.../cmd/ls.c.html

mehulved

Post ur C/C++ Programs Here

hmmmmmmmmmm

i m tryin to make and application tht will generate a listin of files in a directory and display them????

anyone knows how to do it???

sandeep9796

Post ur C/C++ Programs Here

Yeah PyShell is there too, but its sort of weak at its work. Don't use it as a replacement for bash!

QwertyManiac

Post ur C/C++ Programs Here

1)wrap such that the oupput should be az,by,cx,dw.........................
2)wrap such that the oup put should be 1+10,2+9,3+8..........5+6
3)print the numbers in pyramid shape.......
1
2 2
3 3 3
4 4 4 4
4) print
y
z y z
r z y z r
z y z
y

srikanth.9849671439

Post ur C/C++ Programs Here

Or use python

mehulved

Post ur C/C++ Programs Here

Python loaded with os module (>>> import os) would be great, run bash and python commands together from within the python shell

QwertyManiac

Post ur C/C++ Programs Here

But using the output of shell commands within python is moderately difficult. Although the os module does give you the tools, it takes some time to learn them. (os.popen)

It's a long time since I used a "calculator" app. python with ipython shell is bliss. So is sage.

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by [xubz]
I'd hate to open up the Calculator App (especially in Linux).
You can use the bash math commands like bc, it supports floating point calculations.

Use bc filename if you have the math expressions stored in a file line by line.

Or use bc <enter> to enter the interactive mode.

Or even use echo expression | bc to pipe it to bc without a file or interaction.

Don't forget to use man bc or info bc

The other bash commands I know of are dc (reverse polish calculator) and factor (splits a number to its factors).

I think there's also a package for scientific calculation via CLI, its called wcalc.

QwertyManiac

Post ur C/C++ Programs Here

I dunno if it has Linux-haters or Linux-illiterates, and puttin in Linux won't help. We have enough dumb teachers anyway

Nav11aug

Post ur C/C++ Programs Here

did anyone try the turbo calc ?

i've prob with my compiler..

Gigacore

Post ur C/C++ Programs Here

A Command Line Calculator.

I coded this because sometimes if I quickly wanted to multiply/divide some numbers, I'd hate to open up the Calculator App (especially in Linux).

Just cal 2 + 2 or cal 100 / 39 would throw up the result. Much Better

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

int main(int argc, char *argv[])
{
	float a, b;
	char op;

	if (argc < 4 || argc > 4)
	{
		printf("\nUsage: cal <number1> <operator> <number2>\n");
		printf("\nValid Expressions: + - * /\n");
		printf("\nExample: cal 2 + 2\n");
		exit(1);
	}

	/* Store the Command Line Arguments in Local Variables */
	a = atof(argv[1]);
	b = atof(argv[3]);
	op = *argv[2];

	switch(op)
	{
		case '+':
			printf("\n%f", (float)a+b);
			break;

		case '-':
			printf("\n%f", (float)a-b);
			break;

		case '*':
			printf("\n%f", (float)a*b);
			break;

		case '/':
			printf("\n%f", (float)a/b);
			break;

		default:
			printf("\nInvalid Operator");
			break;
	}

	printf("\n");
	return(0);
}
Tested to compile and work using GCC under Linux

[xubz]

Post ur C/C++ Programs Here

It worked now for me in Dev C++.. nice program.. keep it up!

Gigacore

Post ur C/C++ Programs Here

Quote:
You can use Switch-Case instead of Insane no if nested-if for just validating a single number
know it... but I still prefer if clause...

Quote:
It worked now for me in Dev C++.. nice program.. keep it up!
nice program? isn't this supposed to be a n00bish bit of code?(what else can you expect from a cbse programmer?)

MetalheadGautham

Post ur C/C++ Programs Here

Quote:
Originally Posted by Gigacore
did anyone try the turbo calc ?

i've prob with my compiler..
Working Fine here.

Used Borland C++ 5.5 and VIM (heh, I use vim even in windows ^_^)

@MetalheadGautham -> You can use Switch-Case instead of Insane no if nested-if for just validating a single number

[xubz]

Post ur C/C++ Programs Here

Anyone here running a 64bit OS who can try that out and tell us what size their int is?

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by The_Devil_Himself
yea man dev c++ looks more geeky(hence cool).Lols.dev c++ is light on resources and thats very important for a IDE.
Quote:
Originally Posted by Zeeshan Quireshi
dud then u seriously need to use Visual C++ Express or Eclipse . You'll forget DevC++ after using them .

Download Visual C++ 2005 Express Here [FREE]:
http://msdn2.microsoft.com/hi-in/express/aa700735.aspx

or you can down Eclipse C++ Developer Pack Here [FREE}:
http://www.eclipse.org/downloads/

The only problem with Eclipse is , t does not Bundle a Compiler with it . so you need to Install GCC(MinGW or Cygwin or DJGPP on Windows) before installing it and then configure it to use ur Installation of GCC , whereas Visual C++ 2005 Express bundles everything into a neat package .
or try netbeans

http://www.netbeans.org/products/cplusplus/

Desi-Tek.com

Post ur C/C++ Programs Here

Quote:
Originally Posted by Sykora
So it would seem. We'll only be able to tell if you run the same thing on TC++.
Well TC++ Generates 16 Bit Executables , so it's Int n Floats would be Half the size of a Present Day 32 Bit Compiler , so in short this code should not work in TC++

Quote:
Originally Posted by QwertyManiac
So TC++'s int is short int, guess that solves the issue.
Yups , Int on a 16 Bit System is Equal to Short on a 32 Bit System .

Zeeshan Quireshi

Post ur C/C++ Programs Here

So it would seem. We'll only be able to tell if you run the same thing on TC++.

Sykora

Post ur C/C++ Programs Here

I don't have that but here's anomit's screen-shot of it running in TC++:



So TC++'s int is short int, guess that solves the issue.

QwertyManiac

Post ur C/C++ Programs Here

got this:
Code:
Data Type               Size            Minimum                 Maximum
char                    1               -128                    127
short int               2               -32768                  32767
int                     4               -2147483648             2147483647
long int                4               -2147483648             2147483647
unsigned char           1               0                       255
unsigned short          2               0                       65535
unsigned int            4               0                       4294967295
unsigned long           4               0                       4294967295

The_Devil_Himself

Post ur C/C++ Programs Here

Am getting the same:
Code:
Data Type               Size            Minimum                 Maximum
char                    1               -128                    127
short int               2               -32768                  32767
int                     4               -2147483648             2147483647
long int                4               -2147483648             2147483647
unsigned char           1               0                       255
unsigned short          2               0                       65535
unsigned int            4               0                       4294967295
unsigned long           4               0                       4294967295
So my educational system is at fault?

QwertyManiac

Post ur C/C++ Programs Here

Qwerty, compile and run this code, and tell me what you get.

Code:
#include <iostream>
#include <limits>

using namespace std;

int main () {
	cout << "Data Type\t\tSize\t\tMinimum\t\t\tMaximum\n";
	cout << "char\t\t\t" << sizeof(char) << "\t\t" << CHAR_MIN << "\t\t\t" << CHAR_MAX << endl;
	cout << "short int\t\t" << sizeof(short int) << "\t\t" << SHRT_MIN << "\t\t\t" <<  SHRT_MAX << endl;
	cout << "int\t\t\t" << sizeof(int) << "\t\t" << INT_MIN << "\t\t" << INT_MAX << endl;
	cout << "long int\t\t" << sizeof(long int) << "\t\t" << LONG_MIN << "\t\t" << LONG_MAX << endl;
	cout << "unsigned char\t\t" << sizeof(unsigned char) << "\t\t" << '0' << "\t\t\t" << UCHAR_MAX << endl; 
	cout << "unsigned short\t\t" << sizeof(unsigned short) << "\t\t" << '0' << "\t\t\t" << USHRT_MAX << endl;
	cout << "unsigned int\t\t" << sizeof(unsigned int) << "\t\t" << '0' << "\t\t\t" << UINT_MAX << endl; 
	cout << "unsigned long\t\t" << sizeof(unsigned long) << "\t\t" << '0' << "\t\t\t" << ULONG_MAX << endl;
	return 0;
}
You're right, I'm getting the same values for INT_MAX and LONG_MAX. 32767 is for SHRT_MAX.

Sykora

Post ur C/C++ Programs Here

If you're that into Binary operations, you ought to be writing a class for binary numbers and overloading their operators. If you go that way, there's all sorts of cool things you can do. But that's in C++/Java/Python/Some other OO language.

If you want to stick with C, it is possible to write arithmetic functions over strings, but its slightly cumbersome.

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by aditya.shevade
I don't think that the 40th number might be above integer range.
Yes its odd, an int actually displays numbers even upto the 47th Fibonacci value

A sample output from the program below:
Code:
38: 24157817
39: 39088169
40: 63245986
41: 102334155
42: 165580141
43: 267914296
44: 433494437
45: 701408733
46: 1134903170
47: 1836311903
48: -1323752223 (Goes wrong here onwards)
All this through an Integer variable whose max size is supposed to be 32768?! Or is it some kind of a clever compiler behavior, etc?

Here's the code which did the above:
Code:
#include<iostream>

using namespace std;

int main()
{
    int prev=0, fib=0, final=1;
    cout<<"1: "<<prev<<endl<<"2: "<<final<<endl;
    for(int i=0;i<=97;i++)
    {
        fib=final+prev;
        prev = final;
        final = fib;
        cout<<i+3<<": "<<fib<<endl;
    }
    cout<<endl<<"Final: "<<fib<<endl;
    return 0;
}
Doing the same with float yeilds right values upto 100, which would be the obvious way to do so correctly:
Code:
#include<iostream>

using namespace std;

int main()
{
    float prev=0, fib=0, final=1;
    cout.precision(30);
    cout<<"1: "<<prev<<endl<<"2: "<<final<<endl;
    for(int i=0;i<=97;i++)
    {
        fib=final+prev;
        prev = final;
        final = fib;
        cout<<i+3<<": "<<fib<<endl;
    }
    cout<<endl<<"Final: "<<fib<<endl;
    return 0;
}
Oddly, using long int results in the same execution as int itself, with numbers crapping out at 48th value and above.

QwertyManiac

Post ur C/C++ Programs Here

^thats true but what if we are required to first covert 2 decimal no. into binary and then do some arithmatic calculation and then convert the result back to decimal?

The_Devil_Himself

Post ur C/C++ Programs Here

You're better off writing the output binary number to a string rather than an int with digits 0 and 1. That way you'll be able to handle numbers above 31. Right now, the maximum binary number you can store is 11111, which is 31. Above that, and you'll get a wrap around.

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by Sykora
^^^ Are you asking how to calculate up to the 40th, because you're unable to reach past 20? If that's the case, declare your variables as unsigned long, and then try it.
I don't think that the 40th number might be above integer range.

aditya.shevade

Post ur C/C++ Programs Here

[b] A C Program to convert decimal number to its Binary Number Equivalent

Code:
#include <stdio.h>
#include<conio.h>
void main()
{
	auto	int	dec, bin;
	int	dec_to_bin (int);
	printf("Enter a decimal number \n");
	scanf("%d", &dec);
	bin = dec_to_bin (dec);
	printf("The decimal number is = %d \n", dec);
	printf("The binary number is = %d \n", bin);
}
/*	Funtion to find the binary equivalent	*/
int	dec_to_bin (int d)
{
	auto	int	b,r,k;
		b=0;
		k=0;
		while(d>0)
		{
			r = d % 2;
			d = d / 2;
			b = b + r * k;
			k = k * 10;
		}
		return (b);
getch();
}

Gigacore

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!

QwertyManiac

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??

Abhishek Dwivedi

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.

The_Devil_Himself

Post ur C/C++ Programs Here

^^ You can press Alt+F5 to view results after the execution of program.

Quiz_Master

Post ur C/C++ Programs Here

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

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

send email through gmail smtp in jsp
http://desi-tek.org/blog/2007/09/01/...mail-smtp.html

reusable postgresql database connection class
Quote:
/**
*
*/
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?

Quote:
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 :)

Desi-Tek.com

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

QwertyManiac

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

aditya.shevade

Post ur C/C++ Programs Here

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

praka123

Post ur C/C++ Programs Here

Quote:
Originally Posted by aditya.shevade
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??

shady_inc

Post ur C/C++ Programs Here

^^ cool, working

Gigacore

Post ur C/C++ Programs Here

Heh I can read that but just in case he wants something specific.

A program combining all 3 he's asked is already present here.

QwertyManiac

Post ur C/C++ Programs Here

now thats cool!

Gigacore

Post ur C/C++ Programs Here

How can we write a program (any program) without writing anything in main() ???

shyamno

Post ur C/C++ Programs Here

@ QWERTY.... he needs some programs using STRINGS, stuctures...etc

Gigacore

Post ur C/C++ Programs Here

@ QWERTY... its working thanks a lot.....

And thanks for other guys who involved in help

Gigacore

Post ur C/C++ Programs Here

Yeah and they both are unavailable in Standard C/C++, so it's always suggested to stay away from them. Why don't you run your programs via CMD instead? That'll show the output and still stay alive.

QwertyManiac

Post ur C/C++ Programs Here

@New, What sort of programs and in C or C++ ?

QwertyManiac

Post ur C/C++ Programs Here

U peoples are doing good work.
Buy the way can anyone send some programs on pointers , strings and structurs?
I have internal next week.before that i have to prepare for these three chapters..
Please...
Thanks in advance..

New

Post ur C/C++ Programs Here

Quote:
Originally Posted by The_Devil_Himself
Yep you need to include conio.h for getch and clrscr to work.Try out man both getch and clrscr are very handy.
Hmm.... maybe handy, but they cause the program to become non-portable. (At least, entire portability is not achieved). You cannot compile those programs on machines not running borland compiler.

Aditya

aditya.shevade

Post ur C/C++ Programs Here

Yep you need to include conio.h for getch and clrscr to work.Try out man both getch and clrscr are very handy.

The_Devil_Himself

Post ur C/C++ Programs Here

Can u show me how to add that (where to add)?

Gigacore

Post ur C/C++ Programs Here

Code:
#include <stdio.h>
#include<conio.h>
void main()
{
	int a [100]; /* Array Declaration */
	int i,n,max,mini;
	printf("Enter number of elements in the array");
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	max=a[0];
	mini=a[0];
	for(i=1;i<n;i++)
	{
		if(max<a[i])max=a[i];
		if(mini>a[i])mini=a[i];
	}
	printf("\nMaximum element in the array is %d",max);
	printf("\nMinimum element in the array is %d",mini);
getch();
}
This is the 'Turbo C' version of your program, you need to include conio.h and use getch() at the LAST line.

QwertyManiac

Post ur C/C++ Programs Here

A C program to find the maximum and minimum elements in an array having N elements

Code:
#include <stdio.h>
main()
{
	int a [100]; /* Array Declaration */
	int i,n,max,mini;
	printf("Enter number of elements in the array");
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	max=a[0];
	mini=a[0];
	for(i=1;i<n;i++)
	{
		if(max<a[i])max=a[i];
		if(mini>a[i])mini=a[i];
	}
	printf("\nMaximum element in the array is %d",max);
	printf("\nMinimum element in the array is %d",mini);
return 0;
}

Gigacore

Post ur C/C++ Programs Here

Good one gigacore.But it exits without showing result in turbo c++.BTW why do you hate getch() to much?

The_Devil_Himself

Post ur C/C++ Programs Here

Hope this is not a old news ;
Introduction to C++ - Stanford Video Tutorials and Other Lectures

Updated September 15, 2007




Here are some of the best rated videos on C++. The first set 5 video tutorials is from reconnetworks.com. The next set of 13 lectures from Stanford University is much more in-depth. The lecture at the end is by Dr. Bjarne Stroustrup - the original designer and implementer of the C++ Programming Language.
link to the videos:
http://idealprogrammer.com/languages...ther-lectures/

got this via http://linuxhelp.blogspot.com/2007/0...deos-on-c.html (ofcorz not my blog!)

praka123

Post ur C/C++ Programs Here

Can anybody write a C program to reverse the contents of a SINGLE Linked list?

nithinks

Post ur C/C++ Programs Here

ya man
but its a problem for all programmers
they all are aggressive

timemachine

Post ur C/C++ Programs Here

leave it dude.......just go for straight discussions... no one is targeting nobody here

timemachine

Post ur C/C++ Programs Here

Quote:
Originally Posted by aditya.shevade
I know. I said, I am not targeting you but I am targeting those who do not use standard C. You are not included in that. Cool down.
, arre i'm totally Calm n Composed , was just telling ya bout RHIDE .

Zeeshan Quireshi

Post ur C/C++ Programs Here

Quote:
Originally Posted by Zeeshan Quireshi
Dud , i'm totally for Standard C++ , that's why i said that RHIDE has a TC like Interface but uses GCC as backend therefore it is a 'Standard C++' development environment , but with the look and feel like TC
I know. I said, I am not targeting you but I am targeting those who do not use standard C. You are not included in that. Cool down.

aditya.shevade

Post ur C/C++ Programs Here

Honestly Speaking this is going to be my fevorite thread ever on Digit forum...
BookMarked...
[Its very usefull for a BCA 3rd Sem student of a small town and thats me.. ]

OK, let me post my Today's Homework here..hehe...

Write a C Program to sort numbers of an Array using Bubble Sort Method.

Code:
#include <stdio.h>
#define MAX 10
void swap(int *x,int *y)
{
   int temp;
   temp = *x;
   *x = *y;
   *y = temp;
}
void bsort(int list[], int n)
{
   int i,j;
   for(i=0;i<(n-1);i++)
      for(j=0;j<(n-(i+1));j++)
             if(list[j] > list[j+1])
                    swap(&list[j],&list[j+1]);
}
void readlist(int list[],int n)
{
   int i;
   printf("Enter the elements\n");
   for(i=0;i<n;i++)
       scanf("%d",&list[i]);
}

void printlist(int list[],int n)
{
   int i;
   printf("The elements of the list are: \n");
   for(i=0;i<n;i++)
      printf("%d\t",list[i]);
}

void main()
{
   int list[MAX], n;
   printf("Enter the number of elements in the list max = 10\n");
   scanf("%d",&n);
   readlist(list,n);
   printf("The list before sorting is:\n");
   printlist(list,n);
   bsort(list,n);
   printf("The list after sorting is:\n");
   printlist(list,n);
}
Quote:
Originally Posted by Intel_Gigacore
^ theres nothing in Hint
There IS..
Just Highlight the post.

Quiz_Master

Post ur C/C++ Programs Here

I'm using borland Turbo C++, whenever i execute a program, it runs and closes suddenly... it happens in Dev C++ also.. please help

Gigacore

Post ur C/C++ Programs Here

@yamraj : what was wrong with my prog?? it seemed to run perfectly fine

xbonez

Post ur C/C++ Programs Here

Quote:
Originally Posted by xbonez
@yamraj : what was wrong with my prog?? it seemed to run perfectly fine
Using implementation dependent libraries and functions like clrscr(), and the nonstandard "void main()" violates the rules of the ISO C++ standard. Your executable may run fine on a system, but your code needs more love.

I recommend a decent and recent C++ book, like C++: How To Program, C++ Primer, 4th/e or C++ Primer Plus.

Yamaraj

Post ur C/C++ Programs Here

Quote:
Originally Posted by xbonez
hmm, u use Oxford and Sumita Arora's textbook for C++. they're our course books in XI and XII
I find books by Yashavant Kanetkar the best ones for C/C++.

shady_inc

Post ur C/C++ Programs Here

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");
                                
                        }
                }
        }

QwertyManiac

Post ur C/C++ Programs Here

Quote:
Originally Posted by Intel_Gigacore
use /* before the coment
....and */ after the comment.

can someone tell me what's wrong in this program.Using Dev C++

Quote:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{ /*Use of Function*/
float a,b,sum;
float calsum(float a,float b);
cout<<"Enter the two nos.:\n";
cin>>a>>b;
sum=calsum(a,b);
cout<<"The sum is :"<<sum<<"";
}
calsum(float a,float b)
{ float sum;
sum=a+b;
return (sum);
}

shady_inc

Post ur C/C++ Programs Here

lol... why doesn't thinkdigit have a programming section?

ilugd

Post ur C/C++ Programs Here

Quote:
Originally Posted by Yamaraj
Using implementation dependent libraries and functions like clrscr(), and the nonstandard "void main()" violates the rules of the ISO C++ standard. Your executable may run fine on a system, but your code needs more love.

I recommend a decent and recent C++ book, like C++: How To Program, C++ Primer, 4th/e or C++ Primer Plus.
hmm, u use Oxford and Sumita Arora's textbook for C++. they're our course books in XI and XII

xbonez

Post ur C/C++ Programs Here

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

Sykora

Post ur C/C++ Programs Here

Quote:
Originally Posted by swap_too_fast
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;
}

xbonez

Post ur C/C++ Programs Here

Quote:
Originally Posted by Sykora
@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.

QwertyManiac

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).

The_Devil_Himself

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.

Sykora

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();
	
}

aditya.shevade

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'

QwertyManiac

Post ur C/C++ Programs Here

Quote:
Originally Posted by QwertyManiac
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..

swap_too_fast

 0 1 2 3 4
Previous Question:  Kcron doesnNext Question:  Where is my ACPI Uniprocessor driver?  MSI HQ User to User Forum    null

- Source: Post ur C/C++ Programs Here Digit Forum Programming
- Previous Question: Kcron doesn't work Digit Forum Open Source
- Next Question: Where is my ACPI Uniprocessor driver? MSI HQ User to User Forum null