# Post your C/C++ Programs Here



## Gigacore (Sep 2, 2007)

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 nested if*


```
#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 nested 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.
● TURBO CALC 15000
● A Command Line Calculator.
● Function 2 input a matrix
● Read an int & an int array & search for that int in the int array & return its position.
● Python version of the above program.
● Program to perform operations on a binary search tree.
● Program to calculate the computer sales man salary. (Correction)
● Basic Inventory tracker software program code.
● Sudoku
 ● Simple DOS Text-based alien shooter game
 ● A program for unit conversions.

===========================================
*Last Update: 12 August 2008
--------------------------------------------------------

Some good free C/C++ Compilers*

● Relo 
● Bloodshed Dev C++ 
● GCC 
● Borland C++ 5.5 
● MinGW
● Open Watcom


----------



## xbonez (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

*here's a prog to calc area, surface area, volume, total surface area etc. of numerous 2D and 3D figures using functions*

i had made this one for a friend - it was his project


```
#include<iostream.h>
#include<conio.h>
#include<math.h>

void line(void);
void cuboid(void);
void cube(void);
void cylinder(void);
void cone(void);
void sphere(void);
void hemisphere(void);
void triangle(void);
void rectangle(void);
void square(void);
void circle(void);
void parallelogram(void);

void main()
{
	clrscr();
	int o1,o2;

	menu:
	do{
		clrscr();
		cout<<"\n\n1. 3-D Figures"
		    <<"\n\n2. Plane Figures"
		    <<"\n\n3. Exit"
		    <<"\n\nEnter your choice -->\t";
		cin>>o1;

		switch(o1)
		{
			case 1:         clrscr();
					cout<<"\n\n";
					line();
					cout<<"\n\t\t\t\t3-D Figures\n\n";
					line();
					cout<<"\n\n1. Cuboid"
					    <<"\n\n2. Cube"
					    <<"\n\n3. Cylinder"
					    <<"\n\n4. Cone"
					    <<"\n\n5. Sphere"
					    <<"\n\n6. Hemisphere"
					    <<"\n\n7. Main Menu"
					    <<"\n\nEnter your choice -->\t";
					    cin>>o2;

					    switch(o2)
					    {
						case 1:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tCuboid\n\n";
								line();
								cuboid();
								getch();
								break;

						case 2:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tCube\n\n";
								line();
								cube();
								getch();
								break;

						case 3:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tCylinder\n\n";
								line();
								cylinder();
								getch();
								break;

						case 4:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tCone\n\n";
								line();
								cone();
								getch();
								break;

						case 5:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tSphere\n\n";
								line();
								sphere();
								getch();
								break;

						case 6:		clrscr();
								cout<<"\n\n";
								line();
								cout<<"\n\t\t\t\tHemisphere\n\n";
								line();
								hemisphere();
								getch();
								break;

						case 7:		goto menu;


						default:	cout<<"\n\nInvalid Input\a\a\a";
								goto menu;
					    }
					    getch();
					    break;

			case 2:		    clrscr();
					    cout<<"\n\n";
					    line();
					    cout<<"\n\t\t\t\tPlane Figures\n\n";
					    line();
					    cout<<"\n\n1. Traingle"
						<<"\n\n2. Rectangle"
						<<"\n\n3. Sqaure"
						<<"\n\n4. Circle"
						<<"\n\n5. Parallelogram"
						<<"\n\n6. Main Menu"
						<<"\n\nEnter your choice -->\t";
					    cin>>o2;

					    switch(o2)
					    {
							case 1:		clrscr();
									cout<<"\n\n";
									line();
									cout<<"\n\t\t\t\tTraingle\n\n";
									line();
									triangle();
									getch();
									break;

							case 2:		clrscr();
									cout<<"\n\n";
									line();
									cout<<"\n\t\t\t\tRectangle\n\n";
									line();
									rectangle();
									getch();
									break;

							case 3:        	clrscr();
									cout<<"\n\n";
									line();
									cout<<"\n\t\t\t\tSquare\n\n";
									line();
									square();
									getch();
									break;

							case 4:		clrscr();
									cout<<"\n\n";
									line();
									cout<<"\n\t\t\t\tCircle\n\n";
									line();
									circle();
									getch();
									break;

							case 5:		clrscr();
									cout<<"\n\n";
									line();
									cout<<"\n\t\t\t\tParallelogram\n\n";
									line();
									parallelogram();
									getch();
									break;

							case 6:		goto menu;


							default:	cout<<"\n\nInvalid Input\a\a\a";
									goto menu;
					    }

					    getch();
					    break;

			case 3:             cout<<"\n\nPress any key to exit...\a";
					    getch();
					    break;

			default:	    cout<<"\n\nInvalid Input\a\a\a\a";
					    goto menu;



		}

	}while(o1!=3);

}


void line()
{
	int i;
	for (i=0;i<80;i++)
		cout<<"*";
}

void cuboid()
{
	float l,b,h,a,v;
	cout<<"\n\nEnter length of cuboid -->\t";
	cin>>l;
	cout<<"\n\nEnter breadth of cuboid -->\t";
	cin>>b;
	cout<<"\n\nEnter height of cuboid -->\t";
	cin>>h;
	v=l*b*h;
	a=2*(l*b+b*h+l*h);
	cout<<"\n\nVolume of cuboid is "<<v;
	cout<<"\n\nSurface area of cuboid is "<<a;
}

void cube()
{
	float l,a,v;
	cout<<"\n\nEnter length of side of cube -->\t";
	cin>>l;
	v=l*l*l;
	a=6*l*l;
	cout<<"\n\nVolume of cube is "<<v;
	cout<<"\n\nSurface area of cube is "<<a;
}

void cylinder()
{
	float r,h,v,c,t;
	cout<<"\n\nEnter radius of cylinder -->\t";
	cin>>r;
	cout<<"\n\nEnter height of cylinder -->\t";
	cin>>h;
	v=3.14*r*r*h;
	c=2*3.14*r*h;
	t=3.14*r*(2*h+r);
	cout<<"\n\nVolume of cylinder is "<<v;
	cout<<"\n\nCurved Surface Area of cylinder is "<<c;
	cout<<"\n\nTotal Surface Area of cylinder is "<<t;
}

void cone()
{
	float r,h,l,v,c,t;
	cout<<"\n\nEnter radius of cone -->\t";
	cin>>r;
	cout<<"\n\nEnter height of cone -->\t";
	cin>>h;
	l=sqrt(r*r+h*h);
	v=(3.14*r*r*h)/3;
	c=3.14*r*l;
	t=3.14*r*(l+r);
	cout<<"\n\nSlant height of cone is "<<l;
	cout<<"\n\nVolume of cone is "<<v;
	cout<<"\n\nCurved Surface Area of cone is "<<c;
	cout<<"\n\nTotal Surface Area of cone is "<<t;
}

void sphere()
{
	float r,v,a;
	cout<<"\n\nEnter radius of sphere -->\t";
	cin>>r;
	v=(4*3.14*r*r*r)/3;
	a=4+3.14*r*r;
	cout<<"\n\nVolume of sphere is "<<v;
	cout<<"\n\nSurface Area of sphere is "<<a;
}

void hemisphere()
{
	float r,v,c,t;
	cout<<"\n\nEnter radius of hemisphere -->\t";
	cin>>r;
	v=(2*3.14*r*r*r)/3;
	c=2*3.14*r*r;
	t=3*3.14*r*r;
	cout<<"\n\nVolume of hemisphere is "<<v;
	cout<<"\n\nCurved Surface Area of hemisphere is "<<c;
	cout<<"\n\nTotal Surface Area of hemisphere is "<<t;
}

void triangle()
{
	float b,h,a;

	cout<<"\n\nEnter base of triangle -->\t";
	cin>>b;
	cout<<"\n\nEnter height of triangle -->\t";
	cin>>h;

	a=(b*h)/2;
	cout<<"\n\nArea of the triangle is "<<a;

}

void rectangle()
{
	float l,b,a,p;
	cout<<"\n\nEnter length of rectangle -->\t";
	cin>>l;
	cout<<"\n\nEnter breadth of rectangle -->\t";
	cin>>b;
	a=l*b;
	p=2*(l+b);
	cout<<"\n\nArea of rectangle is "<<a;
	cout<<"\n\nPerimeter of rectangle is "<<p;
}

void square()
{
	float s,a,p;
	cout<<"\n\nEnter length of side of square -->\t";
	cin>>s;
	a=s*s;
	p=4*s;
	cout<<"\n\nArea of square is "<<a;
	cout<<"\n\nPerimeter of square is "<<p;
}

void circle()
{
	float r,a,c;
	cout<<"\n\nEnter radius of circle -->\t";
	cin>>r;
	a=3.14*r*r;
	c=2*3.14*r;
	cout<<"\n\nArea of circle is "<<a;
	cout<<"\n\nCircumference of circle is "<<c;
}

void parallelogram()
{
	float b,h,a,p;
	cout<<"\n\nEnter base of parallelogram -->\t";
	cin>>b;
	cout<<"\n\nEnter height of parallelogram -->\t";
	cin>>h;
	a=b*h;
	p=2*(b+h);
	cout<<"\n\nArea of parallelogram is "<<a;
	cout<<"\n\nPerimeter of parallelogram is "<<p;
}
```

i've put up a lot more progs at my forum. classmates really find it useful since none of them is interested in computers. its so sad...


----------



## max_demon (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

My Program to calculate Addition


```
#include <stdlib.h>
main()
{
float a,b,c,total,multiply,add,input;
printf("Welcome to Demon Calculator \n\n");
printf("Enter the values-\n\n");
printf("a:");
scanf("%f",&a);
printf("b:");
scanf("%f",&b);
printf("c:");
scanf("%f",&c);

total=a*b*c;
if (total>80000)
printf("Meri Marzi , tu khud solve kar.\a\a\a\a\a\a\a\a\a\n\n");
else
printf("The answer is %f\n\n\a\a",total);
system("pause");
}
```


----------



## Ron (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

scanf("%d%d%d",&a,&b,&c);
New to c++.......Whta those this line means


----------



## Yamaraj (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Intel_Gigacore said:
			
		

> ```
> #include <stdio.h>
> main()
> {
> ...


Your program lacks proper braces and a return statement.



			
				xbonez said:
			
		

> *here's a prog to calc area, surface area, volume, total surface area etc. of numerous 2D and 3D figures using functions*
> 
> i had made this one for a friend - it was his project
> 
> ...


Your code doesn't conform to either ISO C or C++ standards.



			
				Ron said:
			
		

> scanf("%d%d%d",&a,&b,&c);
> New to c++.......Whta those this line means


scanf() is a C input function, which is considered unsafe except for formatted data. I advise learning C first, before opting for a much larger, bloated and complex language as C++.


----------



## fun2sh (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

+no the program is correct dude


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

i added the return statement, is it rite now?


----------



## Pathik (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Ron said:
			
		

> scanf("%d%d%d",&a,&b,&c);
> New to c++.......Whta those this line means


y r u using scanf in c++???


----------



## QwertyManiac (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Yamaraj said:
			
		

> Your code doesn't conform to either ISO C or C++ standards.



Don't be so hard on him  He doesn't know TC++'s evils 

Anyway, here's xbonez's program in proper code 


```
#include<iostream>
#include<math.h>

using namespace std;

void line(void);
void cuboid(void);
void cube(void);
void cylinder(void);
void cone(void);
void sphere(void);
void hemisphere(void);
void triangle(void);
void rectangle(void);
void square(void);
void circle(void);
void parallelogram(void);

int main()
{ 
    int o1,o2;
    do{
         
        cout<<"\n\n1. 3-D Figures"
            <<"\n\n2. Plane Figures"
            <<"\n\n3. Exit"
            <<"\n\nEnter your choice -->\t";
        cin>>o1;

        switch(o1)
        {
            case 1:         cout<<"\n\n";
                    line();
                    cout<<"\n\t\t\t\t3-D Figures\n\n";
                    line();
                    cout<<"\n\n1. Cuboid"
                        <<"\n\n2. Cube"
                        <<"\n\n3. Cylinder"
                        <<"\n\n4. Cone"
                        <<"\n\n5. Sphere"
                        <<"\n\n6. Hemisphere"
                        <<"\n\n7. Main Menu"
                        <<"\n\nEnter your choice -->\t";
                        cin>>o2;
                        switch(o2)
                        {
                        case 1:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tCuboid\n\n";
                                line();
                                cuboid();
                                
                                break;

                        case 2:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tCube\n\n";
                                line();
                                cube();
                                
                                break;

                        case 3:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tCylinder\n\n";
                                line();
                                cylinder();
                                
                                break;

                        case 4:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tCone\n\n";
                                line();
                                cone();
                                break;

                        case 5:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tSphere\n\n";
                                line();
                                sphere();
                                break;

                        case 6:        cout<<"\n\n";
                                line();
                                cout<<"\n\t\t\t\tHemisphere\n\n";
                                line();
                                hemisphere();
                                break;

                        case 7:        break;


                        default:    cout<<"\n\nInvalid Input\a\a\a";
                        }
                        
                        break;

            case 2:            
                        cout<<"\n\n";
                        line();
                        cout<<"\n\t\t\t\tPlane Figures\n\n";
                        line();
                        cout<<"\n\n1. Traingle"
                        <<"\n\n2. Rectangle"
                        <<"\n\n3. Sqaure"
                        <<"\n\n4. Circle"
                        <<"\n\n5. Parallelogram"
                        <<"\n\n6. Main Menu"
                        <<"\n\nEnter your choice -->\t";
                        cin>>o2;

                        switch(o2)
                        {
                            case 1:        cout<<"\n\n";
                                    line();
                                    cout<<"\n\t\t\t\tTraingle\n\n";
                                    line();
                                    triangle();
                                    
                                    break;

                            case 2:        cout<<"\n\n";
                                    line();
                                    cout<<"\n\t\t\t\tRectangle\n\n";
                                    line();
                                    rectangle();
                                    
                                    break;

                            case 3:         cout<<"\n\n";
                                    line();
                                    cout<<"\n\t\t\t\tSquare\n\n";
                                    line();
                                    square();
                                    
                                    break;

                            case 4:        cout<<"\n\n";
                                    line();
                                    cout<<"\n\t\t\t\tCircle\n\n";
                                    line();
                                    circle();
                                    break;

                            case 5:        cout<<"\n\n";
                                    line();
                                    cout<<"\n\t\t\t\tParallelogram\n\n";
                                    line();
                                    parallelogram();
                                    break;

                            case 6:        break;


                            default:    cout<<"\n\nInvalid Input\a\a\a";
                        }

                        break;

            case 3:             cout<<"\n\nPress any key to exit...\a";
                        break;

            default:        cout<<"\n\nInvalid Input\a\a\a\a";



        }

    }while(o1!=3);
return 0;
}


void line()
{
    int i;
    for (i=0;i<80;i++)
        cout<<"*";
}

void cuboid()
{
    float l,b,h,a,v;
    cout<<"\n\nEnter length of cuboid -->\t";
    cin>>l;
    cout<<"\n\nEnter breadth of cuboid -->\t";
    cin>>b;
    cout<<"\n\nEnter height of cuboid -->\t";
    cin>>h;
    v=l*b*h;
    a=2*(l*b+b*h+l*h);
    cout<<"\n\nVolume of cuboid is "<<v;
    cout<<"\n\nSurface area of cuboid is "<<a;
}

void cube()
{
    float l,a,v;
    cout<<"\n\nEnter length of side of cube -->\t";
    cin>>l;
    v=l*l*l;
    a=6*l*l;
    cout<<"\n\nVolume of cube is "<<v;
    cout<<"\n\nSurface area of cube is "<<a;
}

void cylinder()
{
    float r,h,v,c,t;
    cout<<"\n\nEnter radius of cylinder -->\t";
    cin>>r;
    cout<<"\n\nEnter height of cylinder -->\t";
    cin>>h;
    v=3.14*r*r*h;
    c=2*3.14*r*h;
    t=3.14*r*(2*h+r);
    cout<<"\n\nVolume of cylinder is "<<v;
    cout<<"\n\nCurved Surface Area of cylinder is "<<c;
    cout<<"\n\nTotal Surface Area of cylinder is "<<t;
}

void cone()
{
    float r,h,l,v,c,t;
    cout<<"\n\nEnter radius of cone -->\t";
    cin>>r;
    cout<<"\n\nEnter height of cone -->\t";
    cin>>h;
    l=sqrt(r*r+h*h);
    v=(3.14*r*r*h)/3;
    c=3.14*r*l;
    t=3.14*r*(l+r);
    cout<<"\n\nSlant height of cone is "<<l;
    cout<<"\n\nVolume of cone is "<<v;
    cout<<"\n\nCurved Surface Area of cone is "<<c;
    cout<<"\n\nTotal Surface Area of cone is "<<t;
}

void sphere()
{
    float r,v,a;
    cout<<"\n\nEnter radius of sphere -->\t";
    cin>>r;
    v=(4*3.14*r*r*r)/3;
    a=4+3.14*r*r;
    cout<<"\n\nVolume of sphere is "<<v;
    cout<<"\n\nSurface Area of sphere is "<<a;
}

void hemisphere()
{
    float r,v,c,t;
    cout<<"\n\nEnter radius of hemisphere -->\t";
    cin>>r;
    v=(2*3.14*r*r*r)/3;
    c=2*3.14*r*r;
    t=3*3.14*r*r;
    cout<<"\n\nVolume of hemisphere is "<<v;
    cout<<"\n\nCurved Surface Area of hemisphere is "<<c;
    cout<<"\n\nTotal Surface Area of hemisphere is "<<t;
}

void triangle()
{
    float b,h,a;

    cout<<"\n\nEnter base of triangle -->\t";
    cin>>b;
    cout<<"\n\nEnter height of triangle -->\t";
    cin>>h;

    a=(b*h)/2;
    cout<<"\n\nArea of the triangle is "<<a;

}

void rectangle()
{
    float l,b,a,p;
    cout<<"\n\nEnter length of rectangle -->\t";
    cin>>l;
    cout<<"\n\nEnter breadth of rectangle -->\t";
    cin>>b;
    a=l*b;
    p=2*(l+b);
    cout<<"\n\nArea of rectangle is "<<a;
    cout<<"\n\nPerimeter of rectangle is "<<p;
}

void square()
{
    float s,a,p;
    cout<<"\n\nEnter length of side of square -->\t";
    cin>>s;
    a=s*s;
    p=4*s;
    cout<<"\n\nArea of square is "<<a;
    cout<<"\n\nPerimeter of square is "<<p;
}

void circle()
{
    float r,a,c;
    cout<<"\n\nEnter radius of circle -->\t";
    cin>>r;
    a=3.14*r*r;
    c=2*3.14*r;
    cout<<"\n\nArea of circle is "<<a;
    cout<<"\n\nCircumference of circle is "<<c;
}

void parallelogram()
{
    float b,h,a,p;
    cout<<"\n\nEnter base of parallelogram -->\t";
    cin>>b;
    cout<<"\n\nEnter height of parallelogram -->\t";
    cin>>h;
    a=b*h;
    p=2*(b+h);
    cout<<"\n\nArea of parallelogram is "<<a;
    cout<<"\n\nPerimeter of parallelogram is "<<p;
}
```


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

Guys... is my program rite now?


----------



## Yamaraj (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Intel_Gigacore said:
			
		

> Guys... is my program rite now?


Try this:

```
#include <stdio.h>

int main(void)
{	
   int a = 0,
       b = 0,
       c = 0,
       greatest = 0;

   printf("Enter three numbers:\n");
   scanf("%d %d %d", &a, &b, &c);

   greatest = a;
   if(b > greatest)
      greatest = b;
   if(c > greatest)
      greatest = c;

   printf("greatest of %d, %d and %d = %d", a, b, c, greatest);
   return 0;
}
```


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

^ thanks buddy......


----------



## utsav (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

this is a program in which u will hav 2 enter any 5 nos between 1 to 49 and if the number matches with the numbers chosen by the computer, u will win the lottery




#include <cstdlib>
#include <iostream>
using namespace std;
void lotto();
void calc(int * a, int * b);
void menu();
// Main function. Seeds random function 
//     and calls menu function.
int main()


    {
    srand((unsigned)time(0));	// Seed the random function......
    menu();
}
// This function prompts the user to pic
//     k five numbers between 1 and 49.
// The function makes sure that the user
//     picks numbers between 1 and 49,
// and that the user does not choose dup
//     licate numbers. Then the computer 
// chooses five random numbers. Error co
//     ntrol is used to check if the 
// computer chooses the same number twic
//     e. Then the numbers are displayed
// to the screen. Finally the calc funct
//     ion is called to calculate and
// output the results of the game...
void lotto()


    {
    int i, k, j, b, x, y;// variables for all the for loops....
    int s, t, user_error;
    int user[5], comp[5];// arrays for user and computers numbers....
    int user_error_check, comp_error_check; // to find if numbers are duplicates....
    // Prompt user to choose numbers
    cout << "Please choose five numbers from 0 to 49" << endl;
    for (i=0; i<5; i++)


        {
        cout << "Enter number " << i + 1 << ":" ;
        cin >> user_; 
        if (user > 49 || user < 0)


            {
            cout << "You did not enter a number from 0 to 49" << endl;
            i--;
        }

    }
    // ERROR CONTROL, to make sure that the 
    //     user does not choose the
    // same number twice.................
    for(s=0; s<5; s++)
    for(t=0; t<s; t++)


        {
        user_error_check = user;
        if(user_error_check == user[t])


            {
            cout << "You have chosen duplicate numbers, please choose another number: " << endl;
            cin >> user_error;
            user = user_error;
        }
    }

    // Now the computer chooses numbers.....
    //     ........
    for (k=0; k<5; k++)


        {
        comp[k] = (rand( ) % 49) + 1; // get comp to randomly generate 1 -49
    }
    // ERROR CONTROL, to make sure that the 
    //     computer does not pick
    // the same number twice.......

    for(x=0; x<5; x++)
    for(y=0; y<x; y++)


        {
        comp_error_check = comp[x];
        if (comp_error_check == comp[y])


            {
            comp[x] = (rand() % 49) + 1;
        }
    } // no guarentee that the computer will not choose another number
    // already in the array, but it's the be
    //     st i can do?????

    cout << "You chose: " ;// output users numbers...
    for (j=0; j<5; j++)


        	{
        cout << user[j] << ", " ;
    }

    cout << endl;

    cout << "The computer chose: "; // output computers numbers...
    for (b=0; b<5; b++)


        {
        cout << comp* << ", " ;
    }
    cout << endl << endl;

    calc(user, comp);// Obtain the results of the game......
}
// This function compares the computers 
//     random numbers to the numbers
// chosen by the user and lets the user 
//     know how many (if any) they
// have matched..............
void calc(int * a, int * b)


    {
    int i, k, match =0;
    for (i=0; i<5; i++)
    for (k=0; k<5; k++)
    if ( a == b[k] )


        {
        match += 1;
        cout << "You have matched: " << a << endl;
    }
    if (match == 0)


        {
        cout << "Sorry you have not matched any of the computers numbers..."
        	 << endl << endl;
    }
    if (match == 5)


        {
        cout << "CONGRATULATIONS, YOU HAVE WON THE LOTTERY!!!!!!!" << endl << endl;
    }
} 
// This function informs the user how to
//     play the game and then allows
// the user to play the game until they 
//     enter 'q' or 'Q' at the prompt.
void menu()


    {
    char choice;
    cout << endl;
    cout << "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << endl;
    cout << "$(C)$" << endl;
    cout << "$ $" << endl;
    cout << "$ *The computer will randomly choose five numbers $" << endl;
    cout << "$ between 1 and 49.$" << endl;
    cout << "$ $" << endl;
    cout << "$ *You can choose five numbers and try to match$" << endl;
    cout << "$ the computers numbers...... $" << endl;
    cout << "$ $" << endl;
    cout << "$ **Do not pick the same number twice or pick a$" << endl;
    cout << "$number less than 1 or greater than 49, o.k.?$" << endl;
    cout << "$ $" << endl;
    cout << "$ $" << endl;
    cout << "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << endl;
    cout << endl;
    while (choice != 'q' || choice != 'Q')


        {

        cout << "Make a selection from the menu: " << endl;
        cout << "[P]- Play the clotto against the computer." << endl;
        cout << "[Q]- Exit this program." << endl;
        cin >> choice;
        switch(choice)


            {
            case 'p':
            case 'P':
            lotto();
            break;
            case 'q':
            case 'Q':
            cout << "No lotto for you!" << endl;
            exit(0);
            break;
        }
    }
}*_


----------



## ratedrsuperstar (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

^^this is totally wrong what if b>c>gr8test there's no condition to test that

use this thread to request programs and then pm to the requester rather than posting so much code over here it really looks a mess and these are quite basic too


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

@ utsav... did it execute buddy?


----------



## Yamaraj (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				ratedrsuperstar said:
			
		

> ^^this is totally wrong what if b>c>gr8test there's no condition to test that


Rules of programming:
1. Read the fscking code. And mine is pretty readable.
2. Test it before complaining.
3. If you still don't get it, it's time to buy a decent C book.


----------



## xbonez (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Yamaraj (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				xbonez said:
			
		

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


----------



## utsav (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Sykora (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

*Program To Reverse a Number*



> #include <stdio.h>
> main()
> {
> long rev, n, num;
> ...


----------



## mehulved (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

And how about using comments in the code so people like me could understand it faster and better.


----------



## utsav (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

^^ i hav used comments in my program


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

use /* before the coment


----------



## shady_inc (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Intel_Gigacore said:
			
		

> use /* before the coment



....and */ after the comment.

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



> #include <iostream>
> #include <conio.h>
> using namespace std;
> int main()
> ...


----------



## ilugd (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## xbonez (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Yamaraj said:
			
		

> 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


----------



## shady_inc (Sep 2, 2007)

*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



I find books by Yashavant Kanetkar the best ones for C/C++.


----------



## Sykora (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

@shady_inc :
conio.h is non-standard.
Your calsum() doesn't have a forward declaration. Put main() after calsum() or put the line :

```
int calsum(float, float);
```
before main().


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

does any know how to write this one? 

*Write a program using functions to find whether the given number is a prime number?*


----------



## ilugd (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

do an iteration from 2 to int(n/2) and if it isn't divisible then it is prime.


----------



## Yamaraj (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				xbonez said:
			
		

> hmm, u use Oxford and Sumita Arora's textbook for C++.


Who told you that? I recommend what I use - Lafore's, Prata's, Lippman's and Stroustrup's.


----------



## Gigacore (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

thanks ilugd i'll try it


----------



## xbonez (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*

sorry, i meant to say *I* use those books...typo *83.149.99.14/forums/style_emoticons/DarksideRG/blush2.gif


----------



## QwertyManiac (Sep 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				shady_inc said:
			
		

> ....and */ after the comment.
> 
> can someone tell me what's wrong in this program.Using Dev C++


Either Sykora's solution or simply add a float to your function definition line:


```
#include <iostream>
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<<"";
        
    return 0;
}

[B] float[/B] calsum(float a,float b)
{ 
    float sum;
    
        sum=a+b;
        
    return (sum);
}
```


----------



## Nav11aug (Sep 3, 2007)

*Re: Post ur C/C++ Programs Here*



			
				ilugd said:
			
		

> do an iteration from 2 to int(n/2) and if it isn't divisible then it is prime.



bad math funda  .. iterate from 2 to (int)sqrt(n) ..if it isnt divisible then itz prime



			
				Yamaraj said:
			
		

> Who told you that? I recommend what I use - Lafore's, Prata's, Lippman's and Stroustrup's.



How to Program in C++ by Deitel and Deitel is good too



			
				shady_inc said:
			
		

> I find books by Yashavant Kanetkar the best ones for C/C++.



And as far as Kanetkar is concerned ... when I was inmy 11/12th I thought so too. But now,  u jst mature. Those books feel like being fed with a spoon. 

They do contain a *LOT* of funda though


----------



## ilugd (Sep 3, 2007)

*Re: Post ur C/C++ Programs Here*

i got 33% in my math exams during my bachelor's degree. Don't know how i lost it. Got 98% in +2 though. Come to think of it, I was socializing, eating and drinking the whole 3 years in BCA (if you know what I mean).


----------



## Nav11aug (Sep 3, 2007)

*Re: Post ur C/C++ Programs Here*

lol yeah... socializing => lookin fr bandis??


----------



## QwertyManiac (Sep 3, 2007)

*Re: 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 ..


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


----------



## Gigacore (Sep 3, 2007)

*Re: Post ur C/C++ Programs Here*

^^ cool, working


----------



## swap_too_fast (Sep 3, 2007)

*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 ..
> 
> 
> ```
> ...



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


----------



## QwertyManiac (Sep 3, 2007)

*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 (Sep 3, 2007)

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


----------



## king khan (Sep 6, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## QwertyManiac (Sep 6, 2007)

*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


----------



## The_Devil_Himself (Sep 6, 2007)

*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 (Sep 6, 2007)

*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 


```
#/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 (Sep 6, 2007)

*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


```
/*  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 (Sep 6, 2007)

*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 (Sep 6, 2007)

*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, 

```
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 (Sep 6, 2007)

*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,
> 
> ...



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 (Sep 6, 2007)

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


----------



## xbonez (Sep 6, 2007)

*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


```
#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 (Sep 6, 2007)

*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;
> ...


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


----------



## praka123 (Sep 6, 2007)

*Re: 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


----------



## shady_inc (Sep 6, 2007)

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



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


----------



## aditya.shevade (Sep 7, 2007)

*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 
	
	



```
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 (Sep 8, 2007)

*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 (Sep 8, 2007)

*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 (Sep 8, 2007)

*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!


----------



## Gigacore (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

^ Ya its very difficult


----------



## mavihs (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

can u guys give me a site where i can reffere about c++ & get some solution. & i got this a prob with a question i hav. if u guys can solve it or give a hint or anything.
here it is:-

WAP to display th following format on the screen.(using loop)  

```
[CENTER][CENTER]1
1   1   1
1   1   1   1   1
1   1   1   1   1   1   1[/CENTER]
  [/CENTER]
```

plzzzzzzz give the ans or atleast some hint or somthing. I got an exam on monday. i hav 2 prepare for it. i can't understand these question how 2 do. plzzzzz help! i've been trying 2 figure it out for a week. it may come for my exam. plzzzz help!!!!!!


----------



## Gigacore (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

Try this:

```
#include <stdio.h>
main()
{
	int	row, col, t, i;
	int	tab=40;
	for(row = 1; row <= 7; row++)
	{
		for (t = 1; t <= tab; t++) printf(" ");
		/* number if blank spaces from left edge of the screen */
		for(col = 1;col <= row; col++)
			printf("%d ",row);
		printf("\n");
		tab--;
	}
return 0;
}
```

For C++ tutors...: *www.cprogramming.com/tutorial.html


----------



## Projjwal (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

do u know wht's the output of following prog
 

#include<stdio.h>
#include<conio.h>
void main()
{
int c;
c=printf("abc");
printf("\n%d",c);
getch();
}
Don't run it. Just guess it's output . & why?


----------



## QwertyManiac (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Intel_Gigacore said:
			
		

> Try this:
> 
> ```
> #include <stdio.h>
> ...


 He needed just 1s and in odd quantities only.  Good write up though


----------



## ilugd (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

what does printf return by the way? a return value or some pointer? It would take a minute to google that but I guess that would be cheating.


----------



## QwertyManiac (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*



			
				ilugd said:
			
		

> what does printf return by the way? a return value or some pointer? It would take a minute to google that but I guess that would be cheating.



I think it returns an int. I've seen int in its prototype for sure. But I got no clue what the output of Projjwal's program's gotta be.


----------



## Projjwal (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

hint:





try it bro....u r partially correct ..It's the value which printf return..But wht is that value.? I give up the ans is
abc
3


----------



## Gigacore (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

^ theres nothing in Hint


----------



## Quiz_Master (Sep 9, 2007)

*Re: 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.*


```
#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);
}
```



			
				Intel_Gigacore said:
			
		

> ^ theres nothing in Hint



There IS..
Just Highlight the post.


----------



## Projjwal (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

yea just highlight my previous post or just press "ctrl+ A ".Actually printf is a function with return type integer .Just open stdio.h file from include directory frm there u will got that. And it returns the length of string which it print.so as a result 
c=printf("abc") 
means printf return value 3 Which saved in C integer variable thats all.


----------



## Gigacore (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

Cool Projjwal, thanks Quiz Master


----------



## Projjwal (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

So,everybody of the forum know swapping  using 3rd variable & without 3rd variable .now write a swapping program in c without 3rd variable & de vital point is use one line function only .
means
b=a+b;
a=b-a;
b=b-a;
---------------de above program has 3 functional  lines now write it in one functional line.


----------



## The_Devil_Himself (Sep 9, 2007)

*Re: Post ur C/C++ Programs Here*

^^eh..how do we do that?


----------



## aditya.shevade (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

Easy. Check this out.


```
#include<iostream>

using namespace std;

main()
{
	int a, b;
	
	cout << "Enter A and B" << endl;
	cout << "a = ";
	cin >> a;
	cout << endl << "b = ";	
	cin >> b;
	
	a = ((b - a) + (b = a));
	
	cout << endl << "a = " << a << endl;
	cout << "b = " << b;
	
	return 0;
	
}
```

EDIT : Output :-


```
EXECUTING:
/home/aditya/test 
----------------------------------------------
Enter A and B
a = 12

b = 23

a = 23
b = 12
----------------------------------------------
Program exited successfully with errcode (0)
Press the Enter key to close this terminal ...
```


----------



## Nav11aug (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

^^ better algo than the one given..

11 @aditya.shevade


----------



## Gigacore (Sep 10, 2007)

*Re: 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


----------



## Quiz_Master (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Desi-Tek.com (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

reusable java class to send email through pop3


```
/*
 * 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();

	}

}
```


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Intel_Gigacore said:
			
		

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


----------



## Nav11aug (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

I think he means that he cant see the output, nt terminating in the middle of smthin. Program completes execution and closes window


----------



## Projjwal (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

@aditya.shevade It's very cool ans.Gr8 job ...I was just looking for this ans.
Now do the same thing without using "()" .

use Bitwise Operators
--------------------------------------------------------------
#include<stdio.h>

#include<conio.h>
void main()
{
int a,b;
a=12;
b=25;
a=((b-a)+(b=a));
printf("\na:%d\nb:%d",a,b);
getch();
}

This is de C version of aditya.shevade run it.
-----------------------------------------------------------


----------



## Batistabomb (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

does anybody had c++ code for converting text to speech


----------



## Quiz_Master (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

^^^^ WHAT????
I dont think anyone here can do that.....

It will require a whole app to be coded not just a single C++ program.


----------



## Projjwal (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

@Batistabomb i think it's not so easy . U have to develop a C++ program with directX .So u have to know directX programming in other language like VB.NET,C#.net DirectX programming r easier then C++.


----------



## Batistabomb (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

dude what's the need for directx here i want code in windows environment through any API in c++,is any api's located for c++


----------



## quan chi (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

just fooling around with a simple program.
#include<iostream.h>
#include<conio.h>
void main()
{getch();
int n;
cout<<"enter a no between 1-3."<<endl;
cin>>n;
switch(n)
{case 1:
cout<<"you won!!"<<endl;
break;
case2:
cout<<"you lost!!"<<endl;
break;
case3:
cout<<"theres a tie "<<endl;
break;
default<<"please follow the above instructions."
break;
}
}


----------



## Batistabomb (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

guys i had a nice c++ turorial in a simple english if anyone needs i can send for your mails


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

That swapping thing cost me 6 marks in an exam last year (In C). The teacher refused to believe it works, and when I showed it in the lab, she said its not the right way to do it  People ..

@Batistabomb - Projjwal is right I guess, .Net would be the easiest way, using Microsoft's APIs. Anyway check these links, I got no idea how to use them though.

*www.microsoft.com/speech/speech2007/speechdevarticle.mspx

Same in wiki's language:
*en.wikipedia.org/wiki/Speech_Application_Programming_Interface


----------



## Nav11aug (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> That swapping thing cost me 6 marks in an exam last year (In C). The teacher refused to believe it works, and when I showed it in the lab, she said its not the right way to do it  People ..



nthn surprisin.. people(especially teachers) dnt appreciate the smart ways of doin things.. got many marks cut when in school fr using KeyB shrtcuts everywhere in Office (


----------



## The_Devil_Himself (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

I couldn't agree more.In many a cases students are way smarter than teachers.Today my Data structure was asking "hey how do we change resolution in linux(red hat)?" and I was laughing like hell.

Hey guys(and gals of course) don't you think this thread should be made a sticky?The starter please start a poll man--sticky or not sticky.


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

Here's something useful with respect to this thread.

* This program creates a vB list out of a file given in a particular format.*

The *format* should be:

Title 1
URL 1
Title 2
URL 2

And the *output* file's content will be the vB code for the following:

*
List Title​ *
 Title 1
 Title 2
Would be helpful for those maintaining List threads. And it'd be good if Intel_Gigacore maintains it for this thread too.

Am uploading an example file along, which contains the list for this thread.

And here's the code. Briefly Documented.

* Edit:* Code removed as the tags inside were getting converted. 
Code's attached as *digit.txt*.


```
Download digit.txt below to view code. 
You can rename it to digit.cpp. 
Sorry for the inconvenience
```
Note: You might find an extra LIST tag at the end of the file but that's cause of the editors. The editors place an extra line at EOF, so can't help it.
I can add a lot of BACKSPACE characters but that's just stupid. So till I find another workaround, this is the code.

* title.txt* is the input test file.
* digitout.txt* is the test output file.
* digit.txt* is the code file. Rename it to *digit.cpp* to get syntax highlighting.

* digitout.txt* when pasted here, will look like:

*Programs*​
 Biggest of 3 Numbers.
 Area, Surface Area (SA), Volume, Total SA, etc. of Various 2D and 3D Figures.
 Simple Random Number Lottery.
 Reverse a Number.
 Simple Stack Implementation using Linked Lists.
 Simple Bulls and Cows game.
 Binary, Decimal, Octal Interconversion.
 Simple Incremental Pyramid.
 Sorting of Numbers using Bubble Sort.
 Swapping of two numbers without a Temporary variable in 1 line.
 Simple Switch-Case Example.
Attachments below:


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

And here's a sample run. Forgot to add it to the earlier post.


```
harsh@qwerty-workstation:~$ ./digit.out 

Digit Forum URL Bulleted List Generator
-------------------------------------

Version 1.0

The Input file must be in the format of Title first and URL next.

Example:
Title1
*URL 1
Title 2
*URL 2

And so on..

Enter the input file's location and name to convert: title
Enter the output file's location and name to store into: digitout
Enter the list name: Programs
harsh@qwerty-workstation:~$
```

This'd hopefully work in Windows as well. As I haven't added any OS-only code.


----------



## aditya.shevade (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Nav11aug said:
			
		

> ^^ better algo than the one given..
> 
> 11 @aditya.shevade



Uhh... better than one given where? Please explain what do you mean.



			
				Projjwal said:
			
		

> @aditya.shevade It's very cool ans.Gr8 job ...I was just looking for this ans.
> Now do the same thing without using "()" .
> 
> use Bitwise Operators
> ...



Alright... Will do that... Right now, gotta run for keyboard class (music).




			
				Projjwal said:
			
		

> This is de C version of aditya.shevade run it.



Oh.... I have a C version of myself now... Didn't know that one 

By the way. Had my C orals today. Mid Semester exams. Scored 23/25. Topped the batch of 20 . Orals of remaining 3 batches are still to be held. 

Aditya


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

Orals?  What are we supposed to do in Orals? 

Btw, swapping in Python is deadly easy 

*a,b=b,a*

That's it, swapped. 

Here's a running example:

```
harsh@qwerty-workstation:~$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=25
>>> b=10
>>> [B]a,b=b,a[/B]
>>> a
10
>>> b
25
>>> exit()
harsh@qwerty-workstation:~$
```


----------



## Nav11aug (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> Uhh... better than one given where? Please explain what do you mean.


better than 





			
				Projjwal said:
			
		

> b=a+b;
> a=b-a;
> b=b-a;
> ---------------de above program has 3 functional  lines now write it in one functional line.


the implementation did not use the line b=a+b.thz why i said "better"


----------



## Quiz_Master (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

Hey QWERTY.. That program in Post #92 is awesome man...
ThankQ Very Much for that....


----------



## Nav11aug (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> Hey guys(and gals of course) don't you think this thread should be made a sticky?The starter please start a poll man--sticky or not sticky.



Sticky now ..sweet


----------



## QwertyManiac (Sep 10, 2007)

*Re: 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


----------



## Quiz_Master (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

This was today's homework.

*Write a C program to find an element from an Array using Binary Search Method.*


```
#include <stdio.h>
#define M 10

void bsearch(int list[],int n,int element)
{
   int l,u,m, flag = 0;
   l = 0;
   u = n-1;
   while(l <= u)
   {
      m = (l+u)/2;
      if( list[m] == element)
      {
	       printf("The element whose value is %d is present at position %d in list\n",element,m);
                 flag =1;
                 break;
      }
      else
            if(list[m] < element)
                   l = m+1;
            else
                   u = m-1;
   }
   if( flag == 0)
   printf("The element whose value is %d is not present in the list\n",element);
}

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[M], n, element;
   printf("Enter the number of elements in the list max = 10\n");
   scanf("%d",&n);
   readlist(list,n);
   printf("\nThe list before sorting is:\n");
   printlist(list,n);
   printf("\nEnter the element to be searched\n");
   scanf("%d",&element);
   bsearch(list,n,element);
}
```

Couldn't test it as I am on Linux right now and Have no Compiler installed here.


----------



## QwertyManiac (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

Are you kidding me? If you'd said Windows I'd have understood the pain. But ... your linux has no compiler?  I wouldn't even use it then 

And we definitely need some sort of a syntax highlighter plugin if a new Programming section is being proposed.


----------



## Sykora (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



> Couldn't test it as I am on Linux right now and Have no Compiler installed here.



rofl.


----------



## aditya.shevade (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

^^ I wonder... Which distro do you use Ashwin?


----------



## zegulas (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

can u ppl plz give me the code to convert any decimal no into a binary no??
in C


----------



## mehulved (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Quiz_Master said:
			
		

> Couldn't test it as I am on Linux right now and Have no Compiler installed here.


 That's a weird statement. gcc is one of the foremost things that is needed to install my distro.


----------



## The_Devil_Himself (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				zegulas said:
			
		

> can u ppl plz give me the code to convert any decimal no into a binary no??
> in C



Check out previous posts in this thread it's alread been posted by someone.


----------



## aditya.shevade (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Projjwal said:
			
		

> @aditya.shevade It's very cool ans.Gr8 job ...I was just looking for this ans.
> Now do the same thing without using "()" .



I tried to do it using bitwise operators, as per your hint. But could not ..... Maybe I am too tired today. Will try it later tonight and see. You please don't post the answer. 

(To others, I just told Projjwal , not to post answer. Not to rest of you..... Just in case...)

Aditya


----------



## Zeeshan Quireshi (Sep 10, 2007)

*Re: Post ur C/C++ Programs Here*

GCC is *not* included in the default install of Ubuntu btw 



			
				Batistabomb said:
			
		

> does anybody had c++ code for converting text to speech


 you mean someting like this ?

```
using System;
using System.Speech.Synthesis;

namespace HelloSpeechSynthesis
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            synth.SpeakText("Hello, world!");
        }
    }
}
```

It's in C# though


----------



## quan chi (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*

well is it possible to program the matrix(the falling numbers in the movie) type programming using c++.


----------



## Nav11aug (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*

@The Binary Search program

doesn't wrk and note tht binary search is only fr sorted arrays


----------



## Yamaraj (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> I tried to do it using bitwise operators, as per your hint. But could not ..... Maybe I am too tired today. Will try it later tonight and see. You please don't post the answer.
> 
> (To others, I just told Projjwal , not to post answer. Not to rest of you..... Just in case...)
> 
> Aditya


Temptation. It's here :- *a^=b^=a^=b*


----------



## Gigacore (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*

@ qwerty, cool programs, and actually the program executes but it, think u enter some values to perform the given task. it does but that dos window will close before showing the output. but when i run it again, i can see the output. help


----------



## Quiz_Master (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> ^^ I wonder... Which distro do you use Ashwin?



Dyne;bolic, custom edition..... [I am not into linux though... My studies require me to stick with Windows.]

Just found a module for programming though...
Now going to use it.



			
				Intel_Gigacore said:
			
		

> @ qwerty, cool programs, and actually the program executes but it, think u enter some values to perform the given task. it does but that dos window will close before showing the output. but when i run it again, i can see the output. help



Arre yaar.. read what I previously written...
You will need to press Alt+F5 to view result...
Alternatevly use getch() function just before the end of program (just before "}" , you will need to include 'stdio.h' file in C++ program for this.)

Hope you get me this time.


----------



## Nav11aug (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Quiz_Master said:
			
		

> Alternatevly use getch() function just before the end of program (just before "}" , you will need to include 'stdio.h' file in C++ program for this.)



getch() needs conio.h ,getchar() needs stdio.h


----------



## aditya.shevade (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Yamaraj said:
			
		

> Temptation. It's here :- *a^=b^=a^=b*



I had given up. So I checked....

By the way, can you please explain the working of this? I have no experience whatsoever in bitwise operators  And I have a laptop, and the viewing angle was such that I was able to look at the answer without selecting it. 

But, digital logic.... I have quite some. So, at lest explain in a logical, if not precedence level manner.

I had no idea that you can use a^=b in C/C++ program.... 

Aditya


----------



## Zeeshan Quireshi (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> I had given up. So I checked....
> 
> By the way, can you please explain the working of this? I have no experience whatsoever in bitwise operators  And I have a laptop, and the viewing angle was such that I was able to look at the answer without selecting it.
> 
> ...


you should read "The Annotated C++ Reference Manual" by Stroustrup , it gives you really handy tips n tricks and advises you on Efficient Programming styles .


----------



## aditya.shevade (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Alright. Currently I just finished through that Balagurusamy book, skipping the template programming. The book is OK. Not too good.

So, I am reading professional C++ by Solter and Klepper. And I really like that book. It's upright professional as the title says. The way it explained classes when compared with Balagurusamy's explanation... Balagurusamy is not at all very good.


----------



## Projjwal (Sep 11, 2007)

*Re: Post ur C/C++ Programs Here*

@Yamaraj gr8 job 10out of 10

-----------
a^=b^=a^=b  is the answare
here ^= means bitwise XOR operation
I am describing it through an example .
Suppose a=12 ; b=32
Now,for bit wise operation convert it to binary 
So,
a=001100
b=100000
now,
in ' C' operation done on right to left direction 
So, start it from the right most side.
a^=b it's mean a=a^b   so, a=001100 XOR 100000 =101100 but the value of b unchanged b=100000
next part
b^=a  it's mean b=b^a so, b=100000 XOR  101100 =001100 now the value of a =101100
last part
a^=b  it's mean a=a^b   so, a=101100 XOR 001100=100000 now the value of  b=1100
Now the new value of a & b is
a = 100000 = 32 in decimal
b = 1100 =12 in decimal
--------------------The Full C code is---------------
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=12;
b=32;
a^=b^=a^=b ;
printf("\na=%d",a,);
printf("\nb=%d",b);
getch();
}
--------------------------------------------------
@Nav11aug
Not the look of program/algo says this program/algo is good this bad.
the complexity (time,space) of the program/algo decide which one is good & which one is bad.


----------



## aditya.shevade (Sep 12, 2007)

*Re: 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


----------



## Projjwal (Sep 12, 2007)

*Re: Post ur C/C++ Programs Here*

no not k map.XOR is exclusive or means for odd numbers of 1 out put is 1 & for even numbers of 1 output is 0.
now the logic is
1 xor 1=0 xor 1 =1
1 xor 0 =1 xor 1 = 0
0 xor 1 =1 xor 0 = 1
now
0 xor 1=1
1 xor 0 =1
1 xor 1 = 0
sum up formula: a xor b =answer xor a = b
and answer xor b = a
from the ^^ lines  u will get a logic that  answer of xor between two numbers & xor between answer  & any one of the number gives the other one . It's the main logic. so, if u define it in bitwise it will create the algo .

**Here I describe for 1 bit only this operation is happed for all the bit of the number .thats way swap done.


----------



## Nav11aug (Sep 12, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Projjwal said:
			
		

> @Nav11aug
> Not the look of program/algo says this program/algo is good this bad.
> the complexity (time,space) of the program/algo decide which one is good & which one is bad.



i do knw tht.. but in such a small program as this , the aesthetics cms in. jst look at the beauty of coding in tht single line *MASTERY*


----------



## aditya.shevade (Sep 12, 2007)

*Re: Post ur C/C++ Programs Here*

^^ I know what XOR is and the way it functions.

Got it now.

Aditya


----------



## Ankur Gupta (Sep 12, 2007)

*Re: Post ur C/C++ Programs Here*

Hey does anyone have a program to sort an character array alphabetically...
please post it asap


----------



## QwertyManiac (Sep 13, 2007)

*Re: Post ur C/C++ Programs Here*

Wrote this now:


```
#include<stdio.h>

int main()
    {
        char a[10]={'a','g','m','j','f','t','p','w','r','h'}, t;
        int i,j;
        
        for(i=0;i<10;i++)
        for(j=i+1;j<10;j++)
        if(a[i]>a[j])
            {
                t=a[i];
                a[i]=a[j];
                a[j]=t;
            }
        
        printf("Sorted array is: \n");
        for(i=0;i<10;i++)
        printf("%c",a[i]);
        
        return 0;
    }
```
You can modify the input as required.


----------



## Zeeshan Quireshi (Sep 13, 2007)

*Re: Post ur C/C++ Programs Here*



			
				ankurgupta.me said:
			
		

> Hey does anyone have a program to sort an character array alphabetically...
> please post it asap


It's supposed to be the same algorithm you use to sort an Integer Array , as Characters can Implicitly be cast into integers and compared


----------



## Ankur Gupta (Sep 13, 2007)

*Re: Post ur C/C++ Programs Here*

^^Yeah I too realized that and wrote the program myself and it works like a charm!!


----------



## jal_desai (Sep 13, 2007)

*Re: Post ur C/C++ Programs Here*

hello ppl, check out this program... it simulates the TOWER OF HANOI problem... just give the number of rings as the input and it will give u the TOTAL ALGORITHM about how to transfer all of them from one rod to the other using an intermediate rod... 

CODE:
*
#include<conio.h>
#include<iostream.h>
class tower
{
 int nodisk;
 char frmtwr,totwr,auxtwr;
 public:
	void hanoi(int,char,char,char);
};

void tower::hanoi(int nodisk,char frmtwr,char totwr,char auxtwr)
{
	if (nodisk==1)
	{
	cout<<"\nMove disk 1 from tower "<<frmtwr<<" to tower "<<totwr;
	return;
	}
	hanoi(nodisk-1,frmtwr,auxtwr,totwr);
	cout<<"\nMove disk "<<nodisk<<" from tower "<<frmtwr<<" to tower "<<totwr;
	hanoi(nodisk-1,auxtwr,totwr,frmtwr);
	return;
}

void main()
{
	int no;
	tower ob;
	clrscr();
	cout<<"\n\t\t\t\t--- Tower Of Hanoi ---\n";
	cout<<"\n\t\t\t--- (assuming towers X, Y & Z) ---\n";
	cout<<"\n\nEnter the number of disks: ";
	cin>>no;
	ob.hanoi(no,'X','Y','Z');
	cout<<"\n\nPress any key to continue...";
	getch();
}
*

Enjoy...


----------



## Nav11aug (Sep 13, 2007)

*Re: Post ur C/C++ Programs Here*

we had as our assignment to write a program to transfer n disks when there are p pegs ... not just 3


----------



## QwertyManiac (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

@jal_desai - Please use the available 
	
	



```
tags while posting code :)
```


----------



## Gigacore (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

I did it... its not working.... here i've captured a video... i didnt use the getch() and didnt execute the program using Alt+F5 in the video... but even after using it, its not working 

please download the attachment.. its a 2 MB file... but compressed to 33 KB


----------



## The_Devil_Himself (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

@off topic:The compression was great 2mb compressed to 33kb.wow


----------



## Gigacore (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

^ he he... ya.... that was what i was wondering


----------



## The_Devil_Himself (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

BTW what was the program supposed to do?Just input a array and then display its elements?


----------



## Gigacore (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

^ Na... the output window closes before displaying the output.


----------



## The_Devil_Himself (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

@Gigacore I don't know buddy what are you looking for but the following program worked for me.

```
#include<stdio.h>
#include<conio.h>
void main()
{int a[10];
int n;
printf("\n Enter the no. of elements in the array:");
scanf("%d",&n);
printf("\nEnter the elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
                  }
clrscr();                  
printf("\nArray elements are:\n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
                     }
printf("\n\nPrees any key to exit...");
getch();
}
```

Checked in turbo c++ IDE(ya ya ya I know how bad it is).


----------



## Gigacore (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*

Its ok buddy... now its working fine on 98 machine....


*A Simple C Program to read and print a one-dimensional array*


```
#include <stdio.h>
#include<conio.h>
void main()
{
	int a[10];
	int i,n;
	printf("\nEnter number of elements in the array:");
	scanf("%d",&n);
	printf("\nEnter the array elements\n");
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	printf("\nArray elements are\n");
	for(i=0;i<n;i++)
		printf("\t%d",a[i]);
return 0;
Getch()
}
```


----------



## QwertyManiac (Sep 14, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Gigacore said:
			
		

> Its ok buddy... now its working fine on 98 machine....


Hey, checked your video, your program would obviously close after the output cause of the *return 0;* specified there 

In case getch()/getchar() doesn't work out for you, simply put a lame *scanf* or *cin* function to halt the execution.


----------



## Nav11aug (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> Hey, checked your video, your program would obviously close after the output cause of the *return 0;* specified there
> 
> In case getch()/getchar() doesn't work out for you, simply put a lame *scanf* or *cin* function to halt the execution.


It is NOT because of the return 0; statement . The second statement works perfectly though... cmon guyz ..u shudve suggested tht already by now!!!A dumb scanf() is the way to go


----------



## Gigacore (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*

*C Program to find the largest element in an array and the position of its occurrence.*


```
#include <stdio.h>
#include <conip.h>
void main()
{
	int a[100];
	int largest,position,num,index;
	scanf("%d",&num);
	for(index=0;index<num;index++)
		scanf("%d",&a[index]);
	largest=a[0];
	position=0;
	for(index=1;index<num;index++)
	{
		if(largest<a[index])
		{
		largest = a[index];
		position=index;
		}
	}
	printf("Largest element in the array is %d \n", largest);
	printf("Largest element's position in the array %d\n", position+1);
	return 0;
Getch();
}
```


----------



## QwertyManiac (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Nav11aug said:
			
		

> It is NOT because of the return 0; statement . The second statement works perfectly though... cmon guyz ..u shudve suggested tht already by now!!!A dumb scanf() is the way to go


What I meant was the program returns and exits successfully, so if he executes it in its real environment - the terminal, it'll run just fine.


----------



## Gigacore (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*

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


```
#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;
```
}


----------



## The_Devil_Himself (Sep 15, 2007)

*Re: 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?


----------



## Gigacore (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## QwertyManiac (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*


```
#include <stdio.h>
[B]#include<conio.h>[/B]
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);
[B]getch();[/B]
}
```

This is the 'Turbo C' version of your program, you need to include conio.h and use getch() at the LAST line.


----------



## The_Devil_Himself (Sep 15, 2007)

*Re: 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.


----------



## aditya.shevade (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> 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


----------



## QwertyManiac (Sep 15, 2007)

*Re: 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.


----------



## Gigacore (Sep 15, 2007)

*Re: Post ur C/C++ Programs Here*

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

And thanks for other guys who involved in help


----------



## New (Sep 16, 2007)

*Re: 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..


----------



## QwertyManiac (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Gigacore (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## QwertyManiac (Sep 16, 2007)

*Re: 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.


----------



## Gigacore (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

now thats cool!


----------



## shyamno (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Gigacore (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

its not possible without main()


----------



## Sykora (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

Evidently it is possible in C++. I found about it only recently. It seems that static constructors execute before any other function in a program, so put everything in a static constructor and create a global object. Leave main() out.


----------



## The_Devil_Himself (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

Actually the program execution begins with main() so not possible without main().


----------



## shyamno (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

Can we write this ???? 

#define main() main(){printf("Hello World\n");}

main()


----------



## Sykora (Sep 16, 2007)

*Re: Post ur C/C++ Programs Here*

Yes.


----------



## New (Sep 17, 2007)

*Re: Post ur C/C++ Programs Here*

Friends i need programs in C on pointers ,strings and structures.. two days left for my internals  i don't want to read any books..instead i want some programs from you peoples..
one question.
What is global declaration?give one example?
If anyone has good notes on these three chapters please send.
THANKS IN ADVANCE..


----------



## QwertyManiac (Sep 17, 2007)

*Re: Post ur C/C++ Programs Here*

This ain't a passing area 

Anyway global declaration of a variable or function makes it available to be used throughout the program.

See the variable A in the following example:


```
#include<stdio.h>

int A=10;

void DispA()
      {
            printf("\nGlobal A used in DispA() = %d",A);

                  {
                        int A = 30;
                        printf("\nLocal A for DispA() = %d",A);
                  }
      }

int main()
      {
            printf("Global A = %d\n",A);
                  {
                        int A = 20;
                        printf("Local A for Main() = %d\n",A);
                  }
            DispA();
            return 0;
      }
```
Running the above would give you a clear example of what global declaration means.


----------



## ratedrsuperstar (Sep 17, 2007)

*Re: Post ur C/C++ Programs Here*

hey can anyone post a program to display this in c++

                                               A
                                              AB
                                             ABC
                                            ABCD
                                           ABCDE
sloping on both sides


& PASCAL'S triangle using for loops and without <iomanip.h> (if possible)


----------



## ilugd (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

find the length of the string and do a for loop from 1 to length and another from 1 to i in the first loop printing each character. When the inner loop completes, print a newline. Should work.

Just installed centos on friday and trying to get gcc to work. other wise would have posted the entire program. 

ok, got it working
checked and works

```
#include <iostream>
using namespace std;

int main()
{
  char str[255];
  cout<<"Enter the String ";
  cin>> str;
  for (int i=0; i<strlen(str); i++)
    {
      for (int j=0; j<=i; j++)
          cout<<str[j];
      cout<<endl;
      }

  cout<<str;
  return 0;
  }
```


----------



## Quiz_Master (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

Here is my todays Homework : (Just complted this late in night...uhmm... sorry morning... )
Its a fairly simple program... 

*This is a program which compare two strings, concatenate them and then gives the length of string.*


```
/* Program to compare, concatenate and get length of string by Ashwin */

#include<iostream.h>
#include<conio.h>
#include<string.h>
main()
{
   clrscr();
   [COLOR="Blue"]char[/COLOR] a[50],b[25];
   cout<<"Enter First String:=  ";
   cin>>a;
   cout<<"Enter Second String:=  ";
   cin>>b;
   [COLOR="#0000ff"]if[/COLOR] (strcmp(a, b) ==0)
   cout<<"Both Strings are same.\n";
   [COLOR="#0000ff"]else[/COLOR]
   cout<<"Both Strings are not same\n";
   strcat(a,b);
   cout<<"The Combined String Is:= "<<a;
   cout<<"\nThe length of string is:= "<<strlen(a);

   getch();
   [COLOR="#0000ff"]return[/COLOR] 0;
}
```

Thats it for now.... I know its very basic .... But maybe someone on this forum can use this for school homework. 
(And I am ashamed to say that they teach us all this in college level )


----------



## The_Devil_Himself (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

@ilugd dude whats that "using namespace std;" for.I have seen it a lot but don't know exacdtly what it does.


----------



## ilugd (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

do a google search for namespaces. It is like package in a few other languages. Most of c++ standard functions and classes belong to this. If i hadn't used that, i would have had to prefix each cin and cout call with std like std::cin and std::cout


----------



## aditya.shevade (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

In short :- It tells the compiler which function/var/stream to use.

If you define a function x and there is a function named x present in a library you are using, then compiler will not understand which x to call (if the defs are same). So you can tell the compiler using namespaces, about the function you wanna use.


----------



## ilugd (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

right. This explanation is definitely better. Now i know why parents of my friends pay me NOT to teach them.


----------



## The_Devil_Himself (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

got it.thanks guys.


----------



## nithinks (Sep 18, 2007)

*Program to kill a software /demo version expire in C*

Hi guys....

These code snippets written by me.. can make a program written C to expire after certain number of executions. Check this out.

This program is to create a software that expires after 15 executions (I like coding such programs) the technique I used is first program here creates a Encrypted counter file named VALIDITY.DAT in your C drive that contains the counter but nobody can read or modify that. 
I used 10 bit key for encryption here u can specify required number of executions and create the file


```
#include< stdio.h>
#include<conio.h>

void main()
{
int num_executions=15,decrypted=0,encrypted=0,i=0,digit=0;
int xor_bit[10];
int bin_num_executions[10];
int key[10]={'1','1','0','1','0','1','1','1','0','1'}; 
FILE *fp;
clrscr();
for(i=0;i<10;i++) //initialize array
{
bin_num_executions[i]=0;
xor_bit[i]=0;
}
//////////////////////////////////////////////////////
i=9;
do //converting to binary, the number of executions 
{
digit=num_executions%2;
bin_num_executions[i]=digit;
i--;
num_executions=num_executions/2;
}while(num_executions!=0);
for(i=0;i<10;i++)
{
printf("%d",bin_num_executions[i]); 
}
//////////////////////////////////////////////////////
//bitwise xoring,writing to file begins here

printf("\n");
for(i=0;i<10;i++)
{
bin_num_executions[i]=bin_num_executions[i]^key[i]; 
if(bin_num_executions[i]==48)
{
xor_bit[i]=0;
}
else
{
xor_bit[i]=1;
}
}//for loop ends here

fp=fopen("C:\\validity.dat","w"); //writing to a file
for(i=0;i<10;i++) 
{
printf("%d",xor_bit[i]);
//fprintf(fp,"%d",xor_bit[i]);
}
fwrite(xor_bit,sizeof(int),10,fp);
fclose(fp);

// printf("\nInitial key %d\n",num_executions);
// printf("Encrypted %d",encrypted); 
getch();
}
```
this code is for our software which reads the encrypted file, decrypts it and decreases the counter then updates file encrypted

```
#include<stdio.h>
#include<conio.h>
#include<math.h>
int validate()
{
int init_counter[10],cnt,n; 
int i,k=9;
int product=1;
int bin_num_executions[10],xor_bit[10],digit;
int totl=0;
int total_copy=0;
int key[10]={'1','1','0','1','0','1','1','1','0','1'}; 
FILE *fp;
for(i=0;i<10;i++) //initializer
{
init_counter[i]=0;
bin_num_executions[i]=0;
xor_bit[i]=0;
}

fp=fopen("C:\\validity.dat","r");
fread(init_counter,sizeof(int),10,fp); 
fclose(fp);
//decoding
for(i=0;i<10;i++)
{
init_counter[i]=init_counter[i]^key[i];
if(init_counter[i]==48)
{
init_counter[i]=0;
}
else
{
init_counter[i]=1;
}
}
//converting binary init_counter to decimal
for(i=0;i<10;i++)
{
totl=totl+(init_counter[i]*pow(2,k));
k--;
}
totl=totl-1; //reduce counter
total_copy=totl;
/////////////////////////////////////////////////////////////// 
//updating to the file

i=9;
do //converting to binary, the number of executions
{
digit=totl%2;
bin_num_executions[i]=digit;
i--;
totl=totl/2;
}while(totl!=0);
////////////////////////////////////////////////////// 
//bitwise xoring,writing to file begins here


for(i=0;i<10;i++)
{
bin_num_executions[i]=bin_num_executions[i]^key[i];
if(bin_num_executions[i]==48)
{
xor_bit[i]=0;
}
else
{
xor_bit[i]=1;
}
}//for loop ends here

fp=fopen("C:\\validity.dat","w"); //writing to a file
fwrite(xor_bit,sizeof(int),10,fp);
fclose(fp);
return(total_copy);
}
////////////////////////////////////////////////////////////////////
void main()
{
int validity=validate();
clrscr();
if(validity==0)
{
printf("\nSoftware Expired\n");
getch();
exit(); 
}
if(!(validity>0&&validity<16))
{
printf("\nCurrupted associated file\n");
getch();
exit();
}
printf("\nYou have %d more executions\n",validity);
getch(); 
} // end of main
```
If u try to modify any file it gives error.....


----------



## mehulved (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

What's the use of wasting time over coding such cripplewares?


----------



## nithinks (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*



			
				mehulved said:
			
		

> What's the use of wasting time over coding such cripplewares?



Wasting time? I have written a number of codes.. but thought this is a bit different.So I posted.


----------



## mehulved (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*



			
				nithinks said:
			
		

> Wasting time? I have written a number of codes.. but thought this is a bit different.So I posted.


That wasn't my point. Anyways let it be.


----------



## sauravgr8 (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

I am unable to run even a simplest graphics program in C, even though when i compile the program it shows success but when i run it , it gives the error that the 
BGI error: graphics not initialized...
I dont know where is the problem...can any one help plz
#include<stdio.h>
#include<conio.h>
#include<graphics.h.
void main()
{
int gd=DETECT,GM;
initgraph(&gd,&gm,"");
setbkcolor(RED);
getch();
}


----------



## ratedrsuperstar (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

hey ilugd i'm getting a declaration missing statement for the "namespace" thing


----------



## ilugd (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

are you saving the file as a cpp and then compiling as a c++ program? Should work.  Works here. I just copy pasted after running gcc and executiing.


----------



## Projjwal (Sep 18, 2007)

*Re: Post ur C/C++ Programs Here*

@nithinks Really cool one.
But,pls explain the program.Which Encryption technique u use?
Another thing if user copy the .dat file when it execute first(means .dat file with 15 execution validation) then after expiring de software just overwrite the file then what happened? Software with 15 execution trial  or gives an error.
According to ur logic it's worked perfectly for de next 15 execution.


----------



## nithinks (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Projjwal said:
			
		

> @nithinks Really cool one.
> But,pls explain the program.Which Encryption technique u use?
> Another thing if user copy the .dat file when it execute first(means .dat file with 15 execution validation) then after expiring de software just overwrite the file then what happened? Software with 15 execution trial  or gives an error.
> According to ur logic it's worked perfectly for de next 15 execution.



thanks.

Yes.. you are right. what we can do is, create that .DAT file in a particular location like C:\all users\application data\, any location and the path of that file we need not disclose.

And coming to encryption , its simple xor operation, nothing more than that

for example let the key be 1010(hidden from user) and counter 3 (0011)
xor this counter and store it in file 
that is
0011      ->counter
1010      ->key
--------
1001      (encrypted counter)
--------
to get the value back, xor this encypted counter with the key
1001    ->encrypted counter
1010    ->key
---------
0011      which is 3
---------


----------



## Projjwal (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*

Yea...i got it.but i think u have to use some complex hash algorithm like MD5. & create an startup program(hidden) which will use the dat file.As a result when the user overwrite/delete the file windows automatically blocked it.


----------



## ilugd (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*

how bout setting some encrypted string on a harddisk sector/track combination and setting the sector to damaged in the allocation table. The program can then read and update. I guess you will have to use interrupts to do that.


----------



## nithinks (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*



			
				ilugd said:
			
		

> how bout setting some encrypted string on a harddisk sector/track combination and setting the sector to damaged in the allocation table. The program can then read and update. I guess you will have to use interrupts to do that.



Nice idea.. but is it possible to code that in C? and how to write a registry entry in C?


----------



## ilugd (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*

not a registry entry. It will have to be done with assembly or with int function calls. I am not the expert in that though. Just my two cents.


----------



## nithinks (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*

Okay another challenge ..
Can you write a C program to print the number in the format given below?

         *img502.imageshack.us/img502/7007/20758345gu0.jpg

and so on


----------



## QwertyManiac (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*



			
				nithinks said:
			
		

> Okay another challenge ..
> Can you write a C program to print the number in the format given below?
> 
> *img502.imageshack.us/img502/7007/20758345gu0.jpg
> ...


Don't think mine's so efficient but it kind of does the job:


```
#include<iostream>

using namespace std;

/*

            1
           323
          43234
         5432345

*/

int main()
    {
        int count = 1, temp=1, i, j, k;
        
        for(int times=1;times<5;times++)
            {
                for(i=5;i>=times;i--)
                    {
                        cout<<" ";
                        if(i==1)
                            {
                                cout<<1;
                            }                        
                    }
                    
                for(k=temp;k>=2;k--)
                    {
                        cout<<k;
                    }
                
                
                    
                for(j=3;j<=temp;j++)
                    {
                        cout<<j;
                    }
                
                if(temp==1)
                    {
                        temp+=2;
                    }
                else
                    {
                        temp++;
                    }
                
                count+=1;
                    
                cout<<endl;
            }
    }
```


----------



## Desi-Tek.com (Sep 19, 2007)

*Re: Post ur C/C++ Programs Here*

encryption in java 
	
	



```
package ocricket.api.encryption;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

/**

* Encodes a string using MD5 hashing

*

* @author Dheeraj

* @version 1.0

*/

public class MD5

{

/**

* Encodes a string

*

* @param str String to encode

* @return Encoded String

*/

public static String crypt(String str)

{

if (str == null || str.length() == 0) {

throw new IllegalArgumentException(“String to encript cannot be null or zero length”);

}

StringBuffer hexString= new StringBuffer();

try {

MessageDigest md = MessageDigest.getInstance(“MD5″);

md.update(str.getBytes());

byte[] hash = md.digest();

for (int i = 0; i < hash.length; i++) {

if ((0xff & hash[i]) < 0×10) {

hexString.append(“0″ + Integer.toHexString((0xFF & hash[i])));

}

else {

hexString.append(Integer.toHexString(0xFF & hash[i]));

}

}

}

catch (NoSuchAlgorithmException e) {

}

return hexString.toString();

}

}
```
here is the tutorial on how to use it *desi-tek.org/blog/2007/09/19/tutorial-on-how-to-use-encryption-in-java-web-application.html


----------



## Projjwal (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

De Md5 program in c++.It's little bit complicated .......
-----------------------------------------------------------------
MD5.cpp:*www.koders.com/cpp/fid5F95FCF5C140CE260F9D28AD5ECB21531ACAE8C6.aspx?s=md5
md5.h:*www.koders.com/c/fidACD7EC6E0FCD2218463A664206B8BD97237711CC.aspx?s=md5
------------------------------------------------------------------
there r two files md5.cpp & md5.h(the header file).
But it's complicated for me . I used md5 algorithm in my VC# project where it build in. (I use Microsoft VC# 2005)


----------



## Glen Apayart (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

This is my first program in c++. 

Actually its working well and i just want to know the comments or suggestion about my program. i know it still need more code to make it stable and effective.

*Program: a simple shop using string, integers, float, & algebraic operators* 

```
#include <iostream>
using namespace std;

int main()
{
    char firstName[20], lastName[20];

    unsigned short shirts;
    unsigned short pants;
    unsigned short shoes;
    unsigned short caps;
    unsigned short totalItems;

    double priceShirts = 1.25;
    double pricePants = 2.75;
    double priceShoes = 3.25;
    double priceCaps = 1.65;

    float totalShirts;
    float totalPants;
    float totalShoes;
    float totalCaps;
    float all, payment, change;

    int orderDay;
    int orderMonth;
    int orderYear;

    cout << "-=- Apayart Botique -=-";
    cout << "\nEnter your personal information";
    cout << "\nFirst Name: ";
    cin >> ws;
    cin.getline(firstName, 20);
    cout << "Last Name: ";
    cin >> ws;
    cin.getline(lastName, 20);

    cout << "\nEnter date of order";
    cout << "\nOrder Day: ";
    cin >> orderDay;
    cout << "Order Month: ";
    cin >> orderMonth;
    cout << "Order Year: ";
    cin >> orderYear;

    cout << "\nEnter number of shirts: ";
    cin >> shirts;
    cout << "Enter number of pants: ";
    cin >> pants;
    cout << "Enter number of shoes: ";
    cin >> shoes;
    cout << "Enter number of caps: ";
    cin >> caps;

    totalShirts = shirts * priceShirts;
    totalPants = pants * pricePants;
    totalShoes = shoes * priceShoes;
    totalCaps = caps * priceCaps;
    totalItems = shirts + pants + shoes + caps;
    all = totalShirts + totalPants + totalShoes + totalCaps; 

    cout << "\ntotal price: $"; << all;
    cout <<"\nYour payments: $";
    cin >> payment;

    change = payment - all;

    cout << "\n=======================";
    cout << "\n-=- Apayart Botique -=-";
    cout << "\n=======================";
    cout << "\nCustomer Order";
    cout << "\n\tCustomer Name: " << firstName << " " << lastName;
    cout << "\n\tOrder Date: ";
    cout << orderMonth << "/" << orderDay << "/" << orderYear;
    cout << "\n------------------------------";
    cout << "\nItems type    Qty     Price";
    cout << "\n------------------------------";
    cout << "\nShirts        " << shirts << "     $" << totalShirts;
    cout << "\nPants        " << pants << "     $" << totalPants;
    cout << "\nShoes        " << shoes << "     $" << totalShoes;
    cout << "\nCaps        " << caps << "     $ "<< totalCaps;
    cout << "\n------------------------------;
    cout << "\nTotal Items: "; << totalItems;
    cout << "\n\nTotal Price: $" << all;
    cout << "\nPayment: $" << payment;
    cout << "\nChange: $" << change << "\n\n\n\n\n\n";

    return 0;

}
```


----------



## aditya.shevade (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Good style of coding and use of white space. Variable names very good. Keep it up.


----------



## Glen Apayart (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

@aditya.shevade

Thanks! i saw your program which is &quot;Bulls and Cows&quot; and i observe your using the techniques of passing arguments. Im into that from now. Maybe later i'll put my code about passing arguments.

I feel good when someone shares idea to each other. ^^

Edit:.

Here is the code with *passing arguments* of my simple shop.


```
#include <iostream>
#include <string>
using namespace std;

string getUser()
{
    string firstName, lastName, FN;

    cout << "-=- Apayart Botiques-=-";
    cout << "\nEnter your personal information";
    cout << "\nFirst Name: ";
    cin >> firstName;
    cout << "Last Name: ";
    cin >> lastName;

    FN = firstName + " " + lastName;

    return FN;
}

int main()
{
    string user;
    user = getUser();

    unsigned short shirts;
    unsigned short pants;
    unsigned short shoes;
    unsigned short caps;
    unsigned short totalItems;

    double getShirts(unsigned short shirts);
    double getPants(unsigned short pants);
    double getShoes(unsigned short shoes);
    double getCaps(unsigned short caps);

    float totalShirts;
    float totalPants;
    float totalShoes;
    float totalCaps;
    float all, payment, change;

    int orderDay, orderMonth, orderYear;

    cout << "Enter the date of order";
    cout << "\nOrder Day: ";
    cin >> orderDay;
    cout << "Order Month: ";
    cin >> orderMonth;
    cout << "Order Year: ";
    cin >> orderYear;

    cout << "\nEnter number of shirts: ";
    cin >> shirts;
    cout << "Enter number of pants: ";
    cin >> pants;
    cout << "Enter number of shoes: ";
    cin >> shoes;
    cout << "Enter number of caps: ";
    cin >> caps;

    totalShirts = getShirts(shirts);
    totalPants = getPants(pants);
    totalShoes = getShoes(shoes);
    totalCaps = getCaps(caps);

    totalItems = shirts + pants + shoes + caps;
    all = totalShirts + totalPants + totalShoes + totalCaps; 

    cout << "\nTotal price: $" << all;
    cout <<"\nYour payments: $";
    cin >> payment;

    change = payment - all;

    cout << "\n========================&quot;;
    cout << "\n-=- Apayart Botiques -=-&quot;;
    cout << "\n========================&quot;;
    cout << "\nCustomer Order&quot;;
    cout << "\n\tCustomer Name: &quot; << user;
    cout << "\n\tOrder Date: " << orderMonth << "/" << orderDay << "/" << orderYear;
    cout << "\n------------------------------";
    cout << "\nItems type    Qty     Price";
    cout << "\n------------------------------";
    cout << "\nShirts        " << shirts << "     $" << totalShirts;
    cout << "\nPants        " << pants << "     $" << totalPants;
    cout << "\nShoes        " << shoes << "     $" << totalShoes;
    cout << "\nCaps        " << caps << "     $" << totalCaps;
    cout << "\n------------------------------";
    cout << "\nTotal Items: " << totalItems;
    cout << "\n\nTotal Price: $" << all;
    cout << "\nPayment: $" << payment;
    cout << "\nChange: $" << change << "\n\n\n\n\n\n";

    return 0;
}

double getShirts(unsigned short shirts)
{
    double priceShirts = 1.25;
    float totalShirts;

    totalShirts = shirts * priceShirts;

    return totalShirts;
}

double getPants(unsigned short pants)
{
    double pricePants = 2.75;
    float totalPants;

    totalPants = pants * pricePants;

    return totalPants;
}

double getShoes(unsigned short shoes)
{
    double priceShoes = 3.25;
    float totalShoes;

    totalShoes = shoes * priceShoes;

    return totalShoes;
}

double getCaps(unsigned short caps)
{
    double priceCaps = 1.65;
    float totalCaps;

    totalCaps = caps * priceCaps;

    return totalCaps;
}
```


----------



## Sykora (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

^^^ I think it's a bit neater to put your function prototypes above main, and not in it. Or you can put main below everything else, which is what I do. Not really an issue, but just my 2 cents.

It's a good thing you've started out programming in C++ with a good coding style, as aditya.shevade mentioned. Stick to it.


----------



## Nav11aug (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

yup... funcs prototyped inside main() wont be accesible by ne other funcs


----------



## QwertyManiac (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Nav11aug said:
			
		

> yup... funcs prototyped inside main() wont be accesible by ne other funcs


 What about a prototyped function accessing another prototyped function (Both belonging to the same function)?

I don't understand this:

```
#include<iostream>

//    Working Example

using namespace std;

int main()
    {
        void show1(); //    Prototyped Declarations
        void show2(); //        "           "
        
        show1();
        show2();
        
        cout<<endl;
        return 0;
    }

void show2()
    {
        cout<<" World";
    }

void show1()
    {
        cout<<"Hello";
        show2();  //Show1() calls similarly prototyped Show2()
    }
```
This one (above) executes perfectly but this one (below) doesnt:

```
#include<iostream>

//    Non-Working Example

using namespace std;

int main()
    {
        void show1(); //    Prototyped Declarations
        void show2(); //        "           "
        
        show1();
        show2();
        
        cout<<endl;
        return 0;
    }


void show1()
    {
        cout<<"Hello";
        show2();  //Show1() calls similarly prototyped Show2()
    }

void show2()
    {
        cout<<" World";
    }

/*      harsh@qwerty-workstation:~$ g++ test.cpp 
test.cpp: In function ‘void show1()’:
test.cpp:23: error: ‘show2’ was not declared in this scope      */
```
So commonly prototyped functions can access each other only if they are ordered in a particular (sort of global) heirarchy? Isn't this too restrictive?

And what would this type of recursion be called?

```
#include<iostream>

[B]//    NOT FOR EXECUTION.
//    Improper code, ends in Segmentation fault
//    Posted for understanding, not running purposes
[/B]
using namespace std;

void show1();
void show2();

void show2()
    {
        cout<<" World";
        show1();
    }

void show1()
    {
        cout<<"Hello";
        show2();
    }

int main()
    {
        show1();
        show2();
        
        cout<<endl;
        return 0;
    }
```

Edit: Err leave the last one, its stupid. Can't be called a recursion either, as I figured.


----------



## Nav11aug (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

@qwerty : 

Which compiler do u use .As far as i remember readin in K&R , he says whther the order matters depends only on the compiler . 

But still , i dont think i get ne reason. :/ ne1 else ,plz?

Off-topic: i just realized tht urs was one of teh easiest names type out "qwerty"


----------



## QwertyManiac (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

Oh ok.

And I use *g++ GNU C++ Compiler (GCC) version 4.1.2*


----------



## Sykora (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

@Qwerty :

Your first two examples make sense -- The first one works because the definition of show2() is above its function call in show1(). It works in main because it has been prototyped in main(). In the second example, you've interchanged the positions of show1() and show2(), and it doesn't work, becuase show1() doesn't know that show2() exists.

Prototypes are like variable declarations, they lose scope unless declared globally, which is what I suggested. 

Your last example isn't stupid at all. It's a technique called mutual recursion. Obviously its practical uses aren't as simple as what you've written, but if the termination conditions are written properly, it can be very powerful. In fact, one of the best Sudoku solvers I've seen uses a combination of depth-first-search and mutual recursion. I'll see if I can find that code.

I'm pretty sure that the order matters irrespective of the compiler, as long as it conforms to a certain degree of standards.


----------



## Nav11aug (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

my compiler (gcc as u cn see) : 


```
#include<stdio.h>

int main()
{
    void func1(void );
    void func2(void );
    
    func2();
    func1();
    
    getchar();
    
    return 0;
}

void func2(void )
{
    printf("Wrkin?");
    func1();
}

void func1(void )
{
    printf("\nIn func1 now");
}
```

g++.exe  C:\gcc\Source\protoinmain1.o -o C:\gcc\Source\protoinmain1.exe  -Wall -fpermissive 
C:\gcc\Source\protoinmain1.o(.text+0x43): protoinmain1: undefined reference to `func1'
Failure


----------



## aditya.shevade (Sep 21, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Nothing (1st and 2nd) working here with gcc 4.1, OpenSuSE 10.2.

@ Glen, I am also new to C++. I had been using C for long time. It's been only about a month with C++ (in terms of learning, 30 days).

@ Glen, Listen to Sykora. It's better to declare the functions before main and then you can either define them after main of define them right before main along with the declaration.


----------



## Desi-Tek.com (Sep 22, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Projjwal said:
			
		

> De Md5 program in c++.It's little bit complicated .......
> -----------------------------------------------------------------
> MD5.cpp:*www.koders.com/cpp/fid5F95FCF5C140CE260F9D28AD5ECB21531ACAE8C6.aspx?s=md5
> md5.h:*www.koders.com/c/fidACD7EC6E0FCD2218463A664206B8BD97237711CC.aspx?s=md5
> ...


 try to convert my program into c# using c# converter?

i'll soon post the tutorial on JPA and hibernate which has changed the way we use to communicate with database in java and .net.  
here is one of the video tutorial on it
*www.thescreencast.com/2007/07/tour-around-europe-eclipse-for-java-ee.html

and some resources
hibernate in dot net
*NHibernate*

*www.hibernate.org/365.html?cmd=prntdoc

hibernate in java 
*www.hibernate.org/
JPA
*java.sun.com/developer/technicalArticles/J2EE/jpa/


----------



## Glen Apayart (Sep 22, 2007)

*Re: Post ur C/C++ Programs Here*

@Sykora
Thanks for the advice. So, the only function that are considered to be define is the inline function.. Any other circumstances?

@aditya.shevade

Yes, Sykora is right about it. i'll stick to that.


----------



## Sykora (Sep 22, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Glen Apayart said:
			
		

> So, the only function that are considered to be define is the inline function.. Any other circumstances?



Can you bring that one past me again? I didn't understand that at all.


----------



## Glen Apayart (Sep 22, 2007)

*Re: Post ur C/C++ Programs Here*

@Sykora

Nevermind ^^.  im talking about the techniques of a function which is the "inline function" and the other one was the "argument by reference" that are considered to be defined. Anyway, i understood it now.

Sorry for my bad english.


----------



## Gigacore (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

Cool.. seems like this thread helps people and students who are desperate to learn, solve, seeking help... So guys i think this thread should go sticky 

I WILL POST A POLL to make this stick or not.. please vote


----------



## Sykora (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

I would prefer a separate programming section (which I think has been raised a number of times).


----------



## QwertyManiac (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> 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



Same as Sykora, and quoting my old post from the same thread. But of course, no one listens ..


----------



## Gigacore (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

Cool then, +1 for Programming Section


----------



## Ron (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

this thread should go STICKY.........
and all the running c++ threads should be merged.....


----------



## Gigacore (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

no i dont like merging... it will be a real mess


----------



## Nav11aug (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

exactly..we dnt want a huge mess here.A new programming sectiona nd no merges whtsoever


----------



## Gigacore (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

Yeah,, after making the section let them move this thread to that forum and make it sticky


----------



## aditya.shevade (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

+1 for new programming section...


----------



## ilugd (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

can we get back to the topic? it was getting interesting.


----------



## aditya.shevade (Sep 23, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Yep... it was. I had gone to a competition of C programming today. Me and my partner, we ranked third in debugging contest and maybe 5th in coding contest (dunno for sure, but we were one of the 5 that finished the coding in time )

Read more here on my blog


----------



## aditya.shevade (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Getting back to the contest mentioned above, we had to do this program as first assigment :-


```
/* This program calculates the value of a mathematical function and gives */
/* the output depending on it. The function is defined as follows :-      */
/* f(1)    = 1                                                            */
/* f(2n)   = n                                                            */
/* f(2n+1) = f(n) + f (n+1)                                               */
/* The inputs should be taken till a negative value is inputed.           */
/* The maximum number of inputs is considered to be 100.                  */

#include<iostream>

#define _maxInputs 100

using namespace std;

float Function(int);

main()
{
	int* inNumberArray = new int[_maxInputs]; 
	float* outAnswerArray = new float[_maxInputs];
	int cnt, counter;
	
	cout << endl;
	cout << "Please enter the variable values. Enter negative value to exit";
	cout << endl;
	
	for(counter = 0; counter < _maxInputs; counter++)
	{
		cin >> inNumberArray[counter];
		
		if(inNumberArray[counter] < 0)
			break;
		
		outAnswerArray[counter] = Function(inNumberArray[counter]);
		
	}
	
	cnt = counter;
	
	for(counter = 0; counter < cnt; counter++)
	{
		cout << "F(" << inNumberArray[counter] << ") = " << outAnswerArray[counter]
			 << "." << endl;
		
	}
	
	delete[] inNumberArray;
	delete[] outAnswerArray;
	
	return 0;
	
}

float Function (int inNumber)
{
	if(inNumber == 1)
		return 1.0;
	
	else if(inNumber % 2 == 0)
		return (inNumber/2.0);
	
	else if(inNumber % 2 == 1)
		return (Function((inNumber-1)/2) + Function((inNumber+1)/2));
	
}
```

The output is :-


```
EXECUTING:
/home/aditya/Mathematical-Function-1 
----------------------------------------------

Please enter the variable values. Enter negative value to exit
1 2 3 4 5 6 7 8 9 10 11 12 -1 
F(1) = 1.
F(2) = 1.
F(3) = 2.
F(4) = 2.
F(5) = 3.
F(6) = 3.
F(7) = 4.
F(8) = 4.
F(9) = 5.
F(10) = 5.
F(11) = 6.
F(12) = 6.

----------------------------------------------
Program exited successfully with errcode (0)
Press the Enter key to close this terminal ...
```

Is it any good? Any ideas for optimization? Anything?

Aditya


----------



## Gigacore (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

I tried executing ot, its nice


----------



## Sykora (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

If you want to be really picky, the recursive call of your function can be modified as :


```
return !(n - 1) % 4 ? (n - 1)/4 + Function((n + 1)/2) : ((n + 1)/4 + Function((n - 1)/2);
```

All it will do is reduce the overhead of an extra function call. In C++, it won't make too much of a difference unless you are calling it a million times or so, but in a different language, it can cut down the running time dramatically. Also, for a language like python which has a dictionary data structure, you can use caching.


----------



## quan chi (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

guys i have a problem.

well its a program where it firsts cubes a value and then squares it.

#include<iostream.h>
int cube(int x);
int square(int cubed);
void main()
{int x,cubed,squared;
cout<<"enter a value";
cin>>x;
cubed=cube(x);
squared=square(cubed);
cout<<"cubed"<<cubed;
cout<<squared"<<squared;
}
int cube(int x)
{return(x*x*x);
}
int square(int cubed)
{return(cubed*cubed);
}

well my problem is if i enter the value as 2 then the program works well.
if i enter the value as7 then it cubes 7 perfectly.
but gives its squared value as some 4 to 5 digit negative number.

then i changed the int(return type and declaration) to unsigned long then it worked perfectly.why is it so? why didn't it worked for int?


----------



## QwertyManiac (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

That is cause, in C/C++, signed int's range is just till *32768* in the positive range. Anything above that creates garbage. Use float for long digit calculations. Unsigned int is till *65536* and thus works for your solution.


----------



## aditya.shevade (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Maybe the answer was exceeding the limit of integer data type.

And please format the code as is first post.


----------



## QwertyManiac (Sep 25, 2007)

*Re: Post ur C/C++ Programs Here*

Wasn't that what I was trying to point out? :-\

Oh, guess you're saying it to him and not me


----------



## timemachine (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*

Character Eater:

This TSR program hooks itself with timer interrupt and selects a random row and coloums position at each run and writes space at that position, the person using the computer feels that something is eating up the characters from the screen.



> #include"dos.h"
> #include<conio.h>
> #include<stdlib.h>
> 
> ...


----------



## Desi-Tek.com (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*

there are so many programmers here digit should make separate section for programming talk


----------



## timemachine (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*

yes 
i agree.


----------



## Desi-Tek.com (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*



			
				quan chi said:
			
		

> guys i have a problem.
> 
> well its a program where it firsts cubes a value and then squares it.
> 
> ...


thats why we use long

multi threading mini web server in java

```
//***************************************
// HTTP Server 
// @Author Dheeraj
// server implements HTTP GET method
//***************************************


import java.net.*;
import java.io.*;
import java.util.*;


public class MiniServer 
{
    
    public static void main(String args[]) {
	
	int port;
	ServerSocket server_socket;
	
	
	try { 
	    port = Integer.parseInt(args[0]);
	}
	catch (Exception e ) 

	{
	    port = 80;
	   
	}
	

	try {
	    
	    server_socket = new ServerSocket(port);
	    System.out.println ("Welcome to MiniServer v1.0.1  Console");
	    System.out.println("MiniServer is running on port " +  
			       server_socket.getLocalPort() );
	   System.out.println ("Open WEB BROWSER AND ENTER *localhost:"+server_socket.getLocalPort()+"/index.aspx"  );
	    // server infinite loop
	   
	    while(true) {
		Socket socket = server_socket.accept();
		System.out.println("New connection accepted " +
				   socket.getInetAddress() +
				   ":" + socket.getPort());
		
		// Construct handler to process the HTTP request message.
		try {
		    httpRequestHandler request = 
			new httpRequestHandler(socket);
		    // Create a new thread to process the request.
		    Thread thread = new Thread(request);
		    
		    // Start the thread.
		    thread.start();
		}
		catch(Exception e) {
		    System.out.println(e);
		}
	    }
	}
	
	catch (IOException e) {
	    System.out.println(e);
	}
    }
}

//time to play with threading
 
class httpRequestHandler implements Runnable
{
    final static String CRLF = "\r\n";
    Socket socket;
    InputStream input;
    OutputStream output;
    BufferedReader br;

    // Constructor
    public httpRequestHandler(Socket socket) throws Exception 
    {
	this.socket = socket;
	this.input = socket.getInputStream();
	this.output = socket.getOutputStream();
	this.br = 
	    new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    
    // Implement the run() method of the Runnable interface.
    public void run()
    {
	try {
	    processRequest();
	}
	catch(Exception e) {
	    System.out.println(e);
	}
    }
    
    private void processRequest() throws Exception
    {
	while(true) {
	    
	    String headerLine = br.readLine();
	    System.out.println(headerLine);
	    if(headerLine.equals(CRLF) || headerLine.equals("")) break;
	    
	    StringTokenizer s = new StringTokenizer(headerLine);
	    String temp = s.nextToken();
	    
	    if(temp.equals("GET")) {

		String fileName = s.nextToken();
		fileName = "." + fileName ;
		
		// Open the requested file.
		FileInputStream fis = null ;
		boolean fileExists = true ;
		try 
		    {
			fis = new FileInputStream( fileName ) ;
		    } 
		catch ( FileNotFoundException e ) 
		    {
			fileExists = false ;
		    }
		
		// Construct the response message.
		String serverLine = "Server: fpont simple java MiniServer";
		String statusLine = null;
		String contentTypeLine = null;
		String entityBody = null;
		String contentLengthLine = "error";
		if ( fileExists )
		    {
			statusLine = "HTTP/1.0 200 OK" + CRLF ;
			contentTypeLine = "Content-type: " + 
			    contentType( fileName ) + CRLF ;
			contentLengthLine = "Content-Length: " 
			    + (new Integer(fis.available())).toString() 
			    + CRLF;
		    }
		else
		    {
			statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
			contentTypeLine = "text/html" ;
			entityBody = "<HTML>" + 
			    "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
			    "<BODY>404 Not Found" 
			    +"<br>usage:*yourHostName:port/"
			    +"fileName.html</BODY></HTML>" ;
		    }
		
		// Send the status line.
		output.write(statusLine.getBytes());
		
		// Send the server line.
		output.write(serverLine.getBytes());
		
		// Send the content type line.
		output.write(contentTypeLine.getBytes());
		
		// Send the Content-Length
		output.write(contentLengthLine.getBytes());
		
		// Send a blank line to indicate the end of the header lines.
		output.write(CRLF.getBytes());
		
		// Send the entity body.
		if (fileExists)
		    {
			sendBytes(fis, output) ;
			fis.close();
		    }
		else
		    {
			output.write(entityBody.getBytes());
		    }
				
	    }
	}
	
	try {
	    output.close();
	    br.close();
	    socket.close();
	}
	catch(Exception e) {}
    }
    
    private static void sendBytes(FileInputStream fis, OutputStream os) 
	throws Exception
    {
	// Construct a 1K buffer to hold bytes on their way to the socket.
	byte[] buffer = new byte[1024] ;
	int bytes = 0 ;
	
	// Copy requested file into the socket's output stream.
	while ((bytes = fis.read(buffer)) != -1 ) 
	    {
		os.write(buffer, 0, bytes);
	    }
    }
    
    private static String contentType(String fileName)
    {
    	//supported file extension  .html, .htm, .zip, .rar, aspx
	if (fileName.endsWith(".htm") || fileName.endsWith(".aspx") ||fileName.endsWith(".rar") || fileName.endsWith(".zip") || fileName.endsWith(".exe") || fileName.endsWith(".html"))
	    {
		return "text/html/tar/zip/exe/rar/aspx";
	    }
	
	return "";
	
    }
    
}
```


----------



## QwertyManiac (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Desi-Tek.com said:
			
		

> there are so many programmers here digit should make separate section for programming talk


Amen. And you need to create a new thread for Java first


----------



## aditya.shevade (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*


----------



## Desi-Tek.com (Sep 27, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> Amen. And you need to create a new thread for Java first



just include the java in title


----------



## shady_inc (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*


```
#include <iostream>
using namespace std;
void circle ();
void rectangle();
void triangle();
void sphere();
void cone();
void cylinder();
int main()
{ int cho1,cho2,cho3;
  menu:   
  cout<<"1. Plane Figures\n"
      <<"2. 3D Figures\n"
      <<"3. Exit\n"
      <<"Enter your Choice:";
  cin>>cho1;
  switch (cho1)
  { case 1:
    cout<<"You selected Plane Figures\n"     
        <<"1. Circle\n"
        <<"2. Rectangle\n"
        <<"3. Triangle\n"
        <<"Enter your Choice:";
    cin>>cho2;
    switch (cho2)
    { case 1:
      cout<<"You selected Circle\n";
      circle();
      break;
      case 2:
      cout<<"You selected Rectangle\n";
      rectangle();
      break;
      case 3:
      cout<<"You selected Triangle\n";
      triangle();
      break;
      default:
      cout<<"Invalid Input!!!\n";
      goto menu;              /*At start of Main function*/            
    }
    break; 
    case 2:
    cout<<"You selected 3D figures\n"
        <<"1. Cone\n"
        <<"2. Cylinder\n"
        <<"3. Sphere\n"
        <<"Enter your choice:";
    cin>>cho3;
    switch (cho3)
    { case 1:
      cout<<"You selected Cone\n";
      cone();
      break;
      case 2:
      cout<<"You selected Cylinder\n";
      cylinder();
      break;
      case 3:
      cout<<"You selected Sphere\n";
      sphere();
      break;
      default:
      cout<<"Invalid Input!!!";
      goto menu;            /*At start of Main function*/
      
    }  
    break;
    case 3:
    goto menu;             /*At start of Main function*/
    break;
    default:
    cout<<"Invalid Input!!!";        
    goto menu;             /*At start of Main function*/
    
  }
}         
void circle()
{ float r,a;
  cout<<"Enter Radius:\n";
  cin.get();
  cin>>r;
  a=22.0*r*r/7.0;
  cout<<"Area is "<<a;
  cin.get();
}
void rectangle()
{ float l,b,a;
  cout<<"Enter Length and breadth:\n";
  cin.get();
  cin>>l>>b;
  a=l*b;
  cout<<"Area is "<<a;
  cin.get();
}
void triangle()
{ float h,b,a;
  cout<<"Enter Height and base:\n";
  cin.get();
  cin>>h>>b;
  a=h*b/2.0;
  cout<<"Area is "<<a;
  cin.get();
}
void cone()
{ float r,h,a;
  cout<<"Enter radius and height:\n";
  cin.get();
  cin>>r>>h;
  a=22.0*r*r*h/21.0;
  cout<<"Volume is "<<a;
  cin.get();
}
void cylinder()
{ float r,h,a;
  cout<<"Enter radius and height:\n";
  cin.get();  
  cin>>r>>h;
  a=22.0*r*r*h/7.0;
  cout<<"Volume is "<<a;
  cin.get();
}
void sphere()
{ float r,a;
  cout<<"Enter radius:\n";
  cin.get();
  cin>>r;
  a=88.0*r*r/21.0;
  cout<<"Volume is "<<a;
  cin.get();
}
```

Why the hell does this program exit at the last moment????
Me using Bloodshed Dev-C++


----------



## quan chi (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

thanks guys for answering my previous query.
i have another question is it necessary to use 'using namespace std;' in c++ everytime.well my programs work well without writing those.if i write using namespace std it shows declaration syntax error.


----------



## ilugd (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^^ which compiler? Using namespace std is standard. But i remember compiling programs without that line. Some header files have that included in them so when you include them, it does the same thing. Not sure about the declaration syntax error though.


----------



## praka123 (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

may be acc to ISO standard above syntax must be used  prolly gcc or dev-c++ in windows will ask for this?


----------



## aditya.shevade (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^ You are right. gcc and mingw32 both need the declaration, TurboC however, (some old versions of borland compiler)(I think 3.0), does not recognize this declaration and gives an error. It is not according to ISO standards.


----------



## QwertyManiac (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				shady_inc said:
			
		

> ```
> #include <iostream>
> using namespace std;
> void circle ();
> ...


 Cause its programmed to that way! Add a blank cin.get() at the end of it. Like I've edited your program. 

That'll make it wait for a junk input at the end so you can see your output before it exits. Actually these programs are supposed to be executed in terminal environments where you can see the residual output and thereby get your required answers. Try running it via Command Prompt 

Oh and by the way, using unconditional logic jumps ala GoTo is a very bad programming practice.


----------



## The_Devil_Himself (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^agreed using goto statements is considered a very bad programming practice.

Use getch() to stop the program to exit at the last moment.It will exit after you press any key.NOTE:include conio.h or else getch won't work.

you can use it like:
cout<<"Press any key to exit...";
getch();

Hope this helps.


----------



## Zeeshan Quireshi (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> ^^agreed using goto statements is considered a very bad programming practice.
> 
> Use getch() to stop the program to exit at the last moment.It will exit after you press any key.NOTE:include conio.h or else getch won't work.
> 
> ...


Dude , using Non-Standard C++ is also considered a _very bad_ programming practice .

conio.h is a borland specific header , and is not a part of Standard C++  , therefore using cin.get() is a better practice .


----------



## The_Devil_Himself (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^agree but i find using getch so much better.I dunno why it wasn't included in standard c++ but i still use it in almost every program i write.


----------



## soham (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

Hey Qwerty, does the GCC compiler work in windows too? If yes, where form do i download it and make it run.


----------



## The_Devil_Himself (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^I think dev c++ makes use of gcc compiler.I am not sure though.


----------



## timemachine (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

to use gcc you can download an interface like CYGWIN or MinGW.
i consider cygwin as best.
provides programming and the unix X11 features also.
i can give the link. it gives the packages to select and then downloads it and installs it. 

here goes the link to X11 system of cygwin. rest features can be found out here. I prefer gcc due to many reasons. 

*x.cygwin.com/

and dev C++ do not make use of gcc compiler exactly. Well best programming practice is done on gcc(i think so, dont know about rest). use cygwin if you want to use on a windows system.


----------



## aditya.shevade (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^ No need to go for cygwin just for gcc. Use DevCPP. It uses the win32 portal of gcc, known as mingw32.


----------



## The_Devil_Himself (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

^^thanks for confirming.Dev c++ has very good gui too.


----------



## timemachine (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> ^^ No need to go for cygwin just for gcc. Use DevCPP. It uses the win32 portal of gcc, known as mingw32.


MinGW : GTK facility is not available. Lacks of some libraries of gcc.
Downloaded original interface of MinGW but i was not able to find GTK extensions and some binutils.


----------



## shady_inc (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> Oh and by the way, using unconditional logic jumps ala GoTo is a very bad programming practice.



Hmmm....I find goto quite helpful in the program I have posted..What is the other alternative to it??

Also,How is microsoft visual C++..Better or worse than Dev-C++???


----------



## timemachine (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

Depends upon the requirement of the project.... if i would have to choose, i would have chosen Dev C++. But Visual C++ is also good, but difficult to learn however.


----------



## The_Devil_Himself (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

yea man dev c++ looks more geeky(hence cool).Lols.dev c++ is light on resources and thats very important for a IDE.


----------



## timemachine (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

Well about looks, it depends person to person. Well i like the UNIX enviornment and the traditional black and white screen for programming. Lotzz of libraries and binutils and a great satisfaction. May vary from person to person


----------



## Ankur Gupta (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				shady_inc said:
			
		

> Hmmm....I find goto quite helpful in the program I have posted..What is the other alternative to it??
> 
> Also,How is microsoft visual C++..Better or worse than Dev-C++???



Making a function is a much better way to implement goto statement...
Never use goto statement...it is a very inefficient way of programming...


----------



## ayush_chh (Sep 28, 2007)

*Re: Post ur C/C++ Programs Here*

Here is program to insert a node in a singly linked list. The program works fine but it gives a warning 'the code is unusable' and if i remove this(bolded part) then the program doesn't work........


```
/* Inserting a node into a singly Linked List*/

#include<stdio.h>
#include<conio.h>
struct list
{
 int info;
 struct list *link;
};
typedef struct list node;
// create the list
void createlist(node *n)
{
 char ch;
 printf("\n\nEnter the item (number only) to be inserted\n");
 scanf("%d",&n->info);
 printf("\nDo you want to continue(Y/N)\n");
 ch= getche();
 getch();
 if(ch=='y'|| ch=='Y')
 {
  n->link=(node *)malloc(sizeof(node));
  createlist(n->link);
 }
 else
 n->link=NULL;
}
void displaylist(node *n)
{
 node *n1;
 n1=n;
 if(n1!=NULL)
 {
  printf("%d\n",n->info);
  displaylist(n1->link);
 }
}
void insnode(node *n,int desti)
{
 int cnt=1;
 node *n1, *temp;
 n1=n;
 while(n1!=NULL)
 {
  cnt++;
  if(desti==1)
  {
   temp->link=(node *)malloc(sizeof(node));
   printf("\nEnter the item to be inserted\n");
   scanf("%d",&temp->info);
   temp->link=n1;
   n=temp;
   [B]n1->link;[/B]
   printf("\nNode Inserted Successfully\n");
   printf("\nThe new Linked List elements are\n");
   break;
  }
  else if(desti==cnt)
  {
   temp->link=(node *)malloc(sizeof(node));
   printf("\nEnter the item to be inserted\n");
   scanf("%d",&temp->info);
   temp->link=n1->link;
   n1->link=temp;
   printf("\nNode Inserted Successfully\n");
   printf("\nThe new Linked List elements are\n");
   break;
  }
  n1=n1->link;
 }
 displaylist(n);
}
void main()
{
 node *start;
 int loc;
 clrscr();
 start->link=(node *)malloc(sizeof(node));
 printf("\nCreate a linked list :");
 createlist(start);
 printf("\n\nCreated linked list elements are:\n");
 displaylist(start);
 printf("\nEnter the position at which you want to add new node\n");
 scanf("%d",&loc);
 insnode(start,loc);
 getch();
}
```


----------



## aditya.shevade (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				timemachine said:
			
		

> MinGW : GTK facility is not available. Lacks of some libraries of gcc.
> Downloaded original interface of MinGW but i was not able to find GTK extensions and some binutils.



^^ Yes.. but I am not sure if GTK is cross platform.... correct me if I am wrong. The man just wants to program C. And on any given day, using Linux and gcc is better than cygwin. 

I have seen the roughs of cygwin. Using Linux is far better.


----------



## timemachine (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> ^^ Yes.. but I am not sure if GTK is cross platform.... correct me if I am wrong. The man just wants to program C. And on any given day, using Linux and gcc is better than cygwin.
> 
> I have seen the roughs of cygwin. Using Linux is far better.



You are right. But it is good for those who knows nothing about UNIX or LINUX systems and can't keep them as a OS because they know nothing. They only want to program with gcc and rest use the features of windows(because they love it). Besides the roughs of cygwin, it can be used for beginning, and then it is good to switch over unix or linux. A desktop linux like mandriva is easy to install, dual - boot , and use. And u r right, using Linux or unix with gcc is best. I use it on a seprate machine, windows on a seprate one.


----------



## mehulved (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> ^^ Yes.. but I am not sure if GTK is cross platform.... correct me if I am wrong. The man just wants to program C. And on any given day, using Linux and gcc is better than cygwin.
> 
> I have seen the roughs of cygwin. Using Linux is far better.


GTK is surely available on windows. There's gaim/pidgin and gimp both available for windows. The former surely makes use of GTK on Windows, not sure of the latter.


----------



## Sykora (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

GIMP definitely uses GTK2+ Environment. If I remember correctly, you are required to install it before installing the GIMP itself.


----------



## shady_inc (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

@ Sykora: You have maintained a excellent blog,buddy.


----------



## Zeeshan Quireshi (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> ^^thanks for confirming.Dev c++ has very good gui too.


 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]:
*msdn2.microsoft.com/hi-in/express/aa700735.aspx

or you can down Eclipse C++ Developer Pack Here [FREE}:
*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 .


----------



## aditya.shevade (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				mehulved said:
			
		

> GTK is surely available on windows. There's gaim/pidgin and gimp both available for windows. The former surely makes use of GTK on Windows, not sure of the latter.



hmm... I think I should do a little digging on it and see if I can program my project for this year in GTK and port it to windows..... Hoping for the best.


----------



## ayush_chh (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

pls help me out....and explain the cause of my warning.


----------



## Sykora (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

@shady_inc : Why thank you. 

@ ayush_chh : 
From what I've read of the insnode() function, the code is a mess. 

For example, you're mallocing a block of memory at temp->link, without ever initializing temp.

The second thing is, the statement you've bolded, ie n1->link;, isn't supposed to do anything by itself. Perhaps you meant n1->link = temp or something?

EDIT : On further study, I think what you meant was :


```
if(desti==1)
  {
   [B]temp[/B]=(node *)malloc(sizeof(node));
   printf("\nEnter the item to be inserted\n");
   scanf("%d",&temp->info);
   temp->link=n1;
   n=temp;
   [B]/*n1->link;*/[/B]
   printf("\nNode Inserted Successfully\n");
   printf("\nThe new Linked List elements are\n");
   break;
  }
```


----------



## quan chi (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

well how to get the 40th fibonacci numer.
the below only calculates upto 20 i think.

```
#include<iostream.h>
int fib(int n);
int main
{int n,answer;
cout<<"enter a number"<<endl;
cin>>n;
answer=fib(n);
cout<<answer<<"is the"<<n<<"th fibonacci number"<,endl;
return(0);
}
int fib(int n)
{if(n<3)
{return(1);
}
else
{return(fib(n-2)+fib(n-1));
}
}
```


----------



## Sykora (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Zeeshan Quireshi (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*

@quan_chi , it would me much more efficient(actually bout Infinitely Efficient) to solve the program iteratively rather than recursively .

Also u can use BNU Multi Precision library if you want to work with Infinite(literally) precision .
*gmplib.org/

this way u can calculate as big as ur RAM allows to with no size restraints


----------



## quan chi (Sep 29, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> If that's the case, declare your variables as unsigned long, and then try it.


by that it dosent show any answer it freezes for some time and returns to the program page.



			
				Zeeshan Quireshi said:
			
		

> @quan_chi , it would me much more efficient(actually bout Infinitely Efficient) to solve the program iteratively rather than recursively .
> 
> Also u can use BNU Multi Precision library if you want to work with Infinite(literally) precision .
> *gmplib.org/
> ...



well can you please tell me in detail what it is and how to use it .


----------



## aditya.shevade (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

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


----------



## Gigacore (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

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

*


----------



## Sykora (Sep 30, 2007)

*Re: 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.


----------



## The_Devil_Himself (Sep 30, 2007)

*Re: 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?


----------



## Sykora (Sep 30, 2007)

*Re: 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.


----------



## QwertyManiac (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

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

```
38: 24157817
39: 39088169
[B]40: 63245986[/B]
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:

```
#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:

```
#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.


----------



## Sykora (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

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


```
#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.


----------



## The_Devil_Himself (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

got this:
	
	



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


----------



## QwertyManiac (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

Am getting the same:

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


----------



## Sykora (Sep 30, 2007)

*Re: 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++.


----------



## QwertyManiac (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

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

*img216.imageshack.us/img216/7272/opuk5.jpg

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


----------



## Zeeshan Quireshi (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

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



			
				QwertyManiac said:
			
		

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


----------



## QwertyManiac (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

Yeah got that


----------



## Desi-Tek.com (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> yea man dev c++ looks more geeky(hence cool).Lols.dev c++ is light on resources and thats very important for a IDE.





			
				Zeeshan Quireshi said:
			
		

> 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]:
> *msdn2.microsoft.com/hi-in/express/aa700735.aspx
> ...


or try netbeans 
*www.netbeans.org/images/v5/product-pages/nb-cc-s.png
*www.netbeans.org/products/cplusplus/


----------



## Sykora (Sep 30, 2007)

*Re: 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?


----------



## Gigacore (Sep 30, 2007)

*Re: 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


----------



## Sykora (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Gigacore (Sep 30, 2007)

*Re: 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?


----------



## timemachine (Sep 30, 2007)

*Re: 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


----------



## Gigacore (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

^ thanks buddy. 

i'll try it


----------



## timemachine (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

take the help of turboc++ help function 
it helps a lot really


----------



## Zeeshan Quireshi (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

If you people really Like TC's Interface then u can use DJGPP alond with the RHIDE IDE , which is a direct vopy of TC's user interface but uses GCC(DJGPP) as it's backend and runs perfectly on Win XP .

www.delorie.com/djgpp/

Note: RHIDE can be downloaded from the "Zip Picker" page of DJGPP Site .


----------



## Gigacore (Sep 30, 2007)

*Re: Post ur C/C++ Programs Here*

wow, thats cool. thanks buddy


----------



## ayush_chh (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> @shady_inc : Why thank you.
> 
> @ ayush_chh :
> From what I've read of the insnode() function, the code is a mess.
> ...



Thanks a lot man.....i understood whr i was wrong




			
				Sykora said:
			
		

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



don't have one but i can make a guess ,
 see if the compiler is 64-bit then 
sizeof(int) = 8 byte    because 64 bit/8 bit
now limit will be 16^8 = 4294967296

not sure of this........


----------



## QwertyManiac (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

Yeah that'd be obvious but I think Sykora just wants to confirm it or something ...


----------



## aditya.shevade (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

Hey... was out for some work. Nice proceedings going on. 

Just to add one more thing to the integer range issue, @QuizMaster or Qwerty (I dunno who mentioned it, since the avatars are verymuch similar), our (not only your) education system is faulty.

And, it is now, that I came to know, that there are people who like TurboC/C++'s crap IDE and the entire package...


----------



## QwertyManiac (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

Damn Quiz_Master for plagiarizing my genuine™ avatar 

Hah but my professor hates 'standard'. He says learning all that wasn't necessary in his age and that namespaces etc are just to confuse you, that everything is becoming more technical etc, he hates it


----------



## aditya.shevade (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

^^ He hates that programming is becoming technical? I don't remember when it wasn't technical.....


----------



## Zeeshan Quireshi (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> And, it is now, that I came to know, that there are people who like TurboC/C++'s crap IDE and the entire package...


 Am i mistaken or is it targeted at me


----------



## QwertyManiac (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> ^^ He hates that programming is becoming technical? I don't remember when it wasn't technical.....


Is becoming* more* technical actually


----------



## aditya.shevade (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Zeeshan Quireshi said:
			
		

> Am i mistaken or is it targeted at me



No. It is not targeted at you. It's your choice what you wanna use. 

I am targeting this at some people here (here means where I live) who love it and create compiler specific programs. Like using conio.h and graphics.h etc.

And they make me use it also. And I want freedom. So, I am a bit frustrated.



			
				QwertyManiac said:
			
		

> Is becoming* more* technical actually



.... I can understand


----------



## Zeeshan Quireshi (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## timemachine (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

^^^^^hmmmm gud ........


----------



## aditya.shevade (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Zeeshan Quireshi said:
			
		

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


----------



## timemachine (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## QwertyManiac (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

Yeah, cause ultimately the cleaner code wins, no matter what.


----------



## timemachine (Oct 1, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Zeeshan Quireshi (Oct 2, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

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


----------



## praka123 (Oct 4, 2007)

*Re: 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:
*idealprogrammer.com/languages/cc/introduction-to-c-standford-video-tutorials-and-other-lectures/

got this via  *linuxhelp.blogspot.com/2007/09/collection-of-best-rated-videos-on-c.html (ofcorz not my blog!)


----------



## nithinks (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## Sykora (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*

The only way is to create a new list, going through each node of the previous list and inserting it at the beginning of the new list.

eg :


```
Node *p = head->next;
Node *revHead = head;
head = head->next;
revHead->next = NULL;
while (p != NULL) {
    p = p->next;
    head->next = revHead;
    revHead = head;
    head = p;
}
```

Now you have a new list, with revHead as the head node.


----------



## nithinks (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> The only way is to create a new list, going through each node of the previous list and inserting it at the beginning of the new list.
> 
> eg :
> 
> ...



Fine.. but lets assume that list contains some 1 lack records.. so if thats the case this program will create an overhead... any optimistic code?


----------



## Sykora (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*

How does it create overhead? It isn't creating new nodes, just reinserting them in a new list.


----------



## nithinks (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> How does it create overhead? It isn't creating new nodes, just reinserting them in a new list.



You are right..  but is it not possible to do that without creating another  list?


----------



## Nav11aug (Oct 4, 2007)

*Re: Post ur C/C++ Programs Here*

try this..


```
node *revList(node *head)
{	
	if(head==NULL)
		return head;
		
	node *p,*q,*r;
	p=head;		

	while(p!=NULL){
		r=q=p->next;
		if(q!=NULL){
			q->next=p;
			p=r;
		}		
	}
	
	head=p;
	
	return head;	
}
```


----------



## Glen Apayart (Oct 5, 2007)

*Re: Post ur C/C++ Programs Here*

My brother always use my admin account because i leave my pc on sometimes when im away or sleeping for a while. 

So, I made a *simple conditional statement* for my brother to be reminded about the account he is using.  By changing the icons of my .exe from his  favorite game  icon. hehe 


```
#include <iostream>
using namespace std;

int main()
{
    char Ans;

    cout << "Hello!\n";
    cout << "The program you have choosen has been disabled by the admin,\n";
    cout << "Please use your own account,\n\n";

    do{
    cout << "do you want to exit (y/n)? ";
    cin >> Ans;

        if(Ans == 'n' || Ans =='N')
            cout << "Could you please leave me now...\n\n";
        else if(Ans == 'y' || Ans == 'Y')
            break;
        else
            cout << "Invalid Entry!\n\n";
    }
    while(Ans != 'y' || Ans != 'Y');
        system("cls");
        cout << "Thank you!" << "\n\n";
        cout << "Press any key to exit...";

    return 0;
}
```


----------



## aditya.shevade (Oct 5, 2007)

*Re: Post ur C/C++ Programs Here*

^^ ROFL 

By the way, I am working on a Library Emulation project. For my submissions. A mini project. The problem is that everyone has to do this one only (Library) and our mam wants 80 different source codes. (I am sure mine will be unique ).

It does not use file handling. I will post it here soon.....

Aditya

PS @ Glen Apayart, I just saw you signature... You are a newbie you say, but still. There is no void main in ISO C/C++


----------



## BBThumbHealer (Oct 5, 2007)

*Re: Post ur C/C++ Programs Here*

i m making my project for class xii...its heading its completion , last thing that i wanna do is like  i m making a calendar and a billing dept. calculation center , i wanna print that on a paper using the printer ! is this possible ? if yes , then plz buddies help in coding !


----------



## arunks (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Glen Apayart said:
			
		

> My brother always use my admin account because i leave my pc on sometimes when im away or sleeping for a while.
> 
> So, I made a *simple conditional statement* for my brother to be reminded about the account he is using.  By changing the icons of my .exe from his  favorite game  icon. hehe
> 
> ...



hey what does system("cls") do...?
is this a inbuilt function...? how and what is its usage..?
is this used to execute shell  commands i mean dos commands..


----------



## QwertyManiac (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*



			
				arunks said:
			
		

> hey what does system("cls") do...?
> is this a inbuilt function...? how and what is its usage..?
> is this used to execute shell  commands i mean dos commands..


Yeah it is used to execute commands, or launch other programs too perhaps. 

Your current running program halts when this is called, and continues only after the command called completes execution. System() makes the code OS-Dependent.

*www.phim.unibe.ch/comp_doc/c_manual/C/FUNCTIONS/system.html


----------



## Gigacore (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*

what is typedef


----------



## QwertyManiac (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*

Typedef is commonly used to give any Data Type a new name.

Like for example:

```
#include<iostream>
int main()
{
    typedef int a; [I] // Thus, [B]a[/B] refers automatically to an integer[/I]
    a abc=1, def=0; [I]// Creates two variables of type int,
                              // as the typedef above shows[/I]
    cout<<"ABC = "<<abc<<" DEF = "<<def<<endl;
    return 0;
}
```
This is very useful while working with a lot of classes, or structures. You can name them comfortably or for different usages (Like we use Position and List names in a clear Linked List algorithm but both are essentially the same structure, just used with a different name to aide understanding).


----------



## Gigacore (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*

thanks qwerty


----------



## shyamno (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*

can anyone give me a tutorial on how to ....do user authentication using C..is it possible...

suppose I ..have created a website ...where a member have to login...so how do I check the user verification.....

Any source code...


----------



## BBThumbHealer (Oct 7, 2007)

*Re: Post ur C/C++ Programs Here*



			
				BlackBerry7100g said:
			
		

> i m making my project for class xii...its heading its completion , last thing that i wanna do is like  i m making a calendar and a billing dept. calculation center , i wanna print that on a paper using the printer ! is this possible ? if yes , then plz buddies help in coding !



wud anyone lyk to help in the above case ?


----------



## aditya.shevade (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

I have been having a problem. And someone please help me as soon as you can.

I have designed a project to be submitted in the college for submission purpose. Now, the project is a library database. I have developed a little part and I am attaching it.

When I showed the program to our teacher, she said that I must use inheritance in the program. The problem is that I don't know much about it, and from whatever I read and tried to gather in the last 2 days, I have reached a conclusion that inheritance cannot be used effectively in this case.

So please please tell me where and how to use it. Else I will have to submit this one only.

Aditya


----------



## QwertyManiac (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

Sometimes in colleges, 'effective' isn't the word, its 'you have to'. So implementing it even for a basic thing would satisfy them. Just saying ..

I don't understand 'make' stuff in your files, you use Ajunta? Is coding them all into one file not a good procedure? And the use of header files etc? Wait, how do I even compile it?  Need some enlightenment on this.


----------



## aditya.shevade (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> Sometimes in colleges, 'effective' isn't the word, its 'you have to'. So implementing it even for a basic thing would satisfy them. Just saying ..
> 
> I don't understand 'make' stuff in your files, you use Ajunta? Is coding them all into one file not a good procedure? And the use of header files etc? Wait, how do I even compile it?  Need some enlightenment on this.



I use anjuta. You guessed right. To compile it... I dunno the sommand line method. But if you have Anjuta, then create a new project and add the files in that project. Then click on auto generate the project.

Then compile, make and build to execute.

And after reading professional C++, I have reached the conclusion that creating different files is the best way to make the program easy to understand, modify and expand.

Try if you can, else I will send you the entire project by mail. The compressed (tar.bz2) file is about 1000KB.

Aditya


----------



## [xubz] (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

Has anyone correctly implimented Brent-Salamin algorithm for computing Pi? I never was able to get it right 

(Only thing i've done is Leibniz method of Pi, thats easy, but it takes insane amount to just calculate 10 decimal places accurately! :-/)


----------



## The_Devil_Himself (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

^^lol me too.I am wondering how to compile it using Dev c++.
BTW you are very good at programming Aditya and a clean programmer.


----------



## QwertyManiac (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*



			
				aditya.shevade said:
			
		

> Try if you can, else I will send you the entire project by mail. The compressed (tar.bz2) file is about 1000KB.


 That's okay, never mind, seems beyond my mind right now. Someone else like Yamaraj or Sykora might be able to answer it I s'pose. Am not that good really, yet 

And a doubt:
Does Anjuta automatically create Header files or did you _HAVE_ to code them?


----------



## aditya.shevade (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

^^


----------



## QwertyManiac (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

Alright, am trying my best right now. (I sure am tired after this).

Hopefully would tell you a few ways to implement inheritance into it after going through entirely.

/Me does a sudo apt-get install anjuta

Edit: You need to document your files .. Comments make it easier


----------



## aditya.shevade (Oct 8, 2007)

*Re: Post ur C/C++ Programs Here*

^^ Anjuta is very good.

And I need this by friday.


----------



## vinit suri (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*

hey guys i needed ur help wid a c program.....

cud sm1 plzz post dis program 4 me...plzzzzz
 d program is that....

it should  accept any number between one and thousand and find the first non zero digit of the factorial of dat number from the right hand side.....


plz plz plz help me...


----------



## mehulved (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*

Shouldn't that be easy.
1) Find the factorial
2) Divide it by 10
3) Check the remainder
4) If it's 0 discard it


----------



## vinit suri (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*

d question is which datatype 2 use....
v are talkin abt d factorial of even 1000....
so ders no datatype which can store dat....finding factorial is impossible....

hey guys i needed ur help wid a c program.....

cud sm1 plzz post dis program 4 me...plzzzzz
 d program is that....

it should accept any number between one and thousand and find the first non zero digit of the factorial of dat number from the right hand side.....


plz plz plz help me...
 		 	 		 		 		 		 			 				__________________


----------



## The_Devil_Himself (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*

You can use exponential form i.e. aeb= a into e raised to the power b.Its limits is from -3.4e38 to 3.4e38.Hope this helps.I have never used it so don't ask  how to implement it.

BTW your question looks like picked up from CAT or something.I'm sure of some trick involved.


----------



## aditya.shevade (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*

^^ trick might be that, if you multiply by 1000 then the first non zero from right cannot be 1 to 3 as there will be three zeros already. Also, for 1000, you will have 990 so add one more zero, 980 another zero and so on.

It's not easy this way, but worth a try.


----------



## aditya.shevade (Oct 10, 2007)

*Re: Post ur C/C++ Programs Here*



			
				QwertyManiac said:
			
		

> Edit: You need to document your files .. Comments make it easier



Actually, even I thought I should but after a couple of my friends who are not very good at C/C++ also understood the code just be the names of the variables, I think I can save the trouble.

So, I just added a naming conventions file as a documentation, and forgot to add it in the zip archive.

Here it is by the way, if you would like.

Aditya


----------



## Batistabomb (Oct 11, 2007)

*Re: Post ur C/C++ Programs Here*

do namespacestd,exception handling concepts are working for you in turbo c++   on windows platform ?



			
				Gigacore said:
			
		

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




great thought dude your's going to be the highest replies thread and most helpful in terms of exchanging knowledge


----------



## quan chi (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

guys i have a problem.refer the program below.

i am starting from main.

```
void main()
{char name[30]
int x,y;
cout<<"enter your name"
cin>>name;
cout<<"enter your date of birth month and day only";
cin>>x;
cin>>y;
cout<<"****************"<<name<<"************* "
cout<<" your date of birth is"<<x<<"   "<<y;
if(x==2&y==3)
{cout<<"some result"
}
else
{cout<<"some result"
}
}
```
now in this program if i enter the name as "abceg" 

the program outputs properly.

but if i enter something like "abced ghtyat"
it only takes my name it asks for dob but dosent take any input.
and take the dob as any garbage value by itself.
and outputs the else statements result.

please help.


----------



## The_Devil_Himself (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

^^dude I think you can't use cin to input strings.use gets to input full names(i.e. with space in between).


----------



## Batistabomb (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*



			
				The_Devil_Himself said:
			
		

> ^^dude I think you can't use cin to input strings.use gets to input full names(i.e. with space in between).


you are right cin inputs strings but wont take spaces in the above program if you are typing your name with spaces then suddenly cin looks for the next cin i.e; x,y here 
you can verify this by typing in output like this 

abcd ghyt 1 2

so cout here is being neglected,so keep gets

 #include<iostream.h>
 #include<stdio.h>
 void main()
{      
char name[30];
int x,y;
cout<<"enter your name";
gets(name);
fflush(stdin);
//cout<<endl;
cout<<"enter your date of birth month and day only"<<endl;
cin>>x;
cin>>y;
cout<<"****************"<<name<<"************* ";
cout<<" your date of birth is"<<x<<"   "<<y;
}
/*if(x==2&y==3)

cout<<"some result"

else

cout<<"some result"

} */


----------



## Sykora (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

If you're programming in C, use gets(). If you're programming in C++, use cin.getline()


----------



## Tech.Masti (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

anyone tell me a good C++ problem book name for beginner.......


----------



## The_Devil_Himself (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

^^ robert lafore.


----------



## aditya.shevade (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> If you're programming in C, use gets(). If you're programming in C++, use cin.getline()



I had been wondering about that... thanks. Needs some digging....


----------



## Desi-Tek.com (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

*www.cplusplus.com/

*www.cplusplus.com/doc/tutorial/


----------



## aditya.shevade (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Sykora said:
			
		

> If you're programming in C, use gets(). If you're programming in C++, use cin.getline()



Hey... I did some digging as I said. And if you are using the string input type, then go for getline. Simple getline, not cin.getline.

The syntax is,

string someString;

std::getline(cin, someString);

cin is the same. It's better than cin.getline();

And you should use cin.ignore(); before the getline to make sure that stdin is clear.

Aditya


----------



## Sykora (Oct 12, 2007)

*Re: Post ur C/C++ Programs Here*

You're right. getline is used with the C++ std::string while cin.getline() is used with char*. You should use std::string whenever possible, but if you're dealing with char* (for whichever reason), use cin.getline().


----------



## Gigacore (Oct 13, 2007)

*Re: Post ur C/C++ Programs Here*

how to declare `feof`


----------



## aditya.shevade (Oct 13, 2007)

*Re: Post ur C/C++ Programs Here*

What do you mean by declare feof? 

Syntax of use if feof(file poniter name) and if you mean the key sequence for end of file then it is ctrl+z in windows/dos and ctrl+d in *nix OS.

EDIT :- the syntax of use *is* feof(file pointer name)


----------



## Gigacore (Oct 13, 2007)

*Re: Post ur C/C++ Programs Here*

lol yeah i mean the syntax  
anyway thankx. 

*I'M A NOOB*


----------



## its me (Oct 21, 2007)

*Re: Post ur C/C++ Programs Here*

Hello



I need a program in C++ that convert numbers from Hexadecimal to Binary


thanks


----------



## nightcrawler (Oct 22, 2007)

*Re: Post ur C/C++ Programs Here*



			
				its me said:
			
		

> Hello
> 
> 
> 
> ...



1. Get Input from user in Hexadecimal format. The C scanf() with %x works in C. I am sure cin can directly take input in hexadecimal. BTW you have to preceed the input with a 0xNumber for example 0x1F for 31.

2. Once you have the number apply bit shifting logic or normal method of divide and mod. And get the binary number (that is if you wish to store it). 

If on the other hand if you wish just to print it I think cout lets you do that like it lets you print in hex. Although I am not sure if it can print in binary.

Correct me if I am wrong guys.

Incidentally why would you want to convert a number from hex to binary ?


----------



## ilugd (Oct 22, 2007)

*Re: Post ur C/C++ Programs Here*

much simpler. One hx digit is 4 binary. Just create an array of 16 which matches each hexadecimal character to its binary equivalent and print it out. It is not puritan but gets the job done.


----------



## its me (Oct 22, 2007)

*Re: Post ur C/C++ Programs Here*

Thank you very much


----------



## quan chi (Oct 26, 2007)

*Re: Post ur C/C++ Programs Here*

guys i have a problem please help.
well can anyone please give me a program on 'classes with other classses as member data'.with a bit of explanation.

for eg you can take a rectangle and point class.

actually there is a program for it but i am not able to get it properly
can anyone please explain it me.
here is the program.

```
class point
{private:
  int itsx;   //to hold the x and y co-ordinate
  int itsy;
public:
void setx(int x){itsx=x}
void sety(int y){itsy=y}
int getx()const{return itsx;}
int gety()const{return itsy;}
};

class rectangle
{private:

point itsupperleft;  /* from here i am not understanding.if these are of
point itsupperright;     type point then why the below its top bottom left etc 
point itslowerleft;         has been defined*/   
point itslowerright;

int itstop;
int itsleft;
int itsbottom;
int its right; 

public:
rectangle(int top,int left,int bottom,int right);
~rectangle(){}

*********the accessor functions defined here********

int getarea() const;

};

rectangle::rectangle(int top,etc etc.....)
{itstop=top;
itsleft=left;
etc etc.......;

itsupperleft.setx(left); /*why these declarations */
itsupperleft.sety(top);

itsupperright.setx(right);
itsupperright.sety(top);

etc etc.....;
}
int rectangle::getarea()const
{int width=its right-its left;        /*how they are calculating it
int height=its top-its bottom;        are they subtracting the two opposite
return(width*height);                    points*/

int main()
{body etc etc.......
}
```


 i have pointed my doubts in the program only.
is there any other simpler way to write this program.or can anybody post any other simpler program.

i reffered sams publications jesse liberty and bradley jones book.pg no.165.

please help.


----------



## CadCrazy (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

Here is mine


#include<stdio.h>

void main()
{
    int Money, GirlFriends;

    while(Money!=0)
    {
        GirlFriends++;
        Money--;
     }
     printf("Beggar");

     getch();
}


----------



## mehulved (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

Is it legal to distribute TC?


----------



## gaurav_indian (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				mehulved said:
			
		

> Is it legal to distribute TC?


No.Its not legal.


----------



## Gigacore (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

oops.... i dont know... if it is illegalll.. please remove it


----------



## gaurav_indian (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Gigacore said:
			
		

> oops.... i dont know... if it is illegalll.. please remove it


Edit your post. I hate piracy.


----------



## Gigacore (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

^ so is it legal ?


----------



## CadCrazy (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				gaurav_indian said:
			
		

> I hate piracy.


Abe 100 chuhe kha ke billi haj ko chali. Haj se vapis aa ke phir chuhe khane lagi


----------



## gaurav_indian (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*



			
				CadCrazy said:
			
		

> Abe 100 chuhe kha ke billi haj ko chali. Haj se vapis aa ke phir chuhe khane lagi


sunday ko holiday hoti hai.


----------



## CadCrazy (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

to kya


----------



## QwertyManiac (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

Some sites have the v3.0 in their abandonware list .. But Borland still has a page for it OUTSIDE the museum... I wouldn't know if its perfectly legal or not to distribute it now. But frankly, I cant stand that stupid IDE anymore. Its like staring at a BSOD for 5 hours only to build something equivalent of giving a BSOD in itself. Wonder why people don't move on ...


----------



## aditya.shevade (Oct 28, 2007)

*Re: Post ur C/C++ Programs Here*

Maybe because of the authors of books (indian) which emphasize on TC. Or maybe, like here in my case, my friends use it cause their classes have it. Or maybe because they have to use it in their colleges. 

I hate it by the way.


----------



## Gigacore (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

*A C Program to check whether a given word is Palindrome or not.*

Example for Palindromes: MADAM, MALAYALAM, LEVEL, RADAR etc...


```
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
	char str[10],str2[10];
	printf("Enter a string");
	scanf("%",str1);
	strcpy(str2,str1);
	strrev(str2);
	if(strcmp(str1,str2)==0)
		printf("%s is a palindrome",str1);
	else
		printf("%s is not a palindrome",str1);
getch();
}
```


----------



## mehulved (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

Reading this wikipedia article, I feel it's in a grey area so I am deleting the post. If someone can give me the proof that it's legal, I will restore it.


----------



## Gigacore (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

i think u dont need to delete it... coz i edited the post


----------



## mehulved (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

...while I was deleting it.


----------



## ayush_chh (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

@ gigacore

waht did ya post BTW????

and what is it all abt??


----------



## QwertyManiac (Oct 29, 2007)

*Re: Post ur C/C++ Programs Here*

Link to Turbo C++ 3.0.


----------



## Gigacore (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*

*A Simple C Program to Display the number and its square from 1 to 10 using register variable.*


```
#include <stdio.h>
#include<conio.h>
void main()
{
		register int count, sqr;
	for(count=1;count<=10;count++)
	{
		sqr=count*count;
		printf("\n%d%d",count,sqr);
	}
getch();
}
```

*EDIT: I added a list of all the PROGRAMS in this thread*


----------



## aditya.shevade (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*

@Gigacore, Great work man...


----------



## Gigacore (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*

^ Thanks a lot Buddy


----------



## quan chi (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*

*greetings guys.
well in an urge to make a matrix falling numbers program.(like in the movie) .i made a simple c++ program which is as follows



		Code:
	

#include<iostream.h>
void main()
{
int counter=0;
loop:
counter++;
cout<<counter<<endl;
goto loop;
}

now the problem is the numbers move from below to up.

and how to exit from this program.once run this program rufuses to exitas it has no termination for loop. .

please help me.is there any way by which by pressing 'esc' as like in other programs i an exit from this program.. *


----------



## QwertyManiac (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*

Ctrl+Pause|Break or just close that Window. Yours is not a good way to implement this.

Have a look at programs like cmatrix, which create the exact effect. You can source install it on Linux. Or see here:
*www.asty.org/cmatrix.html


----------



## harryneopotter (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*


```
#include<iostream.h>
void main()
{
int counter=0;
while(!kbhit())
{
counter++;
cout<<counter<<endl;
}
}
```
use this.................it will exit on any key press.


----------



## blackleopard92 (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Gigacore said:
			
		

> *A Simple C Program to Display the number and its square from 1 to 10 using register variable.*
> 
> 
> ```
> ...


won't recommend this method in C++, as modern compilers automatically optimise for loops with universal register counters.


----------



## quan chi (Oct 30, 2007)

*Re: Post ur C/C++ Programs Here*



			
				harryneopotter said:
			
		

> ```
> #include<iostream.h>
> void main()
> {
> ...



thanks harryneopotter



			
				QwertyManiac said:
			
		

> Ctrl+Pause|Break or just close that Window. Yours is not a good way to implement this.
> 
> Have a look at programs like cmatrix, which create the exact effect. You can source install it on Linux. Or see here:
> *www.asty.org/cmatrix.html



well thanks for the link.i have downloaded it but how to run it in windows please explain in detail.


----------



## Gigacore (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*

*A C Program to find the sum of two matrix using two dimensional array.*


```
#include <stdio.h>
#include<conio.h>
void main()
{
	int a[10][10],b[10][10],c[10][10];
	int i,j,n,m;
	printf("Enter the order of matrix:);
	scanf("%d%d",&n,&m);
	printf("Enter the elements of matrix")
	for(i=0;i<n;i++)
	for(j=0;j<n;j++)
	scanf("%d",&b[i][j]);
	for(i=0;i<n;i++)
	{
	for(j=0;j<m;j++)
	{
	c[i][j]=a[i][j]+b[i][j];
	}
	}
	printf("Addition of matrices");
	for(i=0;i<n;i++)
	{
	for(j=0;j<n;j++)
	{
	printf("%d\t",c[i][j]);
	}
	printf("\n");
	}
	getch();
	return(0);
getch();
}
```


----------



## QwertyManiac (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*

^^
Correction, its '*matrices*' and not '*matrixis*'


----------



## Gigacore (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*

^ Oh thanks qwerty


----------



## mehulved (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Gigacore said:
			
		

> ^ Oh thanks qwerty


 ....the spelling nazi!


----------



## QwertyManiac (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*

Won't learning the right stuff help?


----------



## Gigacore (Nov 6, 2007)

*Re: Post ur C/C++ Programs Here*

@ mehul... its common to make mistakes sometimes  .


----------



## MetalheadGautham (Nov 13, 2007)

*Turbo Calc 15000*

*TURBO CALC 15000*
​ 
This is a basic calculator compiled using GCC, but first written using Borland's Turbo C++ IDE 3.0, hence called turbo calc. It has 15 functions, hence 15000



```
/* 
 Turbo Calc 11000 Coppyright(c) Gautham T 
 
 This is freeware, use this software as you 
 like, but the author must be attributed to 
 when making derivatives. This source code may 
 also be distributed with it. Its delivered under 
 GNU GPL Version 3, a coppy of which may be found in 
 www.gnu.org . This software is Designed to 
 illustrate some basic operations with C++ 
 and it uses Turbo C++ IDE 3.0 for compiling 
 although source code is easily ported to 
 other platforms. 
 */ 
 
#include<iostream.h> 
#include<math.h> 
 
/* iostream.h for basic operations 
   conio.h for clrscr() 
   math.h for many of the calculator's functions */ 
 
int main()                                    //calculator function 
 
{ 
 
long double a,b;                               //the two operants 
 
unsigned short int c;                          //choice 
 
cout<<"This is turbocalc 11000, your best choice for a"<<endl; 
cout<<"simple and robust x86 platform based calculator."<<endl<<endl; 
 
cout<<"Type  1 for addition;"<<endl;                           //add 
cout<<"Type  2 for subtraction;"<<endl;                        //sub 
cout<<"Type  3 for multiplication;"<<endl;                     //multi 
cout<<"Type  4 for dividion;"<<endl;                           //div 
cout<<"Type  5 for finding the Square;"<<endl;                 //square 
cout<<"Type  6 for finding the Cube;"<<endl;                   //cube 
cout<<"Type  7 for finding the square root;"<<endl;            //root 
cout<<"Type  8 for finding the sine;"<<endl;                   //sin 
cout<<"Type  9 for finding the cosine;"<<endl;                 //cos 
cout<<"Type 10 for finding the tangent;"<<endl;                //tan 
cout<<"Type 11 for finding the seccant;"<<endl;                //sec 
cout<<"type 12 for finding the coseccant;"<<endl;              //cosec 
cout<<"Type 13 for finding the cotangent;"<<endl;              //cot     
cout<<"Type 14 for finding the natural logarithm;"<<endl;      //log 
cout<<"Type 15 for finding the logarithm to base 10."<<endl;   //log10 
 
cin>>c;                                            //got the choice now 
 
if ((c==1)||(c==2)||(c==3)||(c==4)) 
{ 
cout<<"Enter the first number:"<<endl; 
cin>>a; 
cout<<endl<<endl<<"Enter the second number:"<<endl; 
cin>>b; 
} 
else if((c==5)||(c==6)||(c==7)||(c==8)||(c==9)||(c==10)||(c==11)||(c==12)||(c==13)||(c==14)||(c==15)) 
{ 
cout<<"enter the number: "<<endl; 
cin>>a; 
} 
else 
{ 
cout<<"You must only enter a number from 1 to 15."<<endl; 
} 
 
if (c==1) 
cout<<"The Sum is     "<<a+b<<endl; 
 
else if (c==2) 
cout<<"The Difference is      "<<a-b<<endl; 
 
else if (c==3) 
cout<<"The Product is     "<<a*b<<endl; 
 
else if (c==4) 
cout<<"The Quotient is     "<<a/b<<endl; 
 
else if (c==5) 
cout<<"The Square is     "<<a*a<<endl; 
 
else if (c==6) 
cout<<"The Cube is     "<<a*a*a<<endl; 
 
else if (c==7) 
cout<<"The Square Root is     "<<sqrt(a)<<endl; 
 
else if (c==8) 
cout<<"The Sine is     "<<sin(a)<<endl; 
 
else if (c==9) 
cout<<"The Cosine is     "<<cos(a)<<endl; 
 
else if (c==10) 
cout<<"The Tangent is     "<<tan(a)<<endl; 
 
else if (c==11) 
cout<<"The Seccant is     "<<1/(cos(a))<<endl; 
 
else if (c==12) 
cout<<"The Coseccant is     "<<1/(sin(a))<<endl; 
 
else if (c==13) 
cout<<"The Cotangent is     "<<1/(tan(a))<<endl; 
 
else if (c==14) 
cout<<"The Natural Logarithm is     "<<log(a)<<endl; 
 
else if (c==15) 
cout<<"The Logarithm to base 10 is     "<<log10(a)<<endl; 
 
else 
cout<<"There must be an error in what you typed."<<endl<<"Try Again."; 
 
return 0; 
}
```
PS: I am a rookie C++ programmer. I had learnt C in the begening of class 6(lol) but forgot it(lol again)

I made this because I just wanted to try something that looks usable. Please excuse my n00bishness

I regret the fact that we have only Turbo C++ in CBSE senior secondary scyllabus. Anjuta IDE and Dev-Cpp along with MinGW Developer Studio are forgotton. CBSE I suppose, is full fo linux haters.


----------



## Nav11aug (Nov 14, 2007)

*Re: 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


----------



## Gigacore (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*

did anyone try the turbo calc ?

i've prob with my compiler..


----------



## [xubz] (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*



			
				Gigacore said:
			
		

> 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


----------



## Gigacore (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*

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


----------



## MetalheadGautham (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*



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



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


----------



## Sykora (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*

Offtopic : 



> nice program? isn't this supposed to be a n00bish bit of code?(*what else can you expect from a cbse programmer?*)



Oi! I may decide to take that as an insult 

"Noobish code" is where you start on your way to greatness. Everyone does noobish code at the beginning. Just don't stay a noob for too long  .

Ontopic : How can you say it compiled with gcc if you used nonstandard header files and outdated syntax?


----------



## QwertyManiac (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*



			
				MetalheadGautham said:
			
		

> know it... but I still prefer if clause...


A switch() block is perhaps faster than an if-else cascading block. Its something to do with jump tables. C compilers automatically optimize a switch block into a branch/jump table. 

But of course, it (switch) has its limitations too, like handling only integral data types (No strings, etc).


----------



## [xubz] (Nov 14, 2007)

*Re: 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 


```
#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


----------



## QwertyManiac (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*



			
				[xubz] said:
			
		

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


----------



## mehulved (Nov 14, 2007)

*Re: Post ur C/C++ Programs Here*

Or use python


----------



## QwertyManiac (Nov 14, 2007)

*Re: 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


----------



## Sykora (Nov 15, 2007)

*Re: 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.


----------



## [xubz] (Nov 15, 2007)

*Re: Post ur C/C++ Programs Here*

Hmmm, Python Shells, Google-ing revealed PyShell, Lemme Try it


----------



## QwertyManiac (Nov 15, 2007)

*Re: 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!


----------



## srikanth.9849671439 (Nov 29, 2007)

*Re: 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


----------



## sandeep9796 (Dec 20, 2007)

*Re: 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???


----------



## mehulved (Dec 25, 2007)

*Re: Post ur C/C++ Programs Here*



			
				sandeep9796 said:
			
		

> 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 *minnie.tuhs.org/UnixTree/V7/usr/src/cmd/ls.c.html


----------



## nvidia (Dec 25, 2007)

*Re: Post ur C/C++ Programs Here*



			
				srikanth.9849671439 said:
			
		

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

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


----------



## girish.g (Jan 8, 2008)

*Re: Post ur C/C++ Programs Here*

please help in the following programs
1 finding triangle matrix in a given matrix
2 to find sum of series:  x-(x^2)/3!+(x^3)/5!-(x^4)/7!+(x^5)/9!.......... upto n terms(where x^2 is x square x^3 is x cube and so on and ! is factorial)
3 to convert binary to decimal
 please this is urgent as i have to submit a project in school


----------



## Sykora (Jan 8, 2008)

*Re: Post ur C/C++ Programs Here*



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


----------



## Faun (Jan 8, 2008)

*Re: Post ur C/C++ Programs Here*



Sykora said:


> Thanks for saving us the trouble of finding out if it was homework...


amen


----------



## Gigacore (Jan 8, 2008)

*Re: Post ur C/C++ Programs Here*

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


----------



## arun_cool (Jan 10, 2008)

*Re: 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


----------



## shady_inc (Jan 21, 2008)

*Re: 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*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;
}

_


----------



## QwertyManiac (Jan 21, 2008)

*Re: Post ur C/C++ Programs Here*



shady_inc said:


> ```
> #include <iostream>
> using namespace std;
> int main()
> ...


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.


```
#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:

```
#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;
}
```


----------



## shady_inc (Jan 21, 2008)

*Re: 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 ..


----------



## ilugd (Jan 22, 2008)

*Re: Post ur C/C++ Programs Here*

something like this will work?

```
#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];
  }
```


----------



## Jove (Jan 30, 2008)

*Re: 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, 

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


----------



## mavihs (Feb 7, 2008)

*Re: Post ur C/C++ Programs Here*

function 2 input a matrix:-

```
void input(int A[10][10], int &R, int &C)
{
     int i, j;
     cout<<"enter the no. of rows:";
     cin>>R;
    cout<<"Enter the no. of columns:";
    cin>>C;
    for(i=0; i<R; i++)
      {
         for(j=0; j<C; j++)
          {
            cin>>A[i][j];
          }
        }
}
```


----------



## mavihs (Feb 18, 2008)

*Re: Post ur C/C++ Programs Here*


```
/* WAP to execute the following function:
    -> Read an integer & an integer array & search for that integer in the intger array & return its position, incase the number is not there in the list, function should return -1.*/

int search(int siz, int ele, int arr[]);
void main()
{
    clrscr();
    int arr[25], siz, i, ele, j;
    cout<<"Enter the number of elements:";
    cin>>siz;
    cout<<"Enter the array:";
    for(i=0; i<siz; i++)
    {
        cin>>arr[i];
        cout<<"\t";
    }
    cout<<"Enter the element to be searched";
    cin>>ele;
    k=search(siz, ele, arr);
    if(j==-1)
        cout<<"Element not found";
    else
        cout<<"The element found at"<<j<<"th position";
        getch();
}
int search(int siz, int ele, int arr[])
{
    int pos=-1;
    for(int i=0; i<siz; i++)
    {
        if(ele==arr[i])
        {
            pos=i;
            break;
        }
        else
        pos=2;
    }
    if(pos==1)
    {
        return(i+1);
    }
    else
    {
        return(-1);
    }
}
```


----------



## QwertyManiac (Feb 19, 2008)

*Re: Post ur C/C++ Programs Here*



mavihs said:


> ```
> /* WAP to execute the following function:
> -> Read an integer & an integer array & search for that integer in the intger array & return its position, incase the number is not there in the list, function should return -1.*/
> 
> ...


The entire thing in simple Python: (Thought it might help the bunch of shifters here)


```
n = int(raw_input("Enter the no of elements: "))
print "Enter the elements:"
a = [int(raw_input()) for x in range(0,n)]
c = int(raw_input("Enter a number to search: "))
print a.index(c) if c in a else -1
```


----------



## Pathik (Feb 19, 2008)

*Re: Post ur C/C++ Programs Here*

EDIT:


QwertyManiac said:


> The entire thing in simple Python: (Thought it might help the bunch of shifters here)


^^ I think it s helping me already..


----------



## QwertyManiac (Feb 19, 2008)

*Re: Post ur C/C++ Programs Here*

What wasn't working in the first place?


----------



## grvpuri (Feb 21, 2008)

*Re: Post ur C/C++ Programs Here*

//Program to perform operations on a binary search tree

#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node *left;
node *right;
};
class bstree
{
private:
node *root;
public:
bstree()
{
root=NULL;
}
~bstree()
{
cout<<"\nDestructor called\n";
inorder_destroy(root);
}
node* search(int,node*&)const;
void insert(int);
void del(int);
void traverse()const;
void inorder(node*)const;
void preorder(node*)const;
void postorder(node*)const;
void inorder_destroy(node*);
};
node* bstree::search(int item,node *&parent)const
{
node *ptr=NULL;
parent=NULL;
if(root!=NULL)
{
ptr=root;
parent=NULL;
while(ptr!=NULL)
{
if(item==ptr->data)
return ptr;
parent=ptr;
if(item<ptr->data)
ptr=ptr->left;
else
ptr=ptr->right;
}
}
return ptr;
}
void bstree::insert(int item)
{
node *parent;
if(search(item,parent)!=NULL)
{
cout<<"\nSuch a node already exists\n";
getch();
return;
}
node *temp=new node;
temp->data=item;
temp->left=NULL;
temp->right=NULL;
if(parent==NULL)
{
root=temp;
return;
}
if(item<parent->data)
parent->left=temp;
else
parent->right=temp;
}
void bstree::traverse()const
{
if(root==NULL)
{
cout<<"\nTree empty\n";
getch();
return;
}
cout<<"\nInorder\n\n";
inorder(root);
cout<<"\nPreorder\n\n";
preorder(root);
cout<<"\nPostorder\n\n";
postorder(root);
getch();
}
void bstree::inorder(node *n)const
{
if(n!=NULL)
{
inorder(n->left);
cout<<n->data<<"\t";
inorder(n->right);
}
}
void bstree:reorder(node *n)const
{
if(n!=NULL)
{
cout<<n->data<<"\t";
preorder(n->left);
preorder(n->right);
}
}
void bstree:ostorder(node *n)const
{
if(n!=NULL)
{
postorder(n->left);
postorder(n->right);
cout<<n->data<<"\t";
}
}
void bstree::del(int item)
{
node *parent;
if(root==NULL)
{
cout<<"\nTree empty\n";
getch();
return;
}
node *loc=search(item,parent);
if(loc==NULL)
{
cout<<"\nNode not found\n";
getch();
return;
}
node *ptr=NULL;
if(loc->left!=NULL && loc->right!=NULL)
{
ptr=loc->right;
parent=loc;
while(ptr->left!=NULL)
{
parent=ptr;
ptr=ptr->left;
}
loc->data=ptr->data;
loc=ptr;
}
if(loc->left==NULL)
ptr=loc->right;
else if(loc->right==NULL)
ptr=loc->left;
if(parent==NULL)
root=ptr;
else if(loc==parent->left)
parent->left=ptr;
else
parent->right=ptr;
delete loc;
cout<<"\nNode Deleted\n";
getch();
}
void bstree::inorder_destroy(node *r)
{
if(r!=NULL)
{
inorder_destroy(r->left);
del(r->data);
inorder_destroy(r->right);
}
}
int main()
{
bstree b;
int choice,flag=1,item;
while(flag)
{
clrscr();
cout<<"\n\t\t\t1-Insert";
cout<<"\n\t\t\t2-Delete";
cout<<"\n\t\t\t3-Traverse";
cout<<"\n\t\t\t4-Exit";
cout<<"\n\tEnter your choice:-";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter the item to insert ";
cin>>item;
b.insert(item);
break;
case 2:
cout<<"\nEnter the item to delete ";
cin>>item;
b.del(item);
break;
case 3:
b.traverse();
break;
case 4:
flag=0;
break;
default:
continue;
}
}
getch();
return 0;
}


----------



## aniket.awati (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*

Hello friends, 
I have devoloped a sudoku game using cpp. Please evaluate this
code. I have used Borland Turbo cpp 3.0 compiler and hence it is windows based and 16 bit.I know iI should shift to more advanced and open source devolopement enviornments, and I am going to do just that. 
But it would be very nice of you to overlook this drawback and give me your suggestions on the logic in the code. I would also like to know about open source graphics libraries.

One more thing, initialy i wanted to code this thing using c language. But I couldn't use clock_t in 'c'. 
Hence i changed it to 'cpp' just for that. As a result you may see printf and scanf used in 'cpp' coding.
Though it is not advisable, I can't help it as it is very time consuming to change it, now that the code has gone on to 800 lines.

you can get it here : *www.esnips.com/web/aniket-programming


----------



## mehulved (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*



aniket.awati said:


> I would also like to know about open source graphics libraries.


Qt? svgalib?


----------



## aniket.awati (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*

Is that a graphic library? svgalib?


----------



## aditya.shevade (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*

^^ Yes it is a graphics library (and a very good one, as Mehul was kind enough to let me know about it).

@ Mehul, we can use Qt for drawing lines? You serious? And I read that Qt is not entirely free on Windows.... shade more light....


----------



## mehulved (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*

Qt is under dual license. GPL and commercial version. The license enforcement doesn't happening according to the platform but according to the nature of your project.
If your project is in open source then you can use the GPL'ed version of Qt, which is available free of cost on any supported platform.
If you're having a commercial project i.e. non-open source, even if it's free of cost, you have to used commercial version of Qt, which costs money. Sykpe and Opera are made using the paid version. The paid version is one license per user and not per computer. See *trolltech.com/developer/downloads/qt/faq
Yeah, you do not get Qt *binaries* on windows. You will have to compile Qt on your own using mingw. See *trolltech.com/developer/downloads/qt/windows
I don't exactly know the difference between graphic capabilities of different libraries out there, but you could check Qt documents for your info. Basically Qt is a GUI programming library for C++ that's as far as I know.


----------



## aditya.shevade (Mar 18, 2008)

*Re: Post ur C/C++ Programs Here*

^^ That is what I thought... Qt is a GUI development thing.... and aniket.awati wants something to draw lines and circles.....


----------



## baccilus (Mar 19, 2008)

*Re: Post ur C/C++ Programs Here*

Here's a program to calculate the computer sales man salary. Base salary, bonus rate and commission are fixed. Input of price per system and number of systems sold is from user.


```
#include<stdio.h>
#define BASE_SAL 2000.0
#define BONUS 200.0
#define COMMISSION 0.02

//Compiled on linux using geany

int main()
{
    int n;
    float bonus, commission, price;
    float gross_sal;
    printf("\nInput the number of systems sold  ",n);
    scanf("%d",&n);
    printf("\nInput the price of each computer  ",price);
    scanf("%f",&price);
    bonus=BONUS*n;
    commission=COMMISSION*price*n;
    gross_sal=BASE_SAL+bonus+commission;
    printf("Base salary is %f\nBonus is %f\nCommission is %f\nGross salary is %f"
    ,BASE_SAL,commission,gross_sal);
}
```

Gross salary is coming out to be wrong but I don't know why. Please tell if you realize that.


----------



## QwertyManiac (Mar 19, 2008)

*Re: Post ur C/C++ Programs Here*

You missed a variable in your printf() statement. The bonus variable I suppose. Or BONUS. 


```
#include<stdio.h>
#define BASE_SAL 2000.0
#define BONUS 200.0
#define COMMISSION 0.02

//Compiled on linux using geany

int main()
{
    int n;
    float bonus, commission, price;
    float gross_sal;
    printf("\nInput the number of systems sold  ",n);
    scanf("%d",&n);
    printf("\nInput the price of each computer  ",price);
    scanf("%f",&price);
    bonus=BONUS*n;
    commission=COMMISSION*price*n;
    gross_sal=BASE_SAL+bonus+commission;
    printf("Base salary is %f\nBonus is %f\nCommission is %f\nGross salary is %f\n"
    ,BASE_SAL,[B]bonus[/B],commission,gross_sal);
}
```


----------



## baccilus (Mar 19, 2008)

*Re: Post ur C/C++ Programs Here*

Thanks. Got it !!


----------



## radonryder (Mar 20, 2008)

*Re: Post ur C/C++ Programs Here*

A lot of this stuff form my comp text..
I can prepare 4 my comp boards with digitXD
Well here's what I did for my school project
It basicaly an inventory tracker software...
I coded the entire thing myself..
I just custumised the menu's for a gunshop...
Im open to reviews.Tell me what you guys think of it....

                 >>>GUNSHOP<<<

```
#include<iostream.h>
#include<stdio.h>
#include<process.h>
#include<string.h>
#include<fstream.h>
#include<conio.h>
class staff
{
char sname[20];                                             //name of employee
int age;                                                    //age of employee
float salary;                                               //salary of employee
char job[20];                                               //type of job done(eg-cashier,delivery man)
public:

void inputs()
{
	cout<<"\nEnter New employee's Name:\n";
	gets(sname);
	cout<<"\nEnter New employee's Age:\n";
	cin>>age;
	cout<<"\nEnter New employee's job:\n";
	gets(job);
	cout<<"\nEnter New employee's Salary:\n";
	cin>>salary;
}
void displays()
{  cout<<"\n";
	cout<<sname;
	cout<<"\t\t"<<age;
	cout<<"\t\t"<<job;
	cout<<"\t\t"<<salary;
}
int searchst(char st1[20])                                          //search by name of employee
{
	if(strcmp(st1,sname)==0)
	return 0;
	else
	return 1;
}
																						  //search by job of employee
	int searchjs(char j1[20] )
{
	if(strcmp(j1,job)==0)
	return 0;
	else
	return 1;
}



};
class guns
{
char gname[20];                                                  //name of gun
char gtype[20];                                                 //type of gun(eg-pistol,shotgun,etc)
int stock;
float cost;																		//no: of guns in stock
public:

void inputg()                                                    //for inputing gun details
{
	cout<<"\nEnter Gun Name:\n";
	gets(gname);
	cout<<"\nEnter Type of Gun:\n";
	gets(gtype);
	cout<<"\nEnter Gun's Price:\n";
	cin>>cost;
	cout<<"\nEnter the Number of Guns in stock:\n";
	cin>>stock;
}

void displayg()                                                  //for displaying gun details
{  cout<<"\n";
	cout<<gname;
	cout<<"\t\t"<<gtype;
	cout<<"\t\t"<<cost;
	cout<<"\t\t"<<stock;
}
int rtstk()
{
return stock;
}

int searchgn(char gn1[20])                                       //search by gun name
{
	if(strcmp(gn1,gname)==0)
	return 0;
	else
	return 1;
}

	int searchct(char ty1[20] )                                    //search by gun type
{
	if(strcmp(ty1,gtype)==0)
	return 0;
	else
	return 1;
}

																					 //updated stock
void update(int i)
{
	 stock=stock+i;


}                                                              //updates cost
void update1()
{
float cos;
cout<<"\nEnter New price:\n";
cin>>cos;
cost=cos;
}                                                       //for purchasing
void update2(int i)
{
stock=stock-i;
}
};
guns g1;
staff s1;
void main()
{
char str[20],a;
fstream f1,f2,f3;
char ch1;
int n,ch,i,j,k,ch3;
char ch4;
cout<<"\n \n\n\nWelcome to Ammunation";
do
{  clrscr();                                                              //start of 1st do while
	cout<<"\nSelect access level";
	cout<<"\n1.Staff";
	cout<<"\n2.Admin";
	cout<<"\n3.Exit\n";
	cin>>ch;
if(ch==1)
{clrscr();
do                                                             //start of staff menu
{
cout<<"\n\nStaff Menu";                                        //gun management
cout<<"\n----------------------------------------";
cout<<"\n1.Display all Guns";
cout<<"\n2.Search by Gun Name";
cout<<"\n3.Search by Gun Type";
cout<<"\n4.Purchase Guns";
cout<<"\n5.Add more Guns";
cout<<"\n6.Update Gun details";
cout<<"\n7.Delete Guns";
cout<<"\n8.Restore deleted Guns";
cout<<"\n9.Create Backup";
cout<<"\n10.restore basckup(Caution!!->Use only if Backup File exits)";
cout<<"\n11.Clear Screen";
cout<<"\nEnter your choice\n";
cin>>ch3;
switch (ch3)
{
case 1:
			f1.open("gun1.dat",ios::in);
			f1.read((char*)&g1,sizeof(g1));
			cout<<"\nGun details";
			cout<<":\n--------------------------";
			cout<<"\nName\t"<<"\tType\t"<<"\tPrice\t"<<"\tStock\t";
			while(f1)
			{
			g1.displayg();
			f1.read((char*)&g1,sizeof(g1));
			}
			f1.close();
			break;
case 2:
			cout<<"\nEnter the Name of the Gun:\n";
			gets(str);
			f1.open("gun1.dat",ios::in);
			f1.read((char*)&g1,sizeof(g1));
			while(f1)
			{

			n=g1.searchgn(str);
			if(n==0)
				{
			cout<<"\nGun details";
			cout<<":\n--------------------------";
			cout<<"\nName\t"<<"\tType\t"<<"\tPrice\t"<<"\tStock\t";
			g1.displayg();
					break;
				}
			f1.read((char*)&g1,sizeof(g1));
			}
			if(n==1)
			{
			cout<<"\nThe Gun was Not Found";
			}
			f1.close();




			break;

case 3:  cout<<"\nEnter Type of Gun:\n";
			gets(str);
			f1.open("gun1.dat",ios::in);
			f1.read((char*)&g1,sizeof(g1));
         i=0;
			while(f1)
			{

			n=g1.searchct(str);
			if(n==0)
				{i++;
				if(i==1)
				cout<<"\nGun details";
			cout<<":\n--------------------------";
			cout<<"\nName\t"<<"\tType\t"<<"\tPrice\t"<<"\tStock\t";
				 g1.displayg();
					break;
				}
			f1.read((char*)&g1,sizeof(g1));
			}
			if(n==1)
			{
			cout<<"\nThere are no guns of "<<str<<" Type";
			}
			f1.close();
			break;

case 4:
			cout<<"\nEnter the Name of the Gun:\n";
			gets(str);
			f1.open("gun1.dat",ios::in|ios::out);
			f1.read((char*)&g1,sizeof(g1));
			k=sizeof(g1);
			while(f1)
			{
			n=g1.searchgn(str);

			if(n==0)
				{
				i=g1.rtstk();
				cout<<"\nEnter the Number of Guns to be Purchased:\n";
				cin>>j;
				if(j>i)
				{
					cout<<"\nThe Number of guns Requested is Not in Stock";
					cout<<"\nOnly "<<i<<" Are Available";
					cout<<"\nDo u still wish to buy?:/n";
					cin>>a;
					if(a=='y'||a=='Y')
					{f1.seekp(-k,ios::cur);
					g1.update2(j);

				 f1.write((char*)&g1,sizeof(g1));
					cout<<"\nPurchased ";
					}
				}
				else
				{ f1.seekp(-k,ios::cur);
					g1.update2(j);

				 f1.write((char*)&g1,sizeof(g1));
					cout<<"\nPurchased ";
				}
				 break;
				}
			f1.read((char*)&g1,sizeof(g1));

			}

			if(n==1)
			{
				cout<<"\nGun not in stock";
			}




			f1.close();



			break;
case 5:
			f1.open("gun1.dat",ios::out|ios::app);
			cout<<"\nEnter the no: of guns:\n";
			cin>>n;
			cout<<"\nEnter Gun Details:\n";
			cout<<"---------------------------------";
			for(i=0;i<n;i++)
			 {
			  g1.inputg();
				f1.write((char*)&g1,sizeof(g1));
			 }

			 f1.close();
			 break;


case 6:	cout<<"\nEnter the Name of the Gun:\n";
			gets(str);
			k=sizeof(g1);
			f1.open("gun1.dat",ios::in|ios::out);
			f1.read((char*)&g1,sizeof(g1));
			while(f1)
			{

			n=g1.searchgn(str);
			if(n==0)
				{
				 g1.update1();
				 cout<<"\nEnter the no: of guns delivered:\n";
				 cin>>i;
             f1.seekp(-k,ios::cur);
				 g1.update(i);

				 f1.write((char*)&g1,sizeof(g1));
				 cout<<"\nUpdated";
					break;
				}
			f1.read((char*)&g1,sizeof(g1));
			}
			if(n==1)
			{
			cout<<"\nThe Gun was Not Found";
			}
			f1.close();


			break;
case 7: f1.open("gun1.dat",ios::in);
		 f2.open("gun2.dat",ios::out|ios::app);
		 f3.open ("gun3.dat",ios::out|ios::app);
		 cout<<"\nEnter Name of the gun";
			gets(str);
			i=0;
			f1.read((char*)&s1,sizeof(s1));
			while(f1)
			{
			n=g1.searchgn(str);
			if(n==0)
			{i++;
			f3.write((char*)&g1,sizeof(g1));
			}
			if(n==1)
			{
			 f2.write((char*)&g1,sizeof(g1));
			}
			f1.read((char*)&g1,sizeof(g1));
			}
			f1.close();
			f2.close();
			f3.close();
			remove("gun1.dat");
			rename("gun2.dat","gun1.dat");
			if(i==0)
			cout<<"\nGun not found";
			break;

case 8: f1.open("gun1.dat",ios::out|ios::app);
		 f2.open("gun3.dat",ios::in);
		 cout<<"\nEnter the Gun's Name:\n";
		 gets(str);
		 i=0;
		 while(f2)
		 {
		 n=g1.searchgn(str);
		 if(n==0)
		 {i++;
		 f1.write((char*)&g1,sizeof(g1));
		 }
		 f2.read((char*)&g1,sizeof(g1));
		 }
		 if(i==0)
		 cout<<"\nGun not found";
		 else
		 cout<<"\nGun Restored";
		 f1.close();
		 f2.close();

			break;
case 9:  f1.open("gun1.dat",ios::in);
			f2.open("bkg.dat",ios::out|ios::app);
			f1.read((char*)&g1,sizeof(g1));

			while(f1)
			{
			f2.write((char*)&g1,sizeof(g1));
			f1.read((char*)&g1,sizeof(g1));
			}
			f2.close();
			f1.close();
			cout<<"\nBackUp Created";
			break;

case 10: remove("gun1.dat");
			rename("bkg.dat","gun1.dat");
			cout<<"\nBackup Restored";
			break;
case 11:
			clrscr();
			break;
default:cout<<"\nWrong choice\n";

}
	cout<<"\nDo u wish to continue?";
	cin>>ch4;

}while(ch4=='y'||ch4=='Y');
											 //end of staff menu
}
if(ch==2)
{

clrscr();
do
{
cout<<"\n\nAdmin Menu";                                     //employee management
cout<<"\n----------------------------------------";
cout<<"\n1.Search by Name of employee";
cout<<"\n2.Display all Staff Details";
cout<<"\n3.Display staff in a specific Catagory ";
cout<<"\n4.Update employee Details";
cout<<"\n5.Hire Staff";
cout<<"\n6.Fire Staff";
cout<<"\n7.Fired Staff History";
cout<<"\n8.Rehire staff";
cout<<"\n9.Create Backup";
cout<<"\n10.restore basckup(Caution!!->Use only if Backup File exits)";
cout<<"\n11.Clear screen";
cout<<"\nEnter Choice?";
cin>>ch3;
switch(ch3)
{
case 1:  f1.open("stf1.dat",ios::in);
			f1.read((char*)&s1,sizeof(s1));
			cout<<"\nEnter Name of the Employee:\n";
			gets(str);
			while(f1)
			{
			n=s1.searchst(str);
			if(n==0)
			{
			cout<<"\nEmployee Details";
			cout<<"\n-----------------------";
			cout<<"\nName\t"<<"\tAge\t"<<"\tJob\t"<<"\tSalary\t";
			s1.displays();
			break;
			}
			f1.read((char*)&s1,sizeof(s1));
			}
			f1.close();
			if(n==1)
			cout<<"\nEmployee does Not Work here";
			break;

case 2:
			f1.open("stf1.dat",ios::in);
			f1.read((char*)&s1,sizeof(s1));
			cout<<"\nEmployee Details";
			cout<<"\n-----------------------";
			cout<<"\nName\t"<<"\tAge\t"<<"\tJob\t"<<"\tSalary\t";

			while(f1)
			{
			s1.displays();
			f1.read((char*)&s1,sizeof(s1));
			}
			f1.close();
			break;

case 3:  i=0;
			f1.open("stf1.dat",ios::in);
			f1.read((char*)&s1,sizeof(s1));
			cout<<"\nPlease Enter job of the employee";
			gets(str);
			while(f1)
			{
			n=s1.searchjs(str);
			if(n==0)
			{i++;
			if(i==1)
			{
			cout<<"\nEmployee Details";
			cout<<"\n-----------------------";
			cout<<"\nName\t"<<"\tAge\t"<<"\tJob\t"<<"\tSalary\t";
			}
			s1.displays();
			}
			f1.read((char*)&s1,sizeof(s1));
			}
			f1.close();
			if(i==0)
							break;
case 4:f1.open("stf1.dat",ios::out|ios::in);
		 cout<<"\nEnter the Employee's Name:\n";
		 gets(str);
		 i=sizeof(s1);
		 f1.read((char*)&s1,sizeof(s1));
		 while(f1)
		 {
		 n=s1.searchst(str);
		 if(n==0)
		 {
		 f1.seekg(-i,ios::cur);
		 cout<<"\nEnter New Details";
		 cout<<":\n--------------------------";
		 s1.inputs();
		 f1.write((char*)&s1,sizeof(s1));
		 break;
		 }
		 f1.read((char*)&s1,sizeof(s1));
		 }
		 if(n==1)
		 cout<<"\nEmployee does Not work here";
		 f1.close();
							break;
case 5: f1.open("stf1.dat",ios::out|ios::app);
		  cout<<"\nEnter the no: New employees:\n";
		  cin>>n;
		  cout<<"\nEnter New employee details";
        cout<<":\n--------------------------";
		  for(i=0;i<n;i++)
			{
			 s1.inputs();
			 f1.write((char*)&s1,sizeof(s1));
			}

		  f1.close();
		  break;

case 6:f1.open("stf1.dat",ios::in);
		 f2.open("stf2.dat",ios::out|ios::app);
		 f3.open ("stf3.dat",ios::out|ios::app);
		 cout<<"\nEnter Name of the Employee:\n";
			gets(str);
			i=0;
			f1.read((char*)&s1,sizeof(s1));
			while(f1)
			{
			n=s1.searchst(str);
			if(n==0)
			{i++;
			f3.write((char*)&s1,sizeof(s1));
			}
			if(n==1)
			{
			 f2.write((char*)&s1,sizeof(s1));
			}
			f1.read((char*)&s1,sizeof(s1));
			}
			f1.close();
			f2.close();
			f3.close();
			remove("stf1.dat");
			rename("stf2.dat","stf1.dat");
			if(i==0)
			cout<<"\nEmployee does Not Work here";
			break;


case 7:
		 f1.open("stf3.dat",ios::in);
			f1.read((char*)&s1,sizeof(s1));
			cout<<"\nFired Employee Histiry";
			cout<<"\n-----------------------";
			cout<<"\nName\t"<<"\tAge\t"<<"\tJob\t"<<"\tSalary\t";

			while(f1)
			{
			s1.displays();
			f1.read((char*)&s1,sizeof(s1));
			}
			f1.close();
			break;
case 8:f1.open("stf1.dat",ios::out|ios::app);
		 f2.open("stf3.dat",ios::in);
		 cout<<"\nEnter the Employee's Name:\n";
		 gets(str);
		 i=0;
		 while(f2)
		 {
		 n=s1.searchst(str);
		 if(n==0)
		 {i++;
		 f1.write((char*)&s1,sizeof(s1));
		 }
		 f2.read((char*)&s1,sizeof(s1));
		 }
		 if(i==0)
		 cout<<"\nName not found";
		 else
		 cout<<"\nEmployee rehired";
		 f1.close();
		 f2.close();
		 break;
case 9:  f1.open("stf1.dat",ios::in);
			f2.open("bks.dat",ios::out|ios::app);
			f1.read((char*)&s1,sizeof(s1));

			while(f1)
			{
			f2.write((char*)&s1,sizeof(s1));
			f1.read((char*)&s1,sizeof(s1));
			}
			f2.close();
			f1.close();
			cout<<"\nBackUp Created";
			break;

case 10: remove("stf1.dat");
			rename("bks.dat","stf1.dat");
			cout<<"\nBackup Restored";
							break;
case 11:

				clrscr();
							break;
default:
	cout<<"\nWrong Choice";

}
	cout<<"\nDo you wish to continue?";
	cin>>ch4;
}while(ch4=='y'||ch4=='Y');
}
if(ch==3)
{

	clrscr();
	exit(0);
}
else
{
	cout<<"\nWrong choice";

cout<<"\nDo u wish to select another access level";
cin>>ch1;

}
}while(ch1=='y'|ch1=='Y');

cout<<"\n\n\n\n";
clrscr();

}                                             //end of program
```


----------



## deviprasad742 (Mar 27, 2008)

*Re: Post ur C/C++ Programs Here*

Code For Sudoku:

Here is the code to solve Sudoku which i wrote in C

It's bit-lenghty but it can solve all difficulty levels

here is the input format to be given at the command prompt
--->./a.out

11 5
12 4
14 6
15 1
19 8
23 1
25 9 
29 4
31 1
33 5
37 7
40 9
44 2
47 6
49 8
51 3
55 2
61 7
66 5
68 3
69 6
-1

0-80 is the  grid numbers

the format should be [grid number(0-80)  [1-9]

input should end with -1;



Here is the source code:


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

int check,zcount;


int update(int pos);
int re_update(int pos);


struct  str
{
int num;
int flag[10];
int group[20];
};



int count[81],once=0;

typedef struct str mynode;

mynode node[81];



///////////////////////////////////////////////




//////////////////////////////////////////////

int main()
{
int i,temp,temp_n[81],tcount=0,num,index;
int n[81];

for(i=0;i<81;i++)
n[i]=0;







printf("\n");



/*---------------------------Taking input------------------------------------*/



printf("\nEnter the index 0-80  and number  1-9\n");
printf("\nEnter -1  to  solve the puzzle \n");

while(1)
{

scanf("%d",&index);



if(index==-1)
break;

scanf("%d",&num);

 if(num>9||num<1||index>80||index<0)
{
printf("\n.......Invalid input.........\n");
continue;
}

else if(node[index].num!=0)
{
printf("\n.......Already filled........\n");
continue;
}

else
{
node[index].num=num;
update(index);
tcount++;
}



}

zcount=81-tcount;

printf("\n-------------------The number of filled places is %d------------------\n",tcount);







for(i=0;i<81;i++)
printf("%2d  ",count[i]);
printf("\n");






tcount=0;


printf("\n\n");

printf("\n\n");


for(i=0;i<81;i++)
{
printf("%2d  ",node[i].num);

if(node[i].num==0)
tcount++;

if((i+1)%3==0)
printf("    ");

if((i+1)%9==0)
printf("\n\n");

if((i+1)%27==0)
printf("\n");

}




printf("\n-------------------The number of unfilled places is %d------------------\n",tcount);





for(i=0;i<81;i++)
n[i]=node[i].num;



for(i=0;i<81;i++)
{
temp_n[i]=n[i];
temp=check_error(i,n);

if(temp==-1)
{
printf("\n\n");
printf("-------Puzzle cannot be solved -------- ");
printf("\n\n");
printf("-------Error at block %d -------- ",i);
printf("\n\n");
exit(0);
}

}




temp=0;

temp=sudoku();



if(temp==-1)
printf("\n Puzzle is not solved \n");



for(i=0;i<81;i++)
printf("%2d  ",count[i]);
printf("\n");




printf("\n\n");

tcount =0;
for(i=0;i<81;i++)
{
printf("%d  ",node[i].num);

if(node[i].num==0)
tcount++;

if((i+1)%3==0)
printf("    ");

if((i+1)%9==0)
printf("\n\n");

if((i+1)%27==0)
printf("\n");
 
}












}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////







///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


int sudoku()
{
int i,j,k,error=0,numb=8,flag=0,s_error=0,n[81],temp=0 ;




while(zcount!=0)
{

flag=1;


for(i=0;i<81;i++)
{

if(count[i]==numb&&node[i].num==0)
{
flag=0; //indicating that  a node with required count is present in the loop;

for(j=1;j<10;j++)
if(node[i].flag[j]==0)
{
node[i].flag[j]=1;
node[i].num=j;
printf("\n<------Element %2d set to %d------->",i,j);


count[i]++;
zcount--;



error=update(i);

if(error==-1)
{
printf("\n---reupdating started");
re_update(i);
count[i]--;
zcount++;
node[i].flag[j]=0;
printf("\n---reupdating finished");
continue;
}

else
s_error=sudoku();

if(s_error==-1)
{
re_update(i);
count[i]--;
zcount++;
node[i].flag[j]=0;
continue;
}

//printf("\n----> zeroes-%2d",zcount);

printf("\n---Breaking");

break;
}
else
continue;

if(error==-1||s_error==-1)
return -1;

}

if(zcount==0)
break;

}



if(flag==1)
numb--;





}


/*
for(i=0;i<81;i++)
printf("%2d  ",count[i]);
printf("\n");
*/



if(once==1)
{

for(i=0;i<81;i++)
n[i]=node[i].num;


for(i=0;i<81;i++)
{
temp=check_error(i,n);

if(temp==-1)
{
printf("\n\n");
printf("-------Puzzle wrongly solved -------- ");
printf("\n\n");
printf("-------Error at block %d -------- ",i);
printf("\n\n");
exit(0);
}

}


exit(0);
}


printf("\n\n");

printf("\n\n");

for(i=0;i<81;i++)
{
printf("%2d  ",node[i].num);

if((i+1)%3==0)
printf("    ");

if((i+1)%9==0)
printf("\n\n");

if((i+1)%27==0)
printf("\n");
 
}

once=1;

return 0;
}













///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////








///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


int check_error(int pos,int *block)
{

int m,n,index,t_num,flag=0,t_index,i,j;

i=pos/9;
j=pos%9;
index=i*9+j;

if(block[index]!=0)
{
t_num=block[index];


for(m=0;m<9;m++)
{

if(m!=i)
{
t_index=m*9+j;
if(block[t_index]==t_num)
flag=1;
}

if(m!=j)
{
t_index=9*i+m;
if(block[t_index]==t_num)
flag=1;
}

if(flag==1)
{
//printf("--------->Break at %d---pos=%d<-----------\n",m,pos);
return -1;
}

// row and  column check completed;
}

/////////////1


for(m=i+1;m>=0;m++)
{

if(m%3==0)
break;

for(n=j+1;n>=0;n++)
{
if(n%3==0)
break;

t_index=9*m+n;

if(block[t_index]==t_num)
{
//printf("--------->Break at %d %d---pos=%d-------------->\n",m,n,pos);
return -1;
}

}
}


/////////2

for(m=i+1;m>=0;m++)
{

if(m%3==0)
break;

for(n=j-1;n>=0;n--)
{
if(n%3==2)
break;

t_index=9*m+n;

if(block[t_index]==t_num)
{
//printf("--------->Break at %d %d-------------->\n",m,n);
return -1;
}

}
}


///////////////3

for(m=i-1;m>=0;m--)
{

if(m%3==2)
break;

for(n=j-1;n>=0;n--)
{
if(n%3==2)
break;

t_index=9*m+n;

if(block[t_index]==t_num)
{
//printf("--------->Break at %d %d-------------->\n",m,n);
return -1;
}

}
}

//// 4

for(m=i-1;m>=0;m--)
{

if(m%3==2)
break;

for(n=j+1;n>=0;n++)
{
if(n%3==0)
break;

t_index=9*m+n;

if(block[t_index]==t_num)
{
//printf("--------->Break at %d %d-------------->\n",m,n);
return -1;
}

}
}





//end of num!=0 check;
}





return 0;

}






///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////








///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


int update(int pos)
{

int m,n,index,t_num,flag=0,t_index,i,j,l,error=0;

i=pos/9;
j=pos%9;
index=i*9+j;

if(node[index].num!=0)
{
t_num=node[index].num;


for(m=0;m<9;m++)
{



if(m!=i)
{
t_index=m*9+j;

if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;

if(count[t_index]==9&&node[t_index].num==0)
error=-1;





for(l=0;l<20;l++)
if(node[index].group[l]==0)
{

if(t_index==0)
t_index=-1;

node[index].group[l]=t_index;
break;
}
else
continue;

}


}


if(m!=j)
{
t_index=9*i+m;


if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;

if(count[t_index]==9&&node[t_index].num==0)
error=-1;


for(l=0;l<20;l++)
if(node[index].group[l]==0)
{
if(t_index==0)
t_index=-1;
node[index].group[l]=t_index;
break;
}
else
continue;

}



}

// row and  column check completed;
}

/////////////1


for(m=i+1;m>=0;m++)
{

if(m%3==0)
break;

for(n=j+1;n>=0;n++)
{
if(n%3==0)
break;

t_index=9*m+n;


if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;

if(count[t_index]==9&&node[t_index].num==0)
error=-1;




for(l=0;l<20;l++)
if(node[index].group[l]==0)
{
if(t_index==0)
t_index=-1;
node[index].group[l]=t_index;
break;
}
else
continue;

}



}
}


/////////2

for(m=i+1;m>=0;m++)
{

if(m%3==0)
break;

for(n=j-1;n>=0;n--)
{
if(n%3==2)
break;

t_index=9*m+n;


if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;

if(count[t_index]==9&&node[t_index].num==0)
error=-1;


for(l=0;l<20;l++)
if(node[index].group[l]==0)
{
if(t_index==0)
t_index=-1;
node[index].group[l]=t_index;
break;
}
else
continue;

}



}
}



///////////////3

for(m=i-1;m>=0;m--)
{

if(m%3==2)
break;

for(n=j-1;n>=0;n--)
{
if(n%3==2)
break;

t_index=9*m+n;

if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;


if(count[t_index]==9&&node[t_index].num==0)
error=-1;

for(l=0;l<20;l++)
if(node[index].group[l]==0)
{
if(t_index==0)
t_index=-1;
node[index].group[l]=t_index;
break;
}
else
continue;

}




}
}

//// 4

for(m=i-1;m>=0;m--)
{

if(m%3==2)
break;

for(n=j+1;n>=0;n++)
{
if(n%3==0)
break;

t_index=9*m+n;


if(node[t_index].flag[t_num]==0)
{
node[t_index].flag[t_num]=1;
count[t_index]++;


if(count[t_index]==9&&node[t_index].num==0)
error=-1;


for(l=0;l<20;l++)
if(node[index].group[l]==0)
{
if(t_index==0)
t_index=-1;
node[index].group[l]=t_index;
break;
}
else
continue;

}



}
}





//end of num!=0 check;
}



if(error==-1)
printf("\nError at --%d \n",pos);

return error;

}







///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////








///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


int re_update(int pos)
{

int m,n,index,t_num,flag=0,t_index,i,j,l;

i=pos/9;
j=pos%9;
index=i*9+j;

if(node[index].num!=0)
{
t_num=node[index].num;
node[index].num=0;

for(l=0;l<20;l++)
{

if(node[index].group[l]==0)
break;

t_index=node[index].group[l];

if(t_index==-1)
t_index=0;

node[t_index].flag[t_num]=0;
count[t_index]--;
node[index].group[l]=0;

}






}







return 0;

}
```


----------



## hsetir (Apr 30, 2008)

*Re: Post ur C/C++ Programs Here*

I suggest for long codes you also present the algo used in brief.


----------



## Sykora (Apr 30, 2008)

*Re: Post ur C/C++ Programs Here*

You could have cut the length of the code down to half if you removed all the groups of empty lines


----------



## deb_gopal (May 1, 2008)

*Re: Post ur C/C++ Programs Here*

can any body give the visual basic 6 code for popup date calendar to date field and saving & loading photo through picture box control to access database ?
pls help me


----------



## [xubz] (May 10, 2008)

*Re: Post ur C/C++ Programs Here*

Heh! Made this as a challenge to a friend who started a debate about graphics.h.. Its a simple DOS Text-based alien shooter game.. The following code is released under Creative Commons Share Alike, Attribution License.

Compiles Obviously only on TC.. A Lame one.. I know :-\


```
/* DESTROY TEH ALIENS (c) [XUBZ] */
#include<stdio.h>
#include<conio.h>
#include<dos.h>

/* Total no of Shots to give for shooting down 10 Aliens */
#define NUMSHOTS 11

char alien[80];
int score;
int shots;
int lastflag = 0;
int alienpos = 3;
int aliensound = 100;

void drawmain(int pos)
{
	int i;
	clrscr();

	/* Draw the Ground */
	for(i = 1; i <= 80; i++) {
		gotoxy(i, 24);
		textcolor(GREEN);
		cprintf("_");
		gotoxy(i, 7);
		textcolor(BLUE);
		cprintf("_");
		gotoxy(i, 24);
	}

	/* Draw the Cannon based on Current Position */
	textcolor(RED);
	gotoxy(pos, 23);
	cprintf(" || ");
	textcolor(GREEN);
	gotoxy(pos, 24);
	cprintf("|__|");
	textcolor(BLUE);
	gotoxy(pos+1, 7); /* For Shot Marker on the Top */
	cprintf(".");

	/* Draw the 'Quit' and 'New Game' Messages */
	gotoxy(2, 2);
	textcolor(RED);
	cprintf("Press Q to Exit");
	gotoxy(2, 3);
	cprintf("Press N for New Game");

	/* Draw the Current Cannon Position */
	gotoxy(66, 2);
	textcolor(YELLOW);
	cprintf("Position: %d", pos);

	/* Draw the Score */
	gotoxy(66, 5);
	textcolor(BLUE);
	cprintf("Score: %d", score);

	/* Draw No. of Shots */
	gotoxy(66, 6);
	textcolor(RED);
	cprintf("Shots Left: %d", shots);

	gotoxy(2, 6);
	textcolor(YELLOW);
	cprintf("DESTROY TEH ALIENS(tm) v0.1 (C) [XUBZ]");

	/* Draw the Aliens */
	if (!lastflag) {
		alienpos = (alienpos == 3) ? 0 : alienpos;
		aliensound = (aliensound == 250) ? 100 : aliensound;
		gotoxy(1+(alienpos++), 10);
	} else {
		gotoxy(alienpos, 10);
	}

	for (i = 0; i < 80; i++) {
		textcolor(WHITE);
		cprintf("%c", alien[i]);
	}

	if (!lastflag) {
		gotoxy(80, 25);
		sound(aliensound);
		delay(50);
		aliensound += 50;
		nosound();
	}

	/* If Score is 10; Show 'You Won' and Play Music ^_^ */
	if (score == 10) {
		gotoxy(36, 15);
		textcolor(YELLOW);
		cprintf("YOU WON!");
		gotoxy(30, 16);
		cprintf("Press N for New Game");
		if (!lastflag) {
			sound(250);
			delay(100);
			sound(450);
			delay(100);
			sound(350);
			delay(100);
			sound(450);
			delay(100);
			sound(350);
			delay(100);
			nosound();
			lastflag = 1;
		}
	}

	/* If No Shots left and score is NOT 10; Show 'Game Over' and Play Music */
	if (shots == 0 && score != 10) {
		gotoxy(35, 15);
		textcolor(RED);
		cprintf("GAME OVER");
		gotoxy(30, 16);
		cprintf("Press N for New Game");
		if (!lastflag) {
			sound(250);
			delay(100);
			sound(350);
			delay(100);
			sound(450);
			delay(100);
			nosound();
			lastflag = 1;
		}
	}

	/* Move the Cursor to End of the Screen for reducing color corruption :-\ */
	textcolor(BLUE);
	gotoxy(80, 25);
}

void newgame()
{
	int i;
	for(i = 0; i < 80; i++)
		alien[i] = '\0';

	/* Alien Positions */
	alien[6] = '0';
	alien[13] = '8';
	alien[18] = '0';
	alien[25] = '0';
	alien[65] = '0';
	alien[32] = '8';
	alien[45] = '0';
	alien[50] = '8';
	alien[58] = '0';
	alien[73] = '0';

	/* Set/Reset the No. of Shots, Score and Flag */
	score = 0;
	shots = NUMSHOTS;
	lastflag = 0;
	alienpos = 3;
	aliensound = 100;
}

void main()
{
	char c;
	int i, curpos = 38;
	clrscr();

	/* Draw Title Screen */
	newgame();
	gotoxy(30, 10);
	textcolor(GREEN);
	cprintf("DESTROY TEH ALIENS(tm)");
	gotoxy(33, 12);
	textcolor(YELLOW);
	cprintf("Press N to Start!");
	gotoxy(80, 25);
	textcolor(BLUE);

	while(c != 'q' && c != 'Q') {
		c = getch();

		/* Move the Cannon; \K is ASCII for Left Key and \M for Right */
		if (c == '\K' || c == '\M') {
			if (c == '\K') {
				if (curpos >= 3)
					curpos--;
			} else if (c == '\M') {
				if (curpos <= 75)
					curpos++;
			}
			drawmain(curpos);
		}

		/* Shoot the Alien and Register the Shots/Score */
		if (c == ' ') {
			if (!lastflag) {
				sound(400);
				delay(100);
			}
			if (curpos >= 2 && curpos <= 76)
				if (shots > 0) {

					if (alien[curpos-(alienpos-1)] == '0' || alien[curpos-(alienpos-1)] == '8') {
						alien[curpos-(alienpos-1)] = '*';
						sound(600);
						delay(100);
						score++;
					}
					shots--;
				}
			nosound();
			drawmain(curpos);
		}

		/* Reset the Game */
		if (c == 'n' || c == 'N') {
			newgame();
			curpos = 38;
			drawmain(curpos);
		}
	}
}
```


----------



## hero_techno (May 16, 2008)

*Re: Post ur C/C++ Programs Here*

#include<fstream.h>
void main()
{hey can anyone send me or make a c++ project for me based on anything...but includes, deletion, insertion, modification, addition, editing....for my class 12 project..no need of graphics n 1 thing laso i  need this based on data file handling and class;
}


----------



## QwertyManiac (May 16, 2008)

*Re: Post ur C/C++ Programs Here*

I could help you do your class 12 project, but for a reasonable sum.

#include<fstream.h>
void main()
{
Is that okay with you or are you gonna learn more than #include(s) ?
}


----------



## legolas (May 16, 2008)

*Re: Post ur C/C++ Programs Here*

there are plenty of sites which offer you what you need which you can get on google, which spoil your academics. Its a project. This is the time for you to learn.


----------



## hero_techno (May 19, 2008)

*Re: Post ur C/C++ Programs Here*

i know!! i can make project myself...but prolem is that ...i don have any time to do that....


----------



## QwertyManiac (May 19, 2008)

*Re: Post ur C/C++ Programs Here*

Imagine that.

How did you reason out that we would have time for your academics, when you do not have it yourself?


----------



## Cool Joe (Jun 3, 2008)

*Re: Post ur C/C++ Programs Here*

This is my program written in C. it does unit conversions.

```
#include<stdio.h>
#include<conio.h>
main()
{
int opt,con;
float in,cm,ina,cma,ft,m,ma,fta,m1,y,m1a,ya,km,mile,mile1,km1,nmile,metre;
float nmile1,metre1,usgal,usl,usgal1,usl1,ukl,ukgal,ukl1,ukgal1,gram,oz;
float oz1,gram1,kg,lbs,lbs1,kg1,kw,hp,kw1,hp1,df,dc,df1,dc1;
clrscr();

printf("------------------------------Converter by Shishir------------------------------\n");
printf("\n1.Conversions\n");
printf("\n2.About Converter\n");
printf("\n3.Exit\n");
printf("\nEnter your choice:");
scanf("%d",&opt);

if(opt==1)
{
clrscr();
printf("\n1.inch to centimetre  2.centimetre to inch\n");
printf("\n3.foot to metre       4.metre to foot\n");
printf("\n5.yard to metre       6.metre to yard\n");
printf("\n7.mile to kilometre   8.kilometre to mile\n");
printf("\n9.n mile to metre     10.metre to n mile\n");
printf("\n11.US gal to litre    12.litre to US gal\n");
printf("\n13.UK gal to litre    14.litre to UK gal\n");
printf("\n15.Oz to gram         16.gram to Oz\n");
printf("\n17.pound to Kg        18.Kg to pound\n");
printf("\n19.hp to kw           20.kw to hp\n");
printf("\nEnter your unit of conversion:");
scanf("%d",&con);

if(con==1)
{
clrscr();
printf("How many inches? :");
scanf("%f",&in);
cm=in*2.54;
printf("\n\nConversion is %f CM",cm);
}

else if(con==2)
{
clrscr();
printf("How many centimtres? :");
scanf("%f",&cma);
ina=cma/2.54;
printf("\n\nConversion is %f IN",ina);
}

else if(con==3)
{
clrscr();
printf("How many feet? :");
scanf("%f",&ft);
m=ft/3.280839895;
printf("\n\nConversion is %f M",m);
}
else if(con==4)
{
clrscr();
printf("How many metres? :");
scanf("%f",&ma);
fta=ma*3.280839895;
printf("\n\nConversion is %f FT",fta);
}

else if(con==5)
{
clrscr();
printf("How many yards? :");
scanf("%f",&y);
m1=y/1.093613298;
printf("\n\nConversion is %f M",m1);
}

else if(con==6)
{
clrscr();
printf("How many metres? :");
scanf("%f",&m1a);
ya=m1a*1.093613298;
printf("\n\nConversion is %f Y",ya);
}

else if(con==7)
{
clrscr();
printf("How many miles? :");
scanf("%f",&mile);
km=mile*1.609344;
printf("\n\nConversion is %f KM",km);
}

else if(con==8)
{
clrscr();
printf("How many KMs? :");
scanf("%f",&km1);
mile1=km1/1.609344;
printf("\n\nConversion is %f miles",mile1);
}

else if(con==9)
{
clrscr();
printf("How many nautical miles? :");
scanf("%f",&nmile);
metre=nmile*1852;
printf("\n\nConversion is %f M",metre);
}
else if(con==10)
{
clrscr();
printf("How many metres? :");
scanf("%f",&metre1);
nmile1=metre1/1852;
printf("\n\nConversion is %f N MILES",nmile1);
}
else if(con==11)
{
clrscr();
printf("How many US gallons? :");
scanf("%f",&usgal);
usl=usgal*3.785412;
printf("\n\nConversion is %f L",usl);
}

else if(con==12)
{
clrscr();
printf("How many litres? :");
scanf("%f",&usl1);
usgal1=usl1/3.785412;
printf("\n\nConversion is %f US GAL",usgal1);
}

else if(con==13)
{
clrscr();
printf("How many UK gallons? :");
scanf("%f",&ukgal);
ukl=ukgal*4.54609;
printf("\n\nConversion is %f L",ukl);
}

else if(con==14)
{
clrscr();
printf("How many litres? :");
scanf("%f",&ukl1);
ukgal1=ukl1/4.54609;
printf("\n\nConversion is %f UK GAL",ukgal1);
}

else if(con==15)
{
clrscr();
printf("How many oz? :");
scanf("%f",&oz);
gram=oz*28.34952;
printf("\n\nConversion is %f G",gram);
}

else if(con==16)
{
clrscr();
printf("How many grams? :");
scanf("%f",&gram1);
oz1=gram1/28.34952;
printf("\n\nConversion is %f OZ",oz1);
}

else if(con==17)
{
clrscr();
printf("How many lbs? :");
scanf("%f",&lbs);
kg=lbs/2.204622476;
printf("\n\nConversion is %f KG",kg);
}

else if(con==18)
{
clrscr();
printf("How many kgs? :");
scanf("%f",&kg1);
lbs1=kg1*2.204622476;
printf("\n\nConversion is %f LBS",lbs1);
}

else if(con==19)
{
clrscr();
printf("How much hp? :");
scanf("%f",&hp);
kw=hp/1.341021859;
printf("\n\nConversion is %f KWs",kw);
}

else if(con==20)
{
clrscr();
printf("How many KWs? :");
scanf("%f",&kw1);
hp1=kw1*1.341021859;
printf("\n\nConversion is %f HP",hp1);
}

}

else if(opt==2)
{
clrscr();
printf("\nThis is a freeware by Shishir Upadhya.");
}

else if(opt==3)
{
printf("\nPress any key to exit...");
}

getch();
}
```

plz tell me wat u think abt it.



----------



## aditya.shevade (Jun 4, 2008)

*Re: Post ur C/C++ Programs Here*

^^ use 
	
	



```
put your code
```
 to insert code.


----------



## Cool Joe (Jun 5, 2008)

*Re: Post ur C/C++ Programs Here*

riiiiiiight!!!


----------



## mehulved (Jun 6, 2008)

*Re: Post ur C/C++ Programs Here*

beta testing's program working with gcc - *blog.mehulved.com/conversion-0.1.tar.bz2
Also, added a while loop so that it runs till exited and cleaned up a bit of formatting.


----------



## aditya.shevade (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

mehul on a mission...


----------



## mehulved (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

Yeah BTW, version 0.2 is done now of the same program, with if-else if replaced with switch-case on recommendations of people on IRC. I have also broken down the conversion part into a different file. It is available at *blog.mehulved.com/conversion-0.2.tar.bz2
Some more work going on.


----------



## QwertyManiac (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

Its better if you make it into functions than switch cases evaluating it, speaking for programs that would "scale" more.


----------



## mehulved (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*



QwertyManiac said:


> Its better if you make it into functions than switch cases evaluating it, speaking for programs that would "scale" more.


Yeah I have been thinking of something on that lines since the morning but yours is a better idea. I will harass you if I face any problems in this 
BTW, can someone tell me how to make C program wait for keyboard input. I tried getchar() but doesn't work, I guess it is because it is inside a loop or doesn't have exit after it. I will paste the relevant code in a while.


----------



## QwertyManiac (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

I don't think thats there in standard C, you will need (n)curses.


----------



## mehulved (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

getchar() is available in stdio.h
yes getch() from ncurses is an option but I would prefer if there's a way without adding additional header files.


----------



## QwertyManiac (Jun 9, 2008)

*Re: Post ur C/C++ Programs Here*

Is what I meant, getch() like functionality is not in standard C, probably OS stuff thats why...


----------



## mehulved (Jun 10, 2008)

*Re: Post ur C/C++ Programs Here*

Then how does this work?

```
while(c=getchar())
putchar(c);
```


----------



## aditya.shevade (Jun 11, 2008)

*Re: Post ur C/C++ Programs Here*

mehul. He said getch() is not standard. getchar is standard.


----------



## mehulved (Jun 12, 2008)

*Re: Post ur C/C++ Programs Here*



aditya.shevade said:


> mehul. He said getch() is not standard. getchar is standard.


I am very much aware of that but the confusion was about the functionality.


----------



## QwertyManiac (Jun 12, 2008)

*Re: Post ur C/C++ Programs Here*

That works as its intended to. The characters are in a buffer until return is hit while input, and till then the function does not know that any character has been input or not. getch() or getche() non-standard implementations see each character entered as you do and thus can be used for keyboard shortcuts stuff.


----------



## aniket.awati (Jun 16, 2008)

*Re: Post ur C/C++ Programs Here*

Mehul. How about while(!kbhit).this will keep refreshing the o/p screen and put a grand loop to get the o/p by getch or getchar whatever. put it just after the loop(inner),so that getch or getchar takes input from buffer.


----------



## Sykora (Jun 16, 2008)

*Re: Post ur C/C++ Programs Here*

kbhit is non-stanrdard.


----------



## c2tarun (Jun 21, 2008)

*Re: Post ur C/C++ Programs Here*

#include<stdio.h>
#include<conio.h>

int* pntr(int *m)
	{
   for (int i=0;i<5;i++)
      {
   	scanf("%d",m);
      m++;
      }
   return (m);
   }

void main()
{
int a;
int *k;
k=pntr(&a);
for(int i=0;i<5;i++)
	{
   k--;
   printf("%d\t",*k);
   }
}

/* This program should take 5 numbers from user and print them in the reverse order as they entered.........
It's a simple program but its not working!!!!!!
It is printing 5 number and then some more worthless characters in turbo c++
Can anyone plz tell me why this is happening */


----------



## Sykora (Jun 21, 2008)

*Re: Post ur C/C++ Programs Here*

You're trying to store 5 integers when you've only allocated space for 1. Declare a as an array, and see what happens.


----------



## c2tarun (Jun 23, 2008)

*Re: Post ur C/C++ Programs Here*

thank you for suggesting to use an array sykora.........
i know that will work..........
what the problem is i am storing the number at different memory locations and retreiving them from there only.........
i am also changing the memory location........
and after all it is printing the output but with useless characters..........
/* IF POSSIBLE DON'T TELL ME ANY ALTERNATIVES, TELL ME WHY THIS IS WRONG */
THANK YOU


----------



## aniket.awati (Jun 23, 2008)

*Re: Post ur C/C++ Programs Here*



c2tarun said:


> what the problem is i am storing the number at different memory locations and retreiving them from there only.........
> i am also changing the memory location........



I think what sykora means by an array is array of pointers. If you use that you will get different memory locations AND they will be static so that you will retrieve them from there only.

And, the some garbage o/p that you get after the printing is due to the null characters in the 
buffer. scanf leaves null character on the buffer, so you would better use flushall() if you use scanf in a loop.

Again you will get normal o/p if you just replace printf/scanf by cout/cin.


----------



## ngtw (Jun 23, 2008)

*Re: Post ur C/C++ Programs Here*

What is the c++ code to find the prime number for let the user to input the integer? Here is my java code help me translate to c++ code.
int i, a, sum=1;

 for(i=2; i<=50;i++) {
  for(a=2; a<i; a++) {

   if ((i%a)==0)
    sum=0;
   }

  if (sum==1) 

  System.out.println(i+" ");

  sum=1;
 }

Help me change my java code to c++ code.
for (int i=0; i<10; i++)
        System.out.print(fib(i)+", ");


	public static int fib(int n) {
                if (n < 2) 
                 return n;

                else 

		   return fib(n-1)+fib(n-2);
                }


----------



## Sykora (Jun 24, 2008)

*Re: Post ur C/C++ Programs Here*



> [*You're trying to store 5 integers when you've only allocated space for 1.* Declare a as an array, and see what happens.





> /* IF POSSIBLE DON'T TELL ME ANY ALTERNATIVES, TELL ME WHY THIS IS WRONG */



Did you even read my entire post? It wasn't that long.

You're allocating space for _one_ integer here :



> int a;



You're then creating a pointer to it here :



> int *k



But then, you're treating that pointer like an array, here :



> int* pntr(int *m)
> {
> for (int i=0;i<5;i++)
> {
> ...



In doing this, you are accessing memory outside of the space that you declared with "int a;". This memory outside your variable is _not_ guaranteed to remain the same between accesses.

As you are using a screwed compiler in Turbo C, it ignores this and prints whatever is there at the time, which is junk. When I compile your program with gcc, it segfaults, and with good reason.


----------



## achalaxp (Jun 25, 2008)

*Re: Post ur C/C++ Programs Here*

Please reply if U know the meaning of "1LL<< x" in C language 

Thanx


----------



## mehulved (Jun 25, 2008)

*Re: Post ur C/C++ Programs Here*



achalaxp said:


> Please reply if U know the meaning of "1LL<< x" in C language
> 
> Thanx


Did you ever try anything? How much do you understand?

Try this program, it may help you understand *rafb.net/p/5tSNGv95.html


----------



## achalaxp (Jun 26, 2008)

*Re: Post ur C/C++ Programs Here*

Thanx for the example program , I also found such programmes but couldnt find the definition of "1LL"

also i couldnt compile ur example in VC++ 6 give me on that too.

---------------------------------------------------------------------------

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

int main(int argc, char *argv[]) {

 int x;
 printf("Enter digits to shift > ");
 scanf("%d", &x);

*->* printf("%Ld\n",1LL<<x);
 printf("%Ld\n",1LL);

 exit(0);
 return(0);
}










C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(11) : error C2059: syntax error : 'bad suffix on number'
C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(11) : error C2146: syntax error : missing ')' before identifier 'L'
C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(11) : error C2059: syntax error : ')'
C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(12) : error C2059: syntax error : 'bad suffix on number'
C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(12) : error C2146: syntax error : missing ')' before identifier 'L'
C:\Program Files\Microsoft Visual Studio\MyProjects\Test\Text.c(12) : error C2059: syntax error : ')'
Error executing cl.exe.
Text.obj - 6 error(s), 0 warning(s)

-------------------------------------------------------------------------------------------

please give that also...

Thax


----------



## aditya.shevade (Jun 26, 2008)

*Re: Post ur C/C++ Programs Here*

Please insert your code inside 
	
	



```
code here [/ code]
```


----------



## mehulved (Jun 26, 2008)

*Re: Post ur C/C++ Programs Here*



achalaxp said:


> Thanx for the example program , I also found such programmes but couldnt find the definition of "1LL"


That's integer 1 but it's long long 1. L is for long.


achalaxp said:


> also i couldnt compile ur example in VC++ 6 give me on that too.
> please give that also...


I don't have VS nor windows, thus I can't do that. My program doesn't have any errors per se so if you run it on gcc it will work. Maybe someone like dheeraj_kumar or ZeeshanQ can point out why it is going wrong with VC++.
And isn't VC++ 6 really old? VS Express Edition should be available for free, try that.


----------



## c2tarun (Jun 30, 2008)

*Re: Post ur C/C++ Programs Here*



Sykora said:


> Did you even read my entire post? It wasn't that long.
> 
> You're allocating space for _one_ integer here :
> 
> ...


 







Thanx Sykora
thanx for everything you explained me........
that really helped me a lot........
good day


----------



## hjpotter92 (Jul 8, 2008)

*Re: Post ur C/C++ Programs Here*

OK than I will be straight forward. The link is right here


----------



## red_devil (Jul 13, 2008)

*Re: Post ur C/C++ Programs Here*

was going through one of the online resources suggested in another thread...

found this one randomly... but i didn't understand why the following was used..

```
cp == &in_line[LINELNG-1]
```
Pls tell me why that was used...[the code is highlighted in red  ]


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

#define LINELNG 100     /* max. length of input line */

main(){
      char in_line[LINELNG];
      char *cp;
      int c;

      cp = in_line;
      while((c = getc(stdin)) != EOF){
              if([COLOR=Red][B]cp == &in_line[LINELNG-1][/B][/COLOR] || c == '\n'){
                      /*
                       * Insert end-of-line marker
                       */
                      *cp = 0;
                      if(strcmp(in_line, "stop") == 0 )
                              exit(EXIT_SUCCESS);
                      else
                              printf("line was %d characters long\n",
                                      (int)cp-in_line);
                      cp = in_line;
              }
              else
                      *cp++ = c;
      }
      exit(EXIT_SUCCESS);
}
```


----------



## Sykora (Jul 13, 2008)

*Re: Post ur C/C++ Programs Here*

The code is getting a string from the user and storing it in an array. The code you've highlighted, is simply checking if it has reached the end of the array, and if so inserts the EOL marker. The LINELNG - 1 part is to make sure that there is one space available for the EOL marker itself.


----------



## ilugd (Jul 13, 2008)

*Re: Post ur C/C++ Programs Here*

Sykora, since LINELNG is 100 so LINELNG-1 is 99. in_line[99] *is* the last position in the error. There is no more space left in the array in_line. Isn't this correct?


----------



## aniket.awati (Jul 14, 2008)

*Re: Post ur C/C++ Programs Here*



ilugd said:


> Sykora, since LINELNG is 100 so LINELNG-1 is 99. in_line[99] *is* the last position in the error. There is no more space left in the array in_line. Isn't this correct?


In that case, it should be -2 rather than -1.

But, i think this statement is to check if pointer has reached the final position of the array, in such case, the program will write eol at that position. i.e. 
	
	



```
*cp=0;
```


----------



## Sykora (Jul 14, 2008)

*Re: Post ur C/C++ Programs Here*

@ilugd: That's exactly what I said.

It checks if it is currently at the last position, and if so inserts an EOL at that position.

@aniket.awati: -1 *is* the last position. The EOL goes there. not at -2.


----------



## aniket.awati (Jul 14, 2008)

*Re: Post ur C/C++ Programs Here*

I was editing the reply, when you replied. Yeah it certainly should be -1 not -2, missed that while editing.


----------



## c2tarun (Jul 22, 2008)

*Needed help with this program*

// This is a Program to convert Date from American format to Normat format
// From "July 15, 1986" to "15 July 1986"

import java.util.*;

class datetrans
{
public static void main(String args[])
    {
    System.out.println("Enter the date in \"July 15, 1986\" format:");
    Scanner stdin=new Scanner(System.in);
    String date=stdin.nextLine();
    String space=" ";
    int buf1=date.indexOf(space,0);
    String month=date.substring(0,buf1);
    String comma=",";
    int buf2=date.indexOf(comma,buf1+1);
    String day=date.substring(buf1,buf2-buf1);
    String year=date.substring(buf2+1,date.length()-buf2);

    System.out.println(day+"-"+month+"-"+year);
    }
}


/* This java program is not working as expected. Its giving and Index out of bounds error in line number 18, though it is not exactly occurring. Can anyone please tell me why this is happening */


----------



## Hitboxx (Jul 22, 2008)

*Re: Post ur C/C++ Programs Here*

Is that C or C++? Post in the proper format or delete it!


----------



## mehulved (Jul 22, 2008)

*Re: Post ur C/C++ Programs Here*



Hitboxx said:


> Is that C or C++? Post in the proper format or delete it!





c2tarun said:


> This java program is not working as expected.


There you go.


----------



## mehulved (Jul 23, 2008)

*Re: Post ur C/C++ Programs Here*



c2tarun said:


> if u are able to understand it then post a reply or dont make non sense comments about deleting.......


Before speaking about non-sense, look at the thread title and user status.


----------



## c2tarun (Jul 23, 2008)

*regret*

i am sorry for my last quote..[it was posted by my friend who used my account] can u help me with that program


----------



## QwertyManiac (Jul 23, 2008)

*Re: Post ur C/C++ Programs Here*

Does your cat type too or do you still not get the difference between C/C++ and Java?


----------



## aniket.awati (Jul 23, 2008)

*Re: Post ur C/C++ Programs Here*

IMHO this sticky should be open for all langs.

As for the code, problem is in the buffers used.
I think this would solve the problem.

```
import java.util.*;
import javax.swing.*;
class datetrans
{
public static void main(String args[])
{
String date=JOptionPane.showInputDialog("Enter the date in \"July 15, 1986\" format:");
String space=" ";
int buf1=date.indexOf(space,0);
String month=date.substring(0,buf1);
String comma=",";
int buf2=date.indexOf(comma,buf1+1);
String day=date.substring(buf1,buf2-1);
String year=date.substring(buf2+1);

JOptionPane.showMessageDialog(null,""+day+"-"+month+"-"+year);
}
}
```


----------



## QwertyManiac (Jul 24, 2008)

*Re: Post ur C/C++ Programs Here*

Simpler:

```
import java.lang.*;
import java.text.*;
import java.util.*;

class date
{
	public static void main(String args[]) throws ParseException
	{
		String textDate = "July 4, 1898";
		SimpleDateFormat input = new SimpleDateFormat("MMMMMMMMM d, yyyy");
		SimpleDateFormat output = new SimpleDateFormat("d MMMMMMMMM yyyy");
		Date df = input.parse(textDate);
		String date ="Date: "+output.format(df);
		System.out.println( date );
	}
}
```


----------



## aditya.shevade (Jul 24, 2008)

*Re: Post ur C/C++ Programs Here*

WTF Qwerty... since when do you know Java?


----------



## QwertyManiac (Jul 25, 2008)

*Re: Post ur C/C++ Programs Here*

Since 2004-2005


----------



## arshetty (Jul 28, 2008)

*Re: Post ur C/C++ Programs Here*

*what i nice program i see!!!1*
*it is realy helpful for student who learn c or c++*
*a small program is there i.e*
*how to swap the value of two variable without using 3rd variable*
*logic:int a,b;*
*a=10;*
*b=11;*
*a=a+b*
*b=a-b;*
*a=a-b;*

*

*


----------



## QwertyManiac (Jul 28, 2008)

*Re: Post ur C/C++ Programs Here*

Request for renaming thread to "Swapping two variables - The most impractically important thing every coder worth his NaCl must know."


----------



## nvidia (Jul 28, 2008)

*Re: Post ur C/C++ Programs Here*



QwertyManiac said:


> Request for renaming thread to "Swapping two variables - The most impractically important thing every coder worth his NaCl must know."


Rofl!


----------



## nvidia (Aug 1, 2008)

*Re: Post ur C/C++ Programs Here*

I was writing a program to solve problem #3 in Project Euler in C.
But it says that the constant "600851475143" is too long! Is there anyway to overcome this?


----------



## aditya.shevade (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*

errr... use python  there is some library for C called the GMP library.... Use that.


----------



## nvidia (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*

^I know there are alternative languages. But i wanted to know if there is any way to overcome this error in C.


----------



## mehulved (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*



QwertyManiac said:


> Request for renaming thread to "Swapping two variables - The most impractically important thing every coder worth his NaCl must know."


What is NaCl


----------



## harryneopotter (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*

NaCl == SALT 
Every coder worth his/her salt ........


----------



## ThinkFree (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*



mehulved said:


> What is NaCl



NaCl - Sodium Chloride or Common Salt


----------



## QwertyManiac (Aug 2, 2008)

*Re: Post ur C/C++ Programs Here*



nvidia said:


> ^I know there are alternative languages. But i wanted to know if there is any way to overcome this error in C.


aditya.shevade mentioned the GMP library, you could use that of course. GMP is short for GNU MultiPrecision library. Look for guides and other help with it here: *gmplib.org/. Works with C/C++. 

There is only so-much you can do with vanilla C, unless of course you decide to write your own big-number stuff, that GMP provides you with. 

@mehulved - Common salt today, maybe a language tomorrow. Ah I must have "lost count".


----------



## Sykora (Aug 3, 2008)

*Re: Post ur C/C++ Programs Here*

nvidia: Use the unsigned long long data type. Should be enough for your purposes. If you have 64 bit libs, and can program on it, all the better.

gmp would be the best way to go, but I hate using it without the oo goodness I get in the c++ wrappers.


----------



## nvidia (Aug 3, 2008)

*Re: Post ur C/C++ Programs Here*

^^If i use "unsigned long long" then whats the character that i should use in the input and the output stings? Like 

```
scanf("%(what?)",&variable);
```
Or suggest me a C compiler which can support large values.


----------



## QwertyManiac (Aug 3, 2008)

*Re: Post ur C/C++ Programs Here*

%lld or %llu should work fine.

Supporting large values is not what a compiler can provide, heh. We've said the same over and over again, GNU MP BigNum is your answer. If you don't want to listen why ask again?


----------



## Sykora (Aug 3, 2008)

*Re: Post ur C/C++ Programs Here*

nvidia:

The size of vaiues you can work with depends on your c libs, not your compiler. Use long long, but if that's not enough, there really is no avoiding gmp (if you want to stick with c, that is).


----------



## aditya.shevade (Aug 3, 2008)

*Re: Post ur C/C++ Programs Here*

That is not entirely true Sykora and QwertyM right? I mean, if he is using 16 bit compiler (the borland one that comes with turboC (the one that sucks)) then the values will be small....


----------



## Gigacore (Aug 12, 2008)

*Re: Post ur C/C++ Programs Here*

Updated the first post with all new programs.


----------



## santhoshkr (Sep 19, 2008)

*Need help in C++ programming*

Dear All,

I am working on DTV application developement project, the requirement  says that, 1. For Photo application , I need to extract the metadata(exif format used in digital cameras) using C++ code.
2. For Music and Video application, I need to extract the metadata(ID3 format) in MP3 files using C++ code.

Could you please suggest me the code or library which will help in getiing my work done.

Thanking You

With You Always
HappyKumar


----------



## shady_inc (Sep 26, 2008)

*Re: Post ur C/C++ Programs Here*

Started to learn user defined data types and operator overloading in C++.You can almost create your own new language using these.Now I understand C++'s superiority over other languages. !


----------



## sameissa (Sep 30, 2008)

*Re: Post ur C/C++ Programs Here*

Hello
I made the following program with C language - but I do not know how to fix the error when the user enters characters instead of numbers;
For Example:
the values entered by the user must be numbers only not characters - and if he type character the program should give him error message says that " please enter numbers only"
how to do this.
appreciate any help ?

 

#include <stdio.h>
#include <conio.h>

float fs;
float t;
float f;
float q;
float c;
int x,i,a;

int S,M,H;

int main()

{
char Ans;

for (i=1;i<=5;i=i+a)
 {
 i--;

  printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  printf("                    >>  Welcome To Audio System  >>                    \n");
  printf("                                                                   \n");
  printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  printf("                       Please Enter:                               \n");
  printf("                                                                   \n");
  printf("                       [1]  To calculate File Size                    \n");
  printf("                                                                   \n");
  printf("                       [2]  To calculate Time                         \n");
  printf("                                                                   \n");
  printf("                       [3]  To calculate Frequnecy                    \n");
  printf("                                                                   \n");
  printf("                       [4]  To calculate Quantization                 \n");
  printf("                                                                   \n");
  printf("                       [5]  To calculate Channels                     \n");
  printf("                                                                   \n");
  printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  scanf("%d",&x);

  if (x==1)
       {
  printf(" Please Enter  Time \n Seconds\n ");
  scanf("%d",&S);
  printf("                                                                   \n");
  printf("  Minutes\n  ");
  scanf("%d",&M);
  printf("                                                                   \n");
  printf("  Hours\n ");
  scanf("%d",&H);
  printf("                                                                   \n");
  t=S+(M*60)+(H*60*60);
  printf(" Please Enter  Frequnecy \n  ");
  scanf("%f",&f);
  printf("                                                                   \n");
  printf(" Please Enter  Quantization \n ");
  scanf("%f",&q);
  printf("                                                                   \n");
  printf(" Please Enter  Channels \n ");
  scanf("%f",&c);
  printf("                                                                   \n");
  fs=t*(f*1000)*q*c;
  fs=fs/8/1024/1024;
  printf("                                                                   \n");
  printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  printf(" The file size is %f MB \n",fs);
  printf("                                                                   \n");
  printf(" -------------------------------------------------------------------------- \n");
  }
  else if (x==2)
       {   printf(" Please Enter \n File Size \n  ");
  scanf("%f",&fs);
  printf(" Please Enter  Frequnecy \n  ");
  scanf("%f",&f);
  printf(" Please Enter  Quantization \n ");
  scanf("%f",&q);
  printf(" Please Enter  Channels \n ");
  scanf("%f",&c);
  t= fs/(f*q*c);
  printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  printf(" The time is %f s \n",t);
  printf("                                                                   \n");
   printf(" -------------------------------------------------------------------------- \n");
       }
  else if (x==3)
  {   printf(" Please Enter  File Size \n ");
  scanf("%f",&fs);
  printf(" Please Enter  Time \n Seconds\n ");
  scanf("%d",&S);
  printf("  Minutes\n  ");
  scanf("%d",&M);
  printf("  Hours\n ");
  scanf("%d",&H);
  t=S+(M*60)+(H*60*60);
  printf(" Please Enter  Quantization \n ");
  scanf("%f",&q);
  printf(" Please Enter  Channels \n ");
  scanf("%f",&c);
  f= (fs/(t*q*c))/1000;
  printf(" -------------------------------------------------------------------------- \n");
   printf("                                                                   \n");
  printf(" The Frequnecy is %f KHz \n",f);
  printf("                                                                   \n");
   printf(" -------------------------------------------------------------------------- \n");
       }
  else if (x==4)
      { printf(" Please Enter \n File Size \n  ");
  scanf("%f",&fs);
  printf(" Please Enter  Time \n Seconds\n ");
  scanf("%d",&S);
  printf("  Minutes\n  ");
  scanf("%d",&M);
  printf("  Hours\n ");
  scanf("%d",&H);
  t=S+(M*60)+(H*60*60);
  printf(" Please Enter  Frequnecy \n  ");
  scanf("%f",&f);
  printf(" Please Enter  Channels \n ");
  scanf("%f",&c);
  q= fs/(t*f*c);
  printf(" -------------------------------------------------------------------------- \n");
   printf("                                                                   \n");
  printf(" The Quantization is %f \n",q);
  printf("                                                                   \n");
   printf(" -------------------------------------------------------------------------- \n");
       }

  else if (x==5)
        {
  printf(" Please Enter \n File Size \n  ");
  scanf("%f",&fs);
  printf(" Please Enter  Time \n Seconds\n ");
  scanf("%d",&S);
  printf("  Minutes\n  ");
  scanf("%d",&M);
  printf("  Hours\n ");
  scanf("%d",&H);
  t=S+(M*60)+(H*60*60);
  printf(" Please Enter  Frequnecy \n  ");
  scanf("%f",&f);
  printf(" Please Enter  Quantization \n ");
  scanf("%f",&q);
  c= fs/(t*f*q);
   printf(" -------------------------------------------------------------------------- \n");
   printf("                                                                   \n");
  printf(" The Channels is %f \n",c);
   printf("                                                                   \n");
   printf(" -------------------------------------------------------------------------- \n");
       }
  else
   {

   printf(" -------------------------------------------------------------------------- \n");
   printf("                                                                   \n");
  printf("\t\t\t\t \n Sorry you have typed wrong input\n \n ");
  printf("\t\t\t\t \n Please Enter Correct Number from [1]  TO  [5] \n\n ");
  printf("                                                                   \n");
   printf(" -------------------------------------------------------------------------- \n");

      }

    do
    {
    printf ("\t\t Please TYPE 'y' To Exit To The Main Menu ");
    scanf ("%c", &Ans);

        if(Ans == 'n' || Ans =='N')
            printf("\t\t \n Could you Please Leave Me Now...\n\n", Ans);
                   else if(Ans == 'y' || Ans == 'Y')
            break;
        else
            printf ( "              \n\n");
    }
    while(Ans != 'y' || Ans != 'Y');

 printf("                                                                   \n");

         printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
         printf ( "\t\t  >> ...Thank YOU For Using OUR Audio System...  >>  \n\n");
 printf("                                                                   \n");
          printf(" -------------------------------------------------------------------------- \n");
  printf("                                                                   \n");
  printf ( "\t\t To Exit To The Main Menu Press Any Key to Exit...");
  printf("                                                                   \n");
  printf(" -------------------------------------------------------------------------- \n");
  getch();
}
}


thanks

enashre@yahoo.com


----------



## QwertyManiac (Sep 30, 2008)

*Re: Post ur C/C++ Programs Here*


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

#define PI 3.1416

float radius(float d) { return d/2; }
float surface(float d) { return 4*PI*pow(d/2,2); }
float circum(float d) { return PI*d; }
float volume(float d) { return (4*PI*pow(d/2,3))/3; }

int main(int argc, char **argv)
{
    float dia;

    printf("Enter the diameter: ");
    scanf("%f",&dia);
    dia<0.0?exit(1):printf("\nDiameter: %f", dia);

    printf("\nRadius is: %f", radius(dia));
    printf("\nSurface Area is: %f", surface(dia));
    printf("\nCircumference is: %f", circum(dia));
    printf("\nVolume is: %f\n", volume(dia));

    return 0;
}
```

Resulting I/O:

```
Enter the diameter: 4

Radius is: 2.000000
Surface Area is: 50.265598
Circumference is: 12.566400
Volume is: 33.510399
```

There, homework done. :\


----------



## aditya.shevade (Oct 2, 2008)

*Re: Post ur C/C++ Programs Here*

LOOLOL Qwerty... I thought we were against this whole _thing_


----------



## sameissa (Oct 6, 2008)

*Re: Post ur C/C++ Programs Here*

thank you very much

*thank you very much*


----------



## mavihs (Oct 8, 2008)

*Re: Post ur C/C++ Programs Here*


```
/*WAP to copy content of one file to another
i) As it is.
ii) After converting all characters to upper case

Name: Shivam*/

#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<stdlib.h>

void main()
{
    clrscr();
    char path1[100], path2[100], ch, ch2;
    int cho;
    cout<<"\n\tEnter the path of the file which has to be copied: ";
    gets (path1);
    ifstream org(path1);
    if(!org)
    {
        cout<<"\tFile not found!";
        exit(0);
    }
    cout<<"Enter the name or the path of the file where the file has to be copied to: ";
    gets(path2);
    ofstream wrt(path2);
    if(!wrt)
    {
        cout<<"\tCannot create file!";
        exit(0);
    }

    cout<<"\t 1. Enter 1 to copy file as it is. \n\t 2. Enter 2 to copy file after converting all lower case characters to upper case characters. \n\n\t Enter your choice: ";
    cin>>cho;
    if(cho==1)
    {
        do{
            org.get(ch);
            wrt.put(ch);
        }while(!org.eof());
    }
    else
    {
        if(cho==2)
        {
            do{
                org.get(ch);
                if(ch > 96 && ch <123)
                {
                    ch2 = ch - 32;
                    wrt.put(ch2);
                }
                else
                wrt.put(ch);
                
            }while(!org.eof());
        }
        else
        cout<<"Wrong choice entered!";
    }
}
```


----------



## gopi_vbboy (Oct 9, 2008)

*Re: Post ur C/C++ Programs Here*

Embedded programming is very interesting...Let me introduce to this type of programmign woth ANSI C

Here how a general super loop is written for any microcontroller--Superloop is just a while loop similar to a MessageProc in WIn32 API where u can wait for an interrupt or some message to arrive.......


```
*/
THe following is a sample prog for keil

This is how u can turn on a LED connect to a port of Microcontroller
say P0.0

#include <reg52.h> //i use keil...reg52 is the lib for atmel 89c52 series

void main()
{

while(1)
{
//super loop

P0.0=0;//MAKING LOW DRIVES CURRENT INTO LED
}
}
///Thsts it a simple LED turn onm prog...............actually a simple controller can also be use ///////but i jus took this for an example for beginner
```

Now jus program the.hex produced by compliler using some flash programming software.............done a embedded project


----------



## aditya.shevade (Oct 9, 2008)

*Re: Post ur C/C++ Programs Here*

^^ LOL... Anyways, nice to see people going to embedded C... Make a thread for this, embedded C for microcontrollers.. name each post by the microcontroller for which the program is.

Try AVR controllers, they are nice.


----------



## umeshtangnu (Oct 14, 2008)

*Re: Post ur C/C++ Programs Here*


```
unsigned char *memcpy(unsigned char *dest, const unsigned char *src, int count)
{
	int i =0;

	for(;i<count;i++)
		*(dest+i)=*(src+i);

	return  dest;
}

unsigned char *memset(unsigned char *dest, unsigned char val, int count)
{

	int i =0;
	while(i<count)
	{
		*(dest+i)=val;
		i++;
	}
	return  dest;
}

unsigned short *memsetw(unsigned short *dest, unsigned short val, int count)
{

	int i =0;
	while(i<count)
	{
		*(dest+i)=val;
		i++;
	}
	return  dest;
}
```

some common C functions 
currently writing print(char * c) and printch(char c)


----------



## Plasma_Snake (Nov 2, 2008)

*Re: Post ur C/C++ Programs Here*

Brethren can you please look at my this program, its my first try at Windows programming, copied from "Sams Teach Yourself Game Programming in 24 Hours" but still erroneous.  Below is the download link to the rar archive containing the actual VS2005 Project. Please see it.

```
*www.uploading.com/files/JSXD03HX/Skeleton.rar.html
```


----------



## Plasma_Snake (Nov 5, 2008)

*Re: Post ur C/C++ Programs Here*

Well since no one has actually taken the pain to see my project's code, can anybody at least tell me that while generating following error, where is the compiler actually looking for .ico files?

```
1>Skeleton.cpp
1>Compiling resources...
1>.\Skeleton.rc(4) : error RC2135 : file not found: Skeleton.ico
1>.\Skeleton.rc(5) : error RC2135 : file not found: Skeleton_sm.ico
1>Build log was saved at "file://c:\Users\Rudra Pratap\Documents\Visual Studio 2005\Projects\Skeleton\Skeleton\Debug\BuildLog.htm"
1>Skeleton - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
```


----------



## QwertyManiac (Nov 5, 2008)

*Re: Post ur C/C++ Programs Here*

I can't download your source from that silly site. Its much like Megaupload, "The slots of your country is over-limit. (Actually, we dropped our scalable balls)". Haven't you heard of Dropbox, or Mediafire, or any other sane upload service?

But anyway, look into your Skeleton.rc file for the location its looking up or pastebin that file here if you don't understand.


----------



## srinivasa.s (Nov 6, 2008)

*Re: Post ur C/C++ Programs Here*

This is something I never knew and read about it recently in "Exceptional C++". Let me start with a code example...

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

Try this out and to your surprise you'll find that this gives a "call to foo is ambiguous" error. But why?? The only foo visible at the place of call is in namespace B. Why should this result in an error? Okay, now try this out - comment out the "foo" definition in namespace B.

namespace A {
  class S { };
  void foo(S& parm) { }
}

namespace B {
  // void foo(A::S& parm) { }
  void bar(A::S& parm) {
    foo(parm); // Which "foo" does this call?
  }
}

This compiles without errors! Surprised again? When you run the program, it'd have called A::foo. What happened here? Does this not appear to be a namespace violation. Apparently not! This strange behavior is explained by "Koenig lookup".

If you supply a function argument of class type (here parm, of type A::S), then to find the function name the compiler considers matching names in the namespace (here A) containing the argument's type.

But still, is'nt this a namespace violation?? NO. Just consider this piece of code...

std::string str("Hello"); 
std::cout << str ; 

This works fine right? How? This works because of Koenig lookup. The function in question here is "operator <<" which is found in "namespace std". But we have'nt used any "using" declaration to bring that function into the current scope. Since std::string is going as an argument into that function, the compiler will automatically look into the std namespace and will find that function. Without this kind of lookup, the same function call would have to be written as...

std:perator <<( std::cout, str) ; // ugly! ain't it?? 

This is the great value that Koenig lookup gets us and we tend to use it every now and then without realising it.


----------



## jax_diu (Nov 6, 2008)

*Re: Post ur C/C++ Programs Here*

can any one give me a simple programe of palindrome.....
pls people give it urgently......


----------



## srinivasa.s (Nov 7, 2008)

*Re: Post ur C/C++ Programs Here*

I once needed to write a program that would modify a file based on certain parameters like: percentage of change, scatter changes over different extents, maximum length of a change extent, randomize changes, etc. To be efficient, the program needed to generate a random list of change extents, sort it and then iterate over the sorted list to seek to particular offset and change the file for the length of that extent. 

An extent was a structure having a pair - {offset, length}. The sort needed to sort the list of extents based on the offsets. Instead of generating a list first and then sorting it, I chose to do a sorted insert into a linked list. One thing that needed to be taken care was to ensure no overlaps in the extents in the list. 

Following is the function that implements the sorted insert with no overlaps: 


```
struct node {
  unsigned pos;  // offset
  unsigned extent;  // extent length
  struct node *next; 
}; 

//
// return false if there's no insert due to overlap
// 
bool sorted_insert_no_overlap( node **head, node *new_node )
{
  node dummy;
  node *cur = &dummy;
  dummy.next = *head;
  while( cur->next && cur->next->pos < new_node->pos )
  {
    cur = cur->next;
  }
  if( ((cur->pos + cur->extent) > new_node->pos) || 
    ( cur->next
      && ( (cur->next->pos == new_node->pos)
            || ((new_node->pos + new_node->extent) > cur->next->pos) )
    ))
  {
    return false;
  }
  new_node->next = cur->next;
  cur->next = new_node;
  *head = dummy.next;
  return true;
}
```


----------



## nvidia (Nov 11, 2008)

*Re: Post ur C/C++ Programs Here*



jax_diu said:


> can any one give me a simple programe of palindrome.....
> pls people give it urgently......


Here -

```
void main()
{
int number,rev,digit,temp;
printf("Enter the number");
scanf("%d",&number);
temp = number;
rev = 0;
while(temp!=0)
{ 
   digit = temp % 10;
   rev = rev*10 + digit;
   temp = temp /10;

}
if(number==rev)
printf("Number is a palindrome");
}
```


----------



## Gigacore (Nov 11, 2008)

*Re: Post ur C/C++ Programs Here*



jax_diu said:


> can any one give me a simple programe of palindrome.....
> pls people give it urgently......



here's an another simple method which also says the word is not a palindrome in case if it isn't:


```
#include <stdio.h>
void main()
{
     int i, length, flag=0;
     char string[25];
     printf("\nEnter the string: ");
     gets(string);
     length = strlen(string);
     for(i=0;i<length/2;i++)
     {
        if(string[i]!=string[--length])
        {
            flag =1;
        break;
        }
     }
  if (flag==1)
  printf("\nThe word is not a palindrome");
  else
  printf("\nThe word is a palindrome");
  getch();
}
```

@ nvidia, u missed the header btw...


----------



## nvidia (Nov 11, 2008)

*Re: Post ur C/C++ Programs Here*

Oops.. Thanks for correcting


----------



## Plasma_Snake (Nov 12, 2008)

*Re: Post ur C/C++ Programs Here*

OK brothers, here is the MediaFire link to my project's rar file. This time I even made 2 icon resources but now getting an eof error in aresource1.h file which is automatically created when I build the project.

```
*www.mediafire.com/?1cyi22xq0jh
```
Please see to it and tell me what I'm doing wrong


----------



## 4T7 (Nov 13, 2008)

*Re: Post ur C/C++ Programs Here*

Here's mine 

```
//Man with umbrella
//man_ubr.c
#include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
#include<dos.h>
#include<conio.h>
void main()
{
  int driver=DETECT,mode,i;
  int x1,x2,x3,x4,x5;
  int y1,y2,y3,y4,y5;
  initgraph(&driver,&mode,"C:\\tc\\bgi");
  cleardevice();
  setcolor(9994);
  x1=100;y1=330;
  x2=150;y2=330;
  x3=125;y3=280;
  x4=0;y4=332;
  x5=600;y5=332;
  for(i=0;i<300;i+=10)
  for(x1=100,x2=150;x1<150,x2>100;x1+=2,x2-=2)
  {
	 delay(15);
	 cleardevice();
	 line(x3+i,240,150+i,240);
	 line(x3+i,240,x1+i,270);
	 line(150+i,240,150+i,180);
	 ellipse(150+i,185,0,200,35,5);
	 line(x1+i,y1,x3+i,y3);
	 line(x2+i,y2,x3+i,y3);
	 ellipse(125+i,260,0,360,5,25);
	 circle(125+i,225,7);
	 line(x4,y4,x5,y5);
  }
  return;
}
```


----------



## Plasma_Snake (Nov 13, 2008)

*Re: Post ur C/C++ Programs Here*

Somebody see to my problem please.


----------



## aditya.shevade (Nov 16, 2008)

*Re: Post ur C/C++ Programs Here*

Okay, I have not seen your code, but I think (underline think) that the problem is due to a newline at the end of the file aresource1.h. Error is because there is no newline at the end of the file. Put a newline at the end (blank) of the file and save it. (Again, I think that is the problem, I have not seen the code)


----------



## teejay_geekEd (Nov 30, 2008)

*Re: Post ur C/C++ Programs Here*

can you help me wid a simple program-- to convert all vowels in a file from upper to lower case and vice-versa using simple file handling concept.?
thanks


----------



## crazyvalentine (Dec 1, 2008)

*a simple program to convert decimal into binary*

#include<iostream.h>
#include<conio.h>
void main()
{
 int n,p=1,s=0;
clrscr();
cout<<"enter any number";
cin>>n;
while(n>0)
{
 k=n%2;
 s=s+k*p;
 n=n/2;
 p=p*10;
}
cout<<s;
getch();
}


----------



## QwertyManiac (Dec 1, 2008)

*Re: Post ur C/C++ Programs Here*



teejay_geekEd said:


> can you help me wid a simple program-- to convert all vowels in a file from upper to lower case and vice-versa using simple file handling concept.?
> thanks




```
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

char lower[] = {'a','e','i','o','u'};
char upper[] = {'A','E','I','O','U'};

char vowel(char a) {
    for(int i=0;i<5;i++) {
        if (a==lower[i]) { return a-32; }
        if (a==upper[i]) { return a+32; }
    }
    return a;
}

int main(int argc, char **argv) {
    ifstream input(argv[1], ifstream::in);
    string ip, op;
    while (input.good()) { getline(input, ip); op.append(ip+"\n"); ip.erase(); }
    transform(op.begin(), op.end(), op.begin(), vowel);
    cout << op;
    return 0;
}
```

Swaps lower vowel to upper and upper to lower and prints to stdout.


----------



## albert VII (Dec 18, 2008)

*Re: Post ur C/C++ Programs Here*

give me basic c programing lessons...


----------



## red_devil (Dec 18, 2008)

*Re: Post ur C/C++ Programs Here*

^ LOL


----------



## QwertyManiac (Dec 19, 2008)

*Re: Post ur C/C++ Programs Here*



albert VII said:


> give me basic c programing lessons...


Here's a quick one.


----------



## aditya.shevade (Dec 22, 2008)

*Re: Post ur C/C++ Programs Here*

You will never learn, will you....


----------



## QwertyManiac (Dec 22, 2008)

*Re: Post ur C/C++ Programs Here*

I don't mind learning stuff myself while helping others (or not). Call me selfish, I don't care.


----------



## ambika (Dec 24, 2008)

*Re: Post ur C/C++ Programs Here*

Someone assign me the algorithm or code for the same .

1. Wite aii interactive C program that outputs a telephone bill, if the number of telephone calls
are given by the user. A telephone call is described by the starting and stopping timqs, where
. the timings are given in the form of hh:mm,/dd/mm/VyW 20 .
hh + the hour 'dd -+ the day
mm -) the minutes mm -+ the month
yyyy -) the year ,
,:The'fo[owtng table describes the cost of a phone call per minute.
Time Cost per minute (in rupees)
00:00 to 7:59
08:00 to 18:59
19;00 to 23:59
0.50
1.00
0.40






1. Write an interactive C program to generate a pay-slip for 7 employees in a small organisation
whose Basic, TA, DA, Allowances, Perks, Deductions (like GPF, loans, LIC) are given by the
user. The pay-slip should contain the name, scale of pay, month and year, designation,
department, gross-pay, net-pay and attendance.


----------



## Yamaraj (Dec 24, 2008)

*Re: Post ur C/C++ Programs Here*



QwertyManiac said:


> ```
> if (a==lower[i]) { return a-32; }
> if (a==upper[i]) { return a+32; }
> ```


Instead of using magic numbers in a program, you should make use of library functions to convert the character to upper or lower case.


----------



## ambika (Dec 24, 2008)

*Re: Post ur C/C++ Programs Here*

MERRY CHRISTMAS TO ALL.....



```
/*program written by AMBIKA for giving you best wishes for christmas and new year*/

#include<stdio.h>

void main()

{

char name;

int choice;

do
{

printf("\nPlease enter your first name here:");

scanf("%s",&name);

printf("\n Hello!! %s!!,How are you ?",&name);

printf("\n Please enter your choice and get my best wishes for you.Thanks!!\n");

printf("\n ***************** 1.Wishes for a good day************************\n");

printf("\n ***************** 2.Wishes for a christmas************************\n");

printf("\n ***************** 3.Wishes for the new year**********************\n");

printf("\n ***************** 4.Exit ****************************************\n");

scanf("%d",&choice);

switch(choice)

{

case 1:printf("\n Have a good day %s!!",&name);
break;

case 2:printf("\n Merry christmas %s!!",&name);
break;

case 3:printf("\n HAPPY NEW YEAR 2009 ,Wishing u a prosperus new year %s.",&name);
break;

case 4:printf("\n THANK YOU ,BYE!!");
break;

default:printf("\nInvalid Entry.Please enter right choice.\n");
break;
}

}while(choice!=4); return 0;

}

/*program ends here.*/
```


----------



## QwertyManiac (Dec 24, 2008)

*Re: Post ur C/C++ Programs Here*



Yamaraj said:


> Instead of using magic numbers in a program, you should make use of library functions to convert the character to upper or lower case.


Ah, yes! 

Diff patch fix (newvowelswap.cpp):

```
--- oldvowelswap.cpp    2008-12-24 18:45:13.000000000 +0530
+++ newvowelswap.cpp    2008-12-24 18:44:55.000000000 +0530
@@ -1,6 +1,7 @@
 #include <iostream>
 #include <fstream>
 #include <algorithm>
+#include <string>
 
 using namespace std;
 
@@ -9,8 +10,8 @@
 
 char vowel(char a) {
     for(int i=0;i<5;i++) {
-        if (a==lower[i]) { return a-32; }
-        if (a==upper[i]) { return a+32; }
+        if (a==lower[i]) { return toupper(a); }
+        if (a==upper[i]) { return tolower(a); }
     }
     return a;
 }
```


----------



## mavihs (Dec 26, 2008)

*Re: Post ur C/C++ Programs Here*

guys can u tell me y do we use 


> using namespace std;


?????


----------



## QwertyManiac (Dec 26, 2008)

*Re: Post ur C/C++ Programs Here*

That's cause the standard library functions all belong to the *std* namespace. So instead of using those functions cin, fstream, etc ... as std::cin, std::fstream, etc ..., we just add the *using namespace std;* line and its automatically done.


----------



## nvidia (Dec 26, 2008)

*Re: Post ur C/C++ Programs Here*

Guys whats the Python equivalent of the C infinite for loop? 

```
for(i = 0;  ; i++)
```

I wanted a range of about 10^25 and i cant use it in python

```
for x in range(1,pow(10,25)):
    somecode
```
When i run this code it says 

```
Traceback (most recent call last):
  File "C:/Python26/Euler_66", line 10, in <module>
    for y in range(1,k):
OverflowError: range() result has too many items
```


----------



## Sykora (Dec 27, 2008)

*Re: Post ur C/C++ Programs Here*

@nvidia:

The simplest infinite loop is 


```
while True :
   do_something()
```

but if you really wanted a for loop instead of a while loop, 


```
from itertools import count
for i in count(0) :
    do_something()
```


----------



## nvidia (Dec 27, 2008)

*Re: Post ur C/C++ Programs Here*

I tried using while(True) in my program but it gets stuck somewhere infinitely.. Don't the break statements work for a while loop in Python?


----------



## QwertyManiac (Dec 27, 2008)

*Re: Post ur C/C++ Programs Here*

@nvidia - Logic issue, not Python. Debug it 

*break* always breaks the loop its nested in.


----------



## nvidia (Dec 27, 2008)

*Re: Post ur C/C++ Programs Here*

My Bad..
My break statement was indented wrongly. 
Thanks skykora and QM
Btw, any of you doing Project Euler?


----------



## QwertyManiac (Jan 2, 2009)

*Re: Post ur C/C++ Programs Here*

A very simple Decimal -> Binary converter. (Correct upto sizeof(int)*8-1 bits)


```
[COLOR=#bc7a00]#include <stdio.h>
#include <stdlib.h>
[/COLOR]
[COLOR=#b00040]void[/COLOR] [COLOR=#0000ff]binary[/COLOR]([COLOR=#b00040]int[/COLOR] num) {
    [COLOR=#b00040]int[/COLOR] i[COLOR=#666666]=[/COLOR][COLOR=#666666]0[/COLOR];
    printf([COLOR=#ba2121]"Binary: "[/COLOR]);
    [COLOR=#008000][B]for[/B][/COLOR](i[COLOR=#666666]=[/COLOR][COLOR=#008000][B]sizeof[/B][/COLOR](num)[COLOR=#666666]*[/COLOR][COLOR=#666666]8[/COLOR][COLOR=#666666]-[/COLOR][COLOR=#666666]1[/COLOR]; i[COLOR=#666666]>-[/COLOR][COLOR=#666666]1[/COLOR]; i[COLOR=#666666]--[/COLOR]) {
        printf([COLOR=#ba2121]"%d"[/COLOR], num[COLOR=#666666]&[/COLOR]([COLOR=#666666]1[/COLOR][COLOR=#666666]<<[/COLOR]i)[COLOR=#666666]?[/COLOR][COLOR=#666666]1[/COLOR][COLOR=#666666]:[/COLOR][COLOR=#666666]0[/COLOR]);
    }
    printf([COLOR=#ba2121]"[/COLOR][COLOR=#bb6622][B]\n[/B][/COLOR][COLOR=#ba2121]"[/COLOR]);
}
[COLOR=#b00040]int[/COLOR] [COLOR=#0000ff]main[/COLOR]([COLOR=#b00040]int[/COLOR] argc, [COLOR=#b00040]char[/COLOR] [COLOR=#666666]**[/COLOR]argv) {
    [COLOR=#008000][B]if[/B][/COLOR] (argc[COLOR=#666666]>[/COLOR][COLOR=#666666]1[/COLOR])
        binary(atoi(argv[[COLOR=#666666]1[/COLOR]]));
    [COLOR=#008000][B]else[/B][/COLOR] {
        [COLOR=#b00040]int[/COLOR] a;
        printf([COLOR=#ba2121]"Enter a number: "[/COLOR]);
        scanf([COLOR=#ba2121]"%d"[/COLOR], [COLOR=#666666]&[/COLOR]a);
        binary(a);
    }
    [COLOR=#008000][B]return[/B][/COLOR] [COLOR=#666666]0[/COLOR];
}
```


----------



## harryneopotter (Jan 2, 2009)

*Re: Post ur C/C++ Programs Here*

here is a link to a simple prog i made in my school days ..have a look.

Its an EXE file, but not a virus or anything like that. 

here is the Link


----------



## nvidia (Jan 2, 2009)

*Re: Post ur C/C++ Programs Here*

^^Makes weird noises when i choose anything..


----------



## ambika (Jan 2, 2009)

*Re: Post ur C/C++ Programs Here*

I am very comfortable with TURBO C or C++........now just i m shifted to dev C++(beta version),geany etc .......in my new linux system .....i have been facing problem with these compilers ......can u guys simplly tell me whts the main difference between these two ........how to set these compilers in linux??


----------



## sam_1710 (Jan 2, 2009)

*Re: Post ur C/C++ Programs Here*



nvidia said:


> ^^Makes weird noises when i choose anything..



Use DOSBOX to play them.. 
btw.. I used to make these when in C lab in college..


----------



## harryneopotter (Jan 3, 2009)

*Re: Post ur C/C++ Programs Here*



nvidia said:


> ^^Makes weird noises when i choose anything..



Run it in XP. I tried to make ringtones for the corresponding titles using C++ .... And its nt that bad yaar


----------



## nvidia (Jan 4, 2009)

*Re: Post ur C/C++ Programs Here*

Cool.. Sounds good on XP


----------



## sankha (Jan 9, 2009)

*Re: Post ur C/C++ Programs Here*

I have a full banking software written in C++. But it's hard to copy here as it's more than 10,000 lines of code. If anybody needs it please contact me.










_________________________________
Protect personal data


----------



## shirishsriv (Jan 16, 2009)

*Re: Post ur C/C++ Programs Here*



Ron said:


> scanf("%d%d%d",&a,&b,&c);
> New to c++.......Whta those this line means


these lines says that
your integer values will be saved in the block of variable a,b&c.

Can anybody tell me the program of snake game without use of pointers And with use of pointers??????


----------



## happy20b (Jan 29, 2009)

*Re: Post ur C/C++ Programs Here*

I Have written a code which will take number between 0 to 99,99,99,999 and will print in words..
this code i had written 4 years back.. 
eg:
input : 22812
output: twenty two thousand eight hundred and twelve

I had written TicTc game in TurboC C with mouse interface
And also solution for Sudoku game (Worst part is giving input  )


----------



## ╬Switch╬ (Feb 1, 2009)

*Re: Post ur C/C++ Programs Here*

Does anyone know what return0 does and also why is it necessary to have "void main" and getch()?


----------



## Sykora (Feb 1, 2009)

*Re: Post ur C/C++ Programs Here*

"void main" is _wrong_. "getch()" is _not_ necessary.

main() is literally the program's main function. The OS uses the return value of a program to determine whether it exited properly or not. Using void main will return a trash value, leaving the OS to guess on its own. Therefore, all your programs _must_ be declared as "int main". Decent compilers will error out on this issue.

Using "return 0" at the end of main() (or any functioni, for that matter) will return the value 0 to the calling function. In main, this value is returned to the OS, where a return value of 0 indicates execution success. This way the OS can properly tell what happened after the fact.

getch() is a Borland-specific hack to get the output to wait for the user's keypress before continuing. It is non-portable, non-standard, and too damn old. Use a better compiler.


----------



## QwertyManiac (Feb 1, 2009)

*Re: Post ur C/C++ Programs Here*

Aren't we getting tired of answering the very same questions every week of the month in this section? We need some sort of a Read-This-First thread with a FAQ.


----------



## Liverpool_fan (Feb 1, 2009)

*Re: Post ur C/C++ Programs Here*

^ I agree. There must be an FAQ which links to FAQ of many programming languages particularly C/C++ and also other languages answering this recurring questions.


----------



## thinkme (Mar 1, 2009)

*Re: Post ur C/C++ Programs Here*

Hey guys,,

come on i've got something to ask u all??


1. What will be the output of:
int main()
{ int a=5;
  printf("%d",printf("%f",a));
}

2. What are command line arguments? How to use them??
     I know a bit abt it. If someone knows it better plz share here...

3. How is VAriable Argument list used.. Plz explain with a good xample.


----------



## mehulved (Mar 1, 2009)

*Re: Post ur C/C++ Programs Here*



thinkme said:


> Hey guys,,
> 
> come on i've got something to ask u all??
> 
> ...


Try it?
Compiler throws me warnings and returns garbage values.



thinkme said:


> 2. What are command line arguments? How to use them??
> I know a bit abt it. If someone knows it better plz share here...


Unless you tell what you know about. Why should someone take the pain of explaining, when you don't do the same.



thinkme said:


> 3. How is VAriable Argument list used.. Plz explain with a good xample.


Loads on examples on this if you search for it.


----------



## Liverpool_fan (Mar 1, 2009)

*Re: Post ur C/C++ Programs Here*

*www.cplusplus.com/reference/clibrary/cstdio/printf.html


> *Return Value*
> On success, the total number of characters written is returned.
> On failure, a negative number is returned.



But it would throw only a garbage value in this case...


----------



## happy20b (Mar 2, 2009)

*Re: Post ur C/C++ Programs Here*



thinkme said:


> Hey guys,,
> 
> come on i've got something to ask u all??
> 
> ...


output wil be garbage but you would hav asked for reason instead of the output

the outputs which i got were 
-0.8992659
-0.0196369
-0.0340909
and you can see number 9 at the end of each output an that is the output of    printf("%d", and the rest out put  is of printf("%f",a) acttualy if you use \n in 2nd printf
like 
  printf("%d",printf("%f\n",a));
you should be able to see output somthing like

-0.039340 printf("%f\n",a)
10    printf("%d" 

since you are printing an integer value in float format internal conversion will make output something like -0.019636 (garbage) and then second printf will print the return value of first printf ie number of characters it printed ie in above case it is 9 characters hence output will be -0.0196369






> 2. What are command line arguments? How to use them??
> I know a bit abt it. If someone knows it better plz share here...


 
It is the way of passing arguments to main function .. 

main(int argc, char *argv[])

so you can pass arguments to this main function at command promt
promt$ ./program   hello     3          name
              argv[0]   argv[1]  argv[2]  argv[3]

so main will get 4 arguments as above .. and argc will be 4




> 3. How is VAriable Argument list used.. Plz explain with a good xample.



you mean to say variable argument in functions ???


----------



## thewisecrab (Mar 28, 2009)

*Re: Post ur C/C++ Programs Here*

This may sound stupid.
I want to set up an editor+compiler to type out C/C++ programs 
Most places I've been use Turbo C 
But after searching on the net, I found that it's old and only trial version is available.
I downloaded and installed Relo
Sadly since I dont have a complier (atleast that's what it seems like), I dont know what to do here on.
Any compilers I should download? If so which one? How?


----------



## Liverpool_fan (Mar 28, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
See my sig


----------



## thewisecrab (Mar 30, 2009)

*Re: Post ur C/C++ Programs Here*



Liverpool_fan said:


> ^ ^ ^
> See my sig


Awesome!
Thanks 
EDIT:
I downloaded MinGW
I left on whole night (NU plan)
Installer stated that download was successful
But when I selected "Install" it gave me "tarball unreadable" error


----------



## Liverpool_fan (Apr 2, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
Strange 
That didn't happen to me. Did you try to do the complete install? Because you don't need to. You just need Base Tools and g++ (for C++) and possibly gdb but that's not necessary too.
Maybe it was a server problem. I suggest to try again, it doesn't take as long as waiting for the night... 
If the problem crops up again, could you post a screenshot?

Also you can try installing the Candidate or previous version insted of the current version.

Alternatively you can try Codeblocks + MinGW integrated installer.
*www.codeblocks.org/downloads/5

(download the second installer of ~19MB which can integrated gcc and gdb)

However the downside of Codeblocks is that it's heavy and has WAY too many features that it borders on being confusing.

However the benefit would be that it wil automatically install MinGW and you can still use Geany as IDE.


----------



## Crazykiller (Apr 2, 2009)

*Re: Post ur C/C++ Programs Here*

You wanted a C++ Program?? Here it is.




> #include <iostream>
> using namespace std;
> void main()
> {
> cout << "Hello World!" << endl;   cout << "Welcome to C++ Programming" << endl; }



I Made it myself. Really...............................


----------



## Liverpool_fan (Apr 2, 2009)

*Re: Post ur C/C++ Programs Here*


*www.gidnetwork.com/b-66.html


----------



## thewisecrab (Apr 2, 2009)

*Re: Post ur C/C++ Programs Here*



Liverpool_fan said:


> ^ ^ ^
> Strange
> That didn't happen to me. Did you try to do the complete install? Because you don't need to. You just need Base Tools and g++ (for C++) and possibly gdb but that's not necessary too.
> Maybe it was a server problem. I suggest to try again, it doesn't take as long as waiting for the night...
> ...


Heres the error:
*img10.imageshack.us/img10/9715/24342726.th.jpg

Here's the "Download Complete" message:
*img14.imageshack.us/img14/9985/56843628.th.jpg

Anyway, I've set it for download now. Lets see what happens...


----------



## Gigacore (May 5, 2009)

*Re: Post ur C/C++ Programs Here*

Hi guys,

I am playing with a program to concatenate two string and find the length of the string using pointers. I am able to concatenate two strings, but when I try to find the length of the string, it gives incorrect output.

for example, if the given string is "forum", the output displays the length of the string as 1 instead of 5...

Here's the code:


```
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void menu();
void CONCAT(char *, char *);
void main()
{
	char str1[30], str2[30];
	int choice;

	while(1)
	{
		menu();
		scanf("%d", &choice);
		fflush(stdin);
		switch (choice)
		{
			case 1: printf("\nConcatenation operation\n");
				printf("\nEnter first string");
				gets(str1);
				fflush(stdin);
				printf("\nEnter second string");
				gets(str2);
				fflush(stdin);
				CONCAT(str1, str2);
				printf("\Concatenated string is \n");
				puts(str1);
				break;
			case 2: printf("\nLength operation \n");
				printf("\nEnter the string");
				gets(str1);
				printf("\nLength %d",LENGTH(str1));
				break;
			case 3: exit(0);
		}
		getch();
	}
}
void menu()
{
clrscr();
printf("\n1. Contenation of two strings");
printf("\n2. Length of the string");
printf("\n3. Exit");
printf("\nEnter your choice ");
}
void CONCAT(char *ptr1, char *ptr2)
{
	while(*ptr1!='\0') ++ptr1;
	while(*ptr2!='\0')
	{
		*ptr1=*ptr2;
		++ptr1;
		++ptr2;
	}
	*ptr1='\0';
	return;
}
int LENGTH(char *Ptr)
{
int l = 0;
while(*Ptr!='\0')
	{
		++l;
		++Ptr;
	}
return 1;
}
```

what's the error?


----------



## Liverpool_fan (May 5, 2009)

*Re: Post ur C/C++ Programs Here*


```
int LENGTH(char *Ptr)
{
int l = 0;
while(*Ptr!='\0')
	{
		++l;
		++Ptr;
	}
[B]return 1[/B];
}
```
Why are you returning *ONE* here? This should be return l (smallcase L)


----------



## Gigacore (May 5, 2009)

*Re: Post ur C/C++ Programs Here*

oh sh*t.. return 1 and 0 has become a practice for me.. 

Thanks Liverpool


----------



## melody~ (May 6, 2009)

*Re: Post ur C/C++ Programs Here*

some inputs from ma side ... here's a 1 line prog to fine if da number is in da power of 2

#define is_power_of_two(n) (! n & (n-1))


----------



## melody~ (May 6, 2009)

*Re: Post ur C/C++ Programs Here*

^^ just 1 change (!(n & (n-1))) ... missed 1 openin brac.


----------



## vamsi360 (May 8, 2009)

*Re: Post ur C/C++ Programs Here*

My OS Lab programs all written by me...I loved writing those....I rocked the lab!...
*BANKER'S ALGORITHM*

```
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int main() {
    int **max,**need,**alloc;
    int *avail,*flag,*sum,*res,c=0,count=0;
    int i,j,k,l,m,n;
    printf("\nEnter the dimensions of matrix:");
    scanf("%d %d",&m,&n);
    flag=(int *)malloc(m*sizeof(int));
    max=(int **)malloc(m * sizeof(int *));
    need=(int **)malloc(m * sizeof(int *));
    alloc=(int **)malloc(m * sizeof(int *));
    avail=(int *)malloc(n*sizeof(int));
    sum=(int *)malloc(n * sizeof(int));
    res=(int *)malloc(n * sizeof(int));
    for(i = 0; i < m; i++) {
        max[i] = (int *)malloc(n * sizeof(int));
        need[i]=(int *)malloc(n * sizeof(int));
        alloc[i]=(int *)malloc(n * sizeof(int));
    }
    for(i=0;i<m;i++) {
        flag[i]=0;
        sum[i]=0;
    }
    printf("\nEnter the instances of %d resources :",n);
    for(i=0;i<n;i++) {
        scanf("%d",&res[i]);
    }
    printf("\nEnter MAX matrix :\n");
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            scanf("%d",&max[i][j]);
    printf("\nEnter Allocation matrix :\n");
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            scanf("%d",&alloc[i][j]);
    printf("\nNeed matrix : ");
    for(i=0;i<m;i++) {
        for(j=0;j<n;j++) {
            need[i][j]=max[i][j]-alloc[i][j];
        }
    }
    for(i=0;i<m;i++) {
        for(j=0;j<n;j++) {
            printf("%d ",need[i][j]);
        }
        printf("\n");
    }
    for(i=0;i<n;i++) {
        for(j=0;j<m;j++) {
            sum[i]+=alloc[j][i];
        }
    }
    printf("\nSUM matrix :");
    for(i=0;i<n;i++) {
        printf("%d ",sum[i]);
    }
    for(i=0;i<n;i++)
        avail[i]=res[i]-sum[i];
    printf("compare\n");
    for(i=0;;i++) {
        i=i%m;
        count=0;
        if(c==m)
            break;
        if(flag[i]==1) {
            c++;
            continue;
        }
        for(j=0;j<n;j++) {
            if(avail[j]>=need[i][j]) {
                count++;
            }
        }
        if(count==3) {
            printf("\nProcess-p%d cleared\t",i);
            for(j=0;j<n;j++) {
                avail[j]+=alloc[i][j];
                flag[i]=1;
                printf("%d  ",avail[j]);
            }
        }
    }
    printf("\nDONE!");
}
[B]
```

OPRA ALGORITHM[/B]


```
#include<stdio.h>
int arr[20]={7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1};
int fr[3]={7,0,1};
int count(int p) {
    int i,j,k,l,large,index=0;
    int c[3]={0,0,0};
    for(j=0;j<3;j++) {
        for(i=p;i<20;i++) {
            if(fr[j]==arr[i]) 
                break;
            else
                c[j]++;
        }
    }
    large=c[0];
    for(i=1;i<3;i++) {
        if(large<c[i]) {
            large=c[i];
            index=i;
        }
    }
    return index;
}
void display() {
    int i;
    for(i=0;i<3;i++)
        printf("%d \t",fr[i]);
    printf("\n");
}

int main() {
    int i,j,k,l;
    int index;
    for(i=3;i<20;i++) {
        if(fr[0]==arr[i] || fr[1]==arr[i] || fr[2]==arr[i])
                continue;
        index=count(i);
        fr[index]=arr[i];
        display();
    }
}
[/CODE}
```


----------



## ╬Switch╬ (May 11, 2009)

*Re: Post ur C/C++ Programs Here*

Hi, Im learning a lot of C programming from this thread, thanks to all the great people contributing.
I just tried a program:

```
#include<stdio.h>
#include<conio.h>
void main()
{
 int a=4,b,c;
 clrscr();
 b=a++*a++;
 printf("b=%d",b);
 a=4;
 a=a++*a++;
 printf("\na=%d",a);
 getch();
}
```
Why does b show 16 while a=18?
This is what I understand:
b=a++*a++ is evaluated as b=a*a and then the incrementation occurs, but I can't understand the next o/p, ie "a".


----------



## Kl@w-24 (May 11, 2009)

*Re: Post ur C/C++ Programs Here*



╬Switch╬ said:


> #include<stdio.h>
> #include<conio.h>
> void main()
> {
> ...



The next operation goes as follows:

You wrote a = a++ * a++;

a=4*4

a=16

Now, twice a++:

a=16+1=17
a=17+1=18

a=18

The post-increment occurs after the multiplication has been performed, and since the val of a is now 16, after incrementing it twice, it becomes 18.


----------



## ╬Switch╬ (May 11, 2009)

*Re: Post ur C/C++ Programs Here*

^^Thanks 
One more thing, I just realised that TC is ancinet, so Im trying to find a newer editor+compiler.
I think Ill go with Rleo for the editor and whats the difference between G++ and and MinGW.
Is there any other editor better than Relo?


----------



## Liverpool_fan (May 11, 2009)

*Re: Post ur C/C++ Programs Here*



╬Switch╬ said:


> Hi, Im learning a lot of C programming from this thread, thanks to all the great people contributing.
> I just tried a program:
> 
> ```
> ...



Keep in mind to avoid using code such as b = a++ + a++ or a = a++ + a++. No I am not joking. C is not owned by a community or a vendor that dictates the way the language behaves. So as a result particulary in case of post-fix and pre-fix operations there is the side-effect whose behaviour depends on the implementation details of the compiler. For instance if I compile these statements with gcc -Wall (which means using GCC compiler with ALL warnings enabled) then, I get the Warning:


			
				gcc -Wall said:
			
		

> abc.c:7: warning: operation on ‘a’ may be undefined


In language such as Java and C#, since the language is owned by a company/community, so in those languages one doesn't have to worry about such details since each compiler. But in C it depends from compiler to compiler.

Though only for learning, try all permutations and combinations of the post fix and pre fix operations and learn them (they are pretty popular VIVA questions) but just keep on mind the implementation varies from compiler to compiler.

Thus my advice would be that beyond the scope of learning, avoid using statements such as these in C. 

EDIT: Few links:
*bytes.com/groups/c/222558-operation-x-may-undefined
*c-faq.com/expr/evalorder2.html

P.S. If this confuses you, you can easily ignore the above post. 



╬Switch╬ said:


> ^^Thanks
> One more thing, I just realised that TC is ancinet, so Im trying to find a newer editor+compiler.
> I think Ill go with Rleo for the editor and whats the difference between G++ and and MinGW.
> Is there any other editor better than Relo?



Just look at my sig. MinGW is the compiler (Minimalist GNU for Windows) and Geany is the IDE. Set 'em up.


----------



## ╬Switch╬ (May 11, 2009)

*Re: Post ur C/C++ Programs Here*

^^Thanks mate


----------



## ╬Switch╬ (May 12, 2009)

*Re: Post ur C/C++ Programs Here*

Guys is there any difference between exit(0) and exit(1)???


----------



## Liverpool_fan (May 12, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
For normal exits, use exit(0), for abnormal termination use exit(1), exit(2)....depending on the error code. (0-127 IIRC)

Also take note...for more clarity of code:
#include <stdlib.h>


```
exit(EXIT_SUCCESS); /*equivalent to exit(0) */
exit(EXIT_FAILURE); /*equivalent to exit(1) or it may range from 1-127*/
```

(also you could you these variables with the return statements)


----------



## ╬Switch╬ (May 12, 2009)

*Re: Post ur C/C++ Programs Here*



Liverpool_fan said:


> ^ ^ ^
> For normal exits, use exit(0), for abnormal termination use exit(1), exit(2)....depending on the error code. (0-127 IIRC)
> 
> Also take note...for more clarity of code:
> ...


I did some search and I think that normal exit is when you want to stop the program after a successful operation and abnormal exit is when you stop the program after an error. Do I sound right?


----------



## Liverpool_fan (May 12, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
Yes


----------



## rajkishor09 (May 13, 2009)

*Re: Post ur C/C++ Programs Here*

hello, i have found a good c program but cannot post that here due to copyright issues you can follow that here.
*hubpages.com/_iinfo/hub/File-Copy-Program-in-C-Language

*hubpages.com/_iinfo/hub/Turn-Your-PC-Keyboard-to-Musical-Keyboard


----------



## Liverpool_fan (May 23, 2009)

*Re: Post ur C/C++ Programs Here*

Old quotes but well...



aditya.shevade said:


> Easy. Check this out.
> 
> 
> ```
> ...


While this solution is impressive, got to say gcc -Wall would give a warning about "undefined behaviour" and that's due to the fact that a is being initialized at the same time and also used between sequence points.
Though it will work well in MOST compilers though. But C Programmers should avoid tricks such as these in real world.



Yamaraj said:


> Temptation. It's here :- *a^=b^=a^=b*


This expression is undefined in C.  This code will modify variable a twice between sequence points and hence it falls in undefined domains of behaviour in C. (Though it works well)
The correct method is:

```
a ^= b;
b ^= a;
a ^= b;
```

But that will work ONLY for integers.


----------



## visu (May 30, 2009)

*Re: Post ur C/C++ Programs Here*

Hello everyone this is a program for the game "FLAMES"-it tests the relationship between a boy and a girl(people think like that)

#include<stdio.h>
#include<ctype.h>
#include<string.h>
int commonnum (char s1[20],char s2[20]);
int main()
{
int sp=0,i,m=6,x,j=0,q;
char s[]={'f','l','a','m','e','s'},fate,change_fate,name1[20],name2[20];
printf("\n%s",s);
start:
printf("\nenter a names");
scanf("%s",name1);
printf("\nenter second name");
scanf("%s",name2);

x=commonnum(name1,name2);
if (x==0)
{
    printf("\naaaa no cheating!!!!");
    goto start;
}
printf("\n%d",x);
y:
for(i=0;i<m;i++)
  {if(s_!='!')
     {
       if(j==x-1)
        {
        s='!';
        j=-1;
        sp++;
        }
     j++;
     }

if(i==m-1)
goto y;
  if(sp==5)
     {
      for(q=0;s[q]!='\0';q++)
        if(s[q]!='!')
         {printf("\n%c",fate=toupper(s[q]));

         switch(fate)
         {case 'F'rintf("\nFRIEND! not bad can try later;");break;
         case 'L'rintf("\nLOVER!!! u r the luckiest being on earth");break;
         case 'A'rintf("AFFECTION! end up u r life making difference b/w love and affection");break;
         case 'M'rintf("\nMARRIAGE!!! a famous saying \"wife is a knife that cuts u r life\"");break;
         case 'S'rintf("SISTER!!!! i pity you ");break;
         case 'E'rintf("ENEMIES lets wage a war!!!!!!!!!");
         }}
     break;}
 }
 getchar();
 printf ("Wanna change u r love ?\n");

 change_fate=getchar();
 if(change_fate=='y')
 goto start;
 return 0;}
int commonnum(char name1[],char name2[])
{int i,j,count=0;
 char temps[20];    

    if(strlen(name2)>strlen(name1))
       {   strcpy(temps,name1);
          strcpy(name1,name2);
          strcpy(name2,temps);
      }
          for(i=0;name2!='\0';i++)
               for(j=0;name1[j]!='\0';j++)
                  if(name2==name1[j])


            count++;
        return strlen(name1)+strlen(name2)-2*count;

}      

enjoy it and any comments are welcome_


----------



## deb.sasmal (Jun 6, 2009)

*Re: Post ur C/C++ Programs Here*

*Circle Drawing :*

#include<graphics.h>
#include<conio.h>
#include<stdio.h>
void circlePlotpoints(int xcenter,int ycenter,int x,int y)

{
putpixel(xcenter+x,ycenter+y , 10 );
putpixel(xcenter-x,ycenter+y , 10 );
putpixel(xcenter+x,ycenter-y , 10 );
putpixel(xcenter-x,ycenter-y , 4 );
putpixel(xcenter+y,ycenter+x , 5 );
putpixel(xcenter-y,ycenter+x , 6 );
putpixel(xcenter+y,ycenter-x , 7 );
putpixel(xcenter-y,ycenter-x , 8 );

}
void circleMidpoint(int xcenter,int ycenter,int radius)
{
int x=0;
int y=radius;
int p=1-radius;
void circlemidpoint(int,int,int,int);
/* Plot first set of points */
circlePlotpoints(xcenter,ycenter,x,y);
while(x<y)
{
x++;
if(p<0)
p+=2*x+1;
else
{
y--;
p+=2*(x-y)+1;

}
circlePlotpoints(xcenter,ycenter,x,y);

}

}
void main()
{
int d=DETECT,c;
initgraph(&d,&c,"");
circleMidpoint(300,300,100);
getch();
}


----------



## boeing_737 (Jul 4, 2009)

*Re: Post ur C/C++ Programs Here*

Hi guys, this program isn't so clear. I have written comments to explain. Any help would be appreciated!


```
#include <stdio.h>

#define PRODUCT(x) (x*x)

int main()
{
	int j,k,i=3;

	j = PRODUCT(i++); // returns i value, 
                                // then increments ie i=3 is returned,
                                // which is sent to PRODUCT to give j = 9. 
                               //Then, i is incremented to 4

	k = PRODUCT(++i); // here, i is first incremented, 
                                 //so i = 5 now, which is sent to
				  // PRODUCT to give 25.
	printf("\nj = %d, k = %d",j,k); // j=9, k=25... INCORRECT ANS!
				// j=9, k=49 is the correct answer on execution.
	return 0;
}
```
Thanks!
-yogesh


----------



## Liverpool_fan (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



boeing_737 said:


> Hi guys, this program isn't so clear. I have written comments to explain. Any help would be appreciated!
> 
> 
> ```
> ...


*PRODUCT(i++) *is replaced as i++ * i++, where you get the correct answer, increments i later due to postfix but first multiplies, so 9 as you got it. (3*3)
However i is incremented TWICE, so i value becomes 5.
Again *PRODUCT(++i)* is replaced as ++i * ++i, now prefix operation is performed before multiplication, so before multiplication i is incremented twice that is to 7, and 7 * 7 = 49.

Another thing is that this program will give warnings with -Wall flag in gcc because twice incrementing withing sequence points is an "undefined behaviour" in C.


----------



## adatapost (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



max_demon said:


> My Program to calculate Addition
> 
> 
> ```
> ...


 
Hi,

Why you add system("pause")? Are programs like Excel, Word, IE etc pauses after we click on close button?

I think it is bad practice to learn and teach c programming. Sometimes people uses getch() in place of system(). It should be stop. 

Thanks,
adatapost


----------



## adatapost (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



Liverpool_fan said:


> *PRODUCT(i++) *is replaced as i++ * i++, where you get the correct answer, increments i later due to postfix but first multiplies, so 9 as you got it. (3*3)
> However i is incremented TWICE, so i value becomes 5.
> Again *PRODUCT(++i)* is replaced as ++i * ++i, now prefix operation is performed before multiplication, so before multiplication i is incremented twice that is to 7, and 7 * 7 = 49.
> 
> Another thing is that this program will give warnings with -Wall flag in gcc because twice incrementing withing sequence points is an "undefined behaviour" in C.


 
Increment/decrement operators have undefinite behaviour with different languages/compilers.


----------



## Liverpool_fan (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



adatapost said:


> Increment/decrement operators have undefinite behaviour with different languages/compilers.



And different architectures too. That's why they have to be avoided.
Not sure of languages though, increment decrement operators are pretty well defined in languages like Java or C#.


----------



## adatapost (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*

Hi,

I read number of threads. 90% of programs of c/c++ are written in old-standard (13 years old). 

Students and tutors must have to learn something new in c/c++ standard. 

*siddhant3s.googlepages.com/how_to_tell_rusted_cpp.html
*home.datacomm.ch/t_wolf/tw/c/ten_commandments.html
*david.tribble.com/text/cdiffs.htm

Use CodeBlocks, Dev-C++, or Visual Studio 2008 compiles - They are free. Do not use old compilers.

conio.h, graphics.h and some other header files are depreciated. Don't put getch() or system("pause") at the end of program.

We always looking for the best and new things. So why not about C/C++?

Thanks,
adatapost


----------



## Liverpool_fan (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
Nice posts.

Do me a favour and mail these links to Digit Admins. Reading their fast track to C++, I guess I know they really need these links...


----------



## adatapost (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



xbonez said:


> *here's a prog to calc area, surface area, volume, total surface area etc. of numerous 2D and 3D figures using functions*
> 
> i had made this one for a friend - it was his project
> 
> ...


 
Here are some non-standard features in your said c++ program.

1. do not use void with main()


```
int main() {
 
    return 0;
  }
```
2. Do not use deprecated header files and old-compilers - turboc 3.0 or something
    Use standard c/c++ compilers.
          CodeBlocks, Dev-C++ and Visual Studio 2008 are free compilers.
3. Read about c99 - It's a standard.
    *siddhant3s.googlepages.com/how_to_tell_rusted_cpp.html
    *home.datacomm.ch/t_wolf/tw/c/ten_commandments.html
    *david.tribble.com/text/cdiffs.htm


----------



## boeing_737 (Jul 5, 2009)

*Re: Post ur C/C++ Programs Here*



Liverpool_fan said:


> *PRODUCT(i++) *is replaced as i++ * i++, where you get the correct answer, increments i later due to postfix but first multiplies, so 9 as you got it. (3*3)
> However i is incremented TWICE, so i value becomes 5.
> Again *PRODUCT(++i)* is replaced as ++i * ++i, now prefix operation is performed before multiplication, so before multiplication i is incremented twice that is to 7, and 7 * 7 = 49.
> 
> Another thing is that this program will give warnings with -Wall flag in gcc because twice incrementing withing sequence points is an "undefined behaviour" in C.



Thanks! That helped a lot.  btw, Since people are mentioning about IDEs, if you want a C/C++ IDE, try Codelite - *www.codelite.org/ - It's open source, and it looks and works beautifully!


----------



## mercyjane (Jul 9, 2009)

*Re: Post ur C/C++ Programs Here*

Good that you have a open source programmers.


----------



## Ultimate_Winner (Aug 30, 2009)

*Re: Post ur C/C++ Programs Here*

I have just started my c++ programming.

Will surely post here when I will learn some more.

Great Thread.


----------



## yatinkumar (Sep 8, 2009)

*Re: Post ur C/C++ Programs Here*

I need help regarding calloc and malloc. I want to solve this question 


The standard library function calloc(n,sz) returns a pointer to n objects of size sz, with the storage initialized to zero. Write calloc, by calling malloc or by modifying it. 
So plz can somebody help me out
thanx in advance


----------



## Manan Saxena (Oct 11, 2009)

*Re: Post ur C/C++ Programs Here*

hi ... 
this is linkage  new on digit 
i m a btech student 1st year(cs)without the official background of cs language i.e nt have cs in 11th and 12th..
i m using "Yashwant's Kanetkar" Let u C.....i just want to know is their any better book then this .... and one more thing can i finish C in 6mnths or 1st semister...


----------



## Liverpool_fan (Oct 11, 2009)

*Re: Post ur C/C++ Programs Here*

^ ^ ^
Yashwant Kanetkar sucks  It's not a good book IMHO

K & R's The C Programming Language is the best book but may not be for beginner's. 
C Programming : A Modern Approach is another good book for C.

C can never be `finished`  but you can have your basics cleared in 6 months or so.


----------



## johnrosswrock (Oct 14, 2009)

*Re: Post ur C/C++ Programs Here*

#include<iostream.h>
void prime( int x)
{
 if(x==2)
 { cout<<"2 is a prime number.";
 }
 else if (x==3)
 {
   cout<<"3 is a prime number.";
 }
 else if (x==5)
 {
   cout<<"5 is a prime number.";
 }
 else if (x==7)
 {
   cout<<"7 is a prime number.";
 }
 else if (x<=0)
 {
   cout<<x<<" is not prime.";
 }
 else if (x/2 || x/3 || x/5 || x/7 == 0)
 {
   cout<<x<<" is not prime.";
 }
 else 
 {
   cout<<x<<" is prime.";
 }
}

int main()
{
 int  x;
 cout<<"Enter any  integer:\n";
 cin>>x;
 cout<<"\n";
 prime(x);
 return 0;
}


----------



## azaad_shri75 (Oct 23, 2009)

*Re: Post ur C/C++ Programs Here*

what is the best full functional free C++ compiler for windows like GCC in linux.


----------



## krishnandu.sarkar (Nov 2, 2009)

*Re: Post ur C/C++ Programs Here*

Use Dev C++ it runs on MingW Compiler


----------



## nkhlgeorge (Dec 6, 2009)

*Re: Runnign TC version 3 on win 7-64 bit*

Hey I recently installed windows 7 ultimate edition 64 bit on my computer. However ever since then Turbo C++  v3.0 has stopped functioning. I get the following error  message-

*i47.tinypic.com/14dfths.png





I tried googling the problem and got the following results-
You can run Turbo C++ 3.0 on Windows XP 64 bit , Vista 32 bit and 64 bit OS (in full screen)

Install the software DOSBox ver 0.72 (Freeware) from the link below (Direct Link)

     Code:
     *prdownloads.sourceforge.net/dosbox/DOSBox0.72-win32-installer.exe?download 
Before going to the details u have to create a folder (any name will do).

Here we name it as Turbo

Copy the TC into the Turbo folder (djdat: I think this means the copy of turbo c++ 3.0)

Run the DOSBox 0.72 from the icon located on the desktop or from the location of the installation folder

Then u are presented with two screens which look like the command prompt in Windows

Now you are presented with two screens. One with a Z prompt. U can ignore the other screen.

There type the following commands at the command prompt [Z]:

Mount [Type in any alphabet that u wish except z] [Type the source of the turbo C] press enter

For example (Type in the following commands after the Z prompt):

Z: mount d c:\Turbo\ [The folder TC is present inside the folder Turbo]

* Now u should get a message which says: Drive D is mounted as a local directory c:\Turbo\ ***

C:\> cd TC [The contents inside the folder Turbo gets mounted as a virtual drive (Here D drive)



*i followed the instructions , TC worked , but it doesn't compile any of my programmes, I dont think its reading the library files- heres the error i get-
* 
*img688.imageshack.us/img688/3276/15rd3kx.th.jpg


----------



## openSUSE (Dec 9, 2009)

*Re: Post ur C/C++ Programs Here*

this is really helpful.....!!!


----------



## aniket.awati (Dec 28, 2009)

*Re: Post ur C/C++ Programs Here*

whole lot of trouble just to get turbo c working...
lol

---------- Post added at 08:53 PM ---------- Previous post was at 08:51 PM ----------

whole lot of trouble just to get turbo c working...
lol


----------



## Ashit Kumar (Jan 12, 2010)

*Re: Post ur C/C++ Programs Here*



Pathik said:


> y r u using scanf in c++???


scanf used only in c.........


----------



## tirthbodawala (Jan 18, 2010)

*Re: Post ur C/C++ Programs Here*



shady_inc said:


> ....and */ after the comment.
> 
> can someone tell me what's wrong in this program.Using Dev C++


first of all declare the function calsum after _namespace std;_
and ur program would work

---------- Post added at 03:12 PM ---------- Previous post was at 03:01 PM ----------

want to look at c++ real programing in DEV c++. download source files from below!

hXXp://CCC.ziddu.com/download/8211925/Neuti.zip.html

replace XX with tt 
   and CCC with www.
please feedback


----------



## abyss88 (Jan 28, 2010)

*Re: Post ur C/C++ Programs Here*

plz write a function that will concatenate two circular linked lists...

thanks


----------



## Apple Juice (Jan 28, 2010)

*Re: Post ur C/C++ Programs Here*

@abyss
dood tis is nt de way.  u sud try writinh tehj program n theen tryy 2 take help. i will try 2 help u sureely if u d0 dat. mayybe if i've s0me time i will help u. 

the only thing i cann say now iz dat the tail of the first lnked list should point 2 the head of 2nd lnked lst and the tail of the 2nd lnked lst sud p0int 2 head of 1st lnked list. 
u sud try 2 write using tis method. 

visca la barca


----------



## abyss88 (Jan 28, 2010)

*Re: Post ur C/C++ Programs Here*

dude...actually a friend is asking me to solve his problems....i'm not much into programming so..i suck at it..plz help out


----------



## Apple Juice (Jan 28, 2010)

*Re: Post ur C/C++ Programs Here*

but if ur frend d0esnt b0ther even to try to start soolving it, why wuud we bother  if he wrritten an incorrectt program evenn i wud ave luved 2 help him butt tis is lazyness. 

mes que un club

---------- Post added at 05:47 PM ---------- Previous post was at 05:45 PM ----------

sorry if i m being harsh but i lyk people givin effort 

---------- Post added at 05:48 PM ---------- Previous post was at 05:47 PM ----------

gimme me day 0r two i mite write it tho


----------



## aniket.awati (Jan 31, 2010)

*Re: Post ur C/C++ Programs Here*

@apple juice, even if  u write it..plz don't publish it.. it will encourage them to get it free without actually trying...


----------



## Apple Juice (Jan 31, 2010)

*Re: Post ur C/C++ Programs Here*



aniket.awati said:


> @apple juice, even if  u write it..plz don't publish it.. it will encourage them to get it free without actually trying...


u r rite


----------



## jamesroy (Feb 6, 2010)

*Re: Post ur C/C++ Programs Here*

hi ,
i got project which already developed in c/c++ as visual studio project so i have to convert it into the java so can u give any information regarding whether any tool is available for conversion or suggest me any way to do this in short time
waiting for reply please its very urgent


----------



## Ei8t (Feb 11, 2010)

*Re: Post ur C/C++ Programs Here*

Please someone reply FAST!!!
When do we make a Virtual Function "Pure"?


----------



## amraj (Feb 24, 2010)

*Re: Post ur C/C++ Programs Here*

can anybody help me to write code for displaying report in C. I would like to display a text file or any report file on screen through C program. While displaying the report line should be highlighted where the cursor is. This should not modify the original report or text file in any way.


----------



## azaad_shri75 (Mar 12, 2010)

*Re: Post ur C/C++ Programs Here*

what happened suddenly so many spammers, tired of reporting.


----------



## mkdeep (Apr 4, 2010)

*Re: Post ur C/C++ Programs Here*

any one  good  at  programming  and  living  in mumbai  please  PM  me


----------



## CA50 (Apr 4, 2010)

*Re: Post ur C/C++ Programs Here*

whats up where is your problem ??


----------



## Ron (Jun 29, 2010)

*Re: Post ur C/C++ Programs Here*

i want the offline version og this thread. IS there any method to download the whole thread...i dont want to save the page one by one......


----------



## The Conqueror (Sep 19, 2010)

*Re: Post ur C/C++ Programs Here*

Can you solve this problem? 

Most mobile phones have their own private dictionary of words to allow users to type messages
quicker. On a typical phone, each number key is assigned a subset of the alphabet
{a, b, ..., z}: 2 is assigned the subset {a, b, c}, 3 is assigned {d, e, f}, 4 is assigned {g, h, i}, 5 is
assigned {j, k, l}, 6 is assigned {m,n, o}, 7 is assigned {p, q, r, s}, 8 is assigned {t, u, v} and 9
is assigned {w, x, y, z}.
When the user types a sequence of numbers, this sequence is mapped to all possible
words that can be constructed from the key assignment. For instance, if the user types 66,
this could correspond to any one of the letter sequences “mm”, “mn”, “mo”, “nm”, “nn”,
“no”, “om”, “on” or “oo”. These letter sequences are looked up in the dictionary stored
in the phone and all matches are reported. For instance, if the phone’s dictionary contains
only “on” and “no” from this set of sequences, the user will be offered a choice of “on”
or “no” to insert in the message. Similarly, the input 4663 might be interpreted as either
“good” or “home”. An input sequence may have a unique interpretation—for example, the
only word in the dictionary matching the input 28 may be “at”. Other sequences may not
match any word in the dictionary—for instance, 99999.
Your task is the following. Given the typical assignment from number keys to letters of
the alphabet given above and given a dictionary of words, report the input sequence that
matches the largest number of words in the dictionary. For example, if the dictionary consists
of the words {at, on, good, no} then the answer is 66, because 66 matches both “on” and
“no” while no other input matches more than one word in the dictionary. On the other
hand, with the dictionary {at, on, good, no, home, gone}, the answer is 4663, because 4663
matches three words, “good”, “home” and “gone” in the dictionary.
Input format
The first line of input is an integer M, the number of words in the dictionary. This is
followed by M lines of input. Each line contain one word from the dictionary, where a word
is sequence of characters from the lowercase alphabet {a, b, c, ..., z}.
Note: Each word in the dictionary is, in general, an arbitrary sequence of letters from
{a, b, c, ..., z}. In particular, it is not assumed that the words stored in the dictionary are
valid words in English or any other language.
Output format
A single line containing the input sequence that matches the maximum number of words in
the dictionary. If multiple input sequences qualify for the maximum number of matches, it
suffices to report any one.
Test data
For all inputs, 1 < or equal to M < or equal to 100000. Each word in the dictionary is at most 8 characters long.
In 50% of the inputs, 1 < or equal to M < or equal to1000.

Example
Here is the sample input and output corresponding to the example discussed above.
Sample input 1
4
at
on
good
no
Sample output 1
66
Sample input 2
6
at
on
good
no
home
gone
Sample output 2
4663
Note: Your program should not print anything other than what is specified in the output
format. Please remove all diagnostic print statements before making your final submission.
A program with extraneous output will be treated as incorrect!


----------



## trickr18 (Sep 26, 2010)

*Re: Post ur C/C++ Programs Here*

how to make a text editor using C?if anyone knows pls submit the result!


----------



## legendary_noob (Nov 1, 2010)

*Re: Post ur C/C++ Programs Here*

what is the algorithm to determine if a binary tree is almost complete?


----------



## gkara (Nov 16, 2010)

*Trigonometric functions using C*

Hi,

A C program that would perfom the basic trigonometric function would have the below possible look:


```
#include<stdio.h>

int fact(int n)
{
  if(n == 0) return 1;
  else return(n * fact(n-1));
}

double power(float x, int y)
{
  int i = 1; double res = 1;
  if(y == 0) return i;
  if(y == 1) return x;
  for(i; i <= y; i++) res* = x;
  return res;
}

float trig(float x)
{
  double value = 0; int i, j;
  for(i = 0, j = 0; i <= 20; i += 2, j++)
    value += (power((float)-1,j))*(power(x,i)/fact(i));
  return value;
}

void main()
{
 double cosx, sinx; double const pi = (float)22/7;
 float x;
 again:
 printf("\nEnter the angle:");
 scanf("%f",&x);
 if(x>0 && x<=pi/2)
 {
   sinx = trig((pi/2)-x);
   printf("sin(%f) = %f", x, sinx); 
   cosx = trig(x);
   printf("\ncos(%f) = %f\n\n", x, cosx);
 }
 else
  goto again;
}
```


----------



## coderunknown (Nov 17, 2010)

*QUIZ game*

*A simple Quiz game. *

*PS:* please don't read the code until you finished playing the game once to enjoy spoiler free gameplay.


```
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
void quiz();
void iq_test();
void help();
void credit();
int ch=0, n=0;
cout<<"\n Welcome to CSE MINI PROJECT 2009 ";
do
{
cout<<"\n\n\n";
cout<<"\n MAIN MENU: \n";
cout<<"\n\n 1. Game. ";
cout<<"\n\n 2. Help. ";
cout<<"\n\n 3. Credit. ";
cout<<"\n\n 4. Exit. ";
cout<<"\n\n\n";
cout<<"\n Enter your choice (1-4): ";
cin>>ch;
switch(ch)
{
case 1: iq_test();
	cout<<"\n\n\n Press 1 to goto main menu or 0 to exit. ";
	cin>>n;
	break;
case 2: help();
	cout<<"\n\n\n Press 1 to goto main menu or 0 to exit.";
	cin>>n;
	break;
case 3: credit();
	cout<<"\n\n\n Press 1 to goto main menu or 0 to exit.";
	cin>>n;
	break;
case 4: n=0;
	break;
default: cout<<"\n Wrong Choice Entered. Game will Exit now. ";
}
}while(n==1);
getch();
}
void iq_test()
{
clrscr();
cout<<"\n\n\t\t GAME: IQ TEST ";
cout<<"\n\n\n\n";
char word[20];
int n;
cout<<" ________________________________________________________________";
cout<<"\n\n\n Question 1: \t\t\t\t Score: 0 of 10";
cout<<"\n\n\n\t What was the last name of the first US President? ";
cout<<"\n\n George __________\t";
cin>>word;
if(strcmp(word, "washington")==0 || strcmp(word, "Washington") == 0)
{
clrscr();
cout<<"\n Question 1: \t\t\t\t Score: 0 of 10";
cout<<"\n\n\n\t What was the last name of the first US President? ";
cout<<"\n\n George __________\t";
cout<<"Washnigton";
cout<<"\n\n Incorrect! The correct answer is Washington.";
}
else
{
cout<<"\n\n Incorrect! The correct answer is Washington.";
}
cout<<"\n\n\n ______________________________________________________________";

n=0;
cout<<"\n\n\n Question 2: \t\t\t\t Score: 0 of 10:";
cout<<"\n\n\n\t In which continent is Moscow located? ";
cout<<"\n\n\t\t 1. North America.";
cout<<"\n\t\t 2. Europe.";
cout<<"\n\t\t 3. Asia.";
cout<<"\n\t\t 4. Australia.";
cout<<"\n\n\t Ans: ";
cin>>n;
if(n==2)
{
cout<<"\n\n Incorrect! Moscow, Idaho, US is located in North America.";
}
else
{
cout<<"\n\n Incorrect! Moscow, Russia is located in Europe.";
}
cout<<"\n\n\n ______________________________________________________________";

n=0;
cout<<"\n\n\n Question 3: \t\t\t\t Score 0 of 10:";
cout<<"\n\n\n\t If your Mother's Brother is your Uncle.";
cout<<"\n\t Who is your Brother's Father's Father? ";
cout<<"\n\n\t\t 1. Your Uncle.";
cout<<"\n\t\t 2. Your Grandfather.";
cout<<"\n\t\t 3. Your Great Grandfather.";
cout<<"\n\t\t 4. Your Great Great Grandfather.";
cout<<"\n\n\t Ans: ";
cin>>n;
if(n==2)
{
cout<<"\n\n Incorrect! Your Mother's Brother's Father's Father is your Great Grandfather.";
}
else
{
cout<<"\n\n Incorrect! Your Brother's Father's Father is your Grandfather.";
}
cout<<"\n\n\n ______________________________________________________________";
n=0;
cout<<"\n\n\n Question 4: \t\t\t\t Score: 0 of 10:";
cout<<"\n\n\t Write the word 'Establishment' You have 10sec left";
cout<<"\n\n\t Ans: ";
cin>>word;
cout<<"\n\n Incorrect! You taken more than 10sec.";
cout<<"\n\n\n ______________________________________________________________";

n=0;
cout<<"\n\n\n Question 5: \t\t\t\t Score: 0 of 10:";
cout<<"\n\n\t Of the following, which is most likely to make a bull charge? ";
cout<<"\n\n\t 1. Green.";
cout<<"\n\t 2. Red.";
cout<<"\n\t 3. Black.";
cout<<"\n\t 4. None of above.";
cout<<"\n\n\t Ans: ";
cin>>n;
if(n==2)
{
cout<<"\n\n Incorrect! Bulls have no colour perception so they \n are likely to charge at red as they are at any other colour.";
}
else
{
cout<<"\n\n Incorrect! Bulls are trained to react at red.";
}
cout<<"\n\n\n ______________________________________________________________";

cout<<"\n\n\n Question 6: \t\t\t\t Score: 0 of 10.";
cout<<"\n\n\t Who discovered America? ";
cout<<"\n\n\t 1. Drake.";
cout<<"\n\t 2. Colombus.";
cout<<"\n\t 3. Megallan.";
cout<<"\n\t 4. Bering.";
cout<<"\n\n\t Ans: ";
cin>>n;
cout<<"\n\n Incorrect! America was discovered by Colombus.";
cout<<"\n\n\n ______________________________________________________________";

cout<<"\n\n\n Question 7: \t\t\t\t Score: 0 of 10.";
cout<<"\n\n\t Who wrote 'Hemlet The Prince of Denmark'?";
cout<<"\n\n\t 1. Aurthur Conan Doyle.";
cout<<"\n\t 2. Willian Shakespere.";
cout<<"\n\t 3. Jack Condon.";
cout<<"\n\t 4. Alexender Dumes.";
cout<<"\n\n\tAns: ";
cin>>n;
cout<<"\n\n Incorrect! The play Hemlet was written by William Shakesphere.";
cout<<"\n\n\n ______________________________________________________________";

n=0;
cout<<"\n\n\n Question 8: \t\t\t\t Score: 0 of 10.";
cout<<"\n\n\t Which month is the shortest? ";
cout<<"\n\n\t 1. May.";
cout<<"\n\t 2. February.";
cout<<"\n\t 3. August.";
cout<<"\n\t 4. November.";
cout<<"\n\n\t Ans: ";
cin>>n;
if(n==2)
{
cout<<"\n\n Incorrect! The shortest month is May (just 3 letters). ";
}
else
{
cout<<"\n\n Incorrect! The shortest month is February (29 days at most). ";
}
cout<<"\n\n\n ______________________________________________________________";

cout<<"\n\n\n Question 9: \t\t\t\t Score: 0 of 10.";
cout<<"\n\n\t Which is the first month of the year? ";
cout<<"\n\n\t 1. March.";
cout<<"\n\t 2. June.";
cout<<"\n\t 3. September.";
cout<<"\n\t 4. December.";
cout<<"\n\n\t Ans: ";
cin>>n;
cout<<"\n\n Incorrect! The first month of the year is January.";
cout<<"\n\n\n ______________________________________________________________";

n=0;
cout<<"\n\n\n Question 10: \t\t\t\t Score: 0 of 10.";
cout<<"\n\n\t Why couldn't you answer at least one question? ";
cout<<"\n\n\t 1. I'm Illiterate.";
cout<<"\n\t 2. I'm Stupid.";
cout<<"\n\t 3. I'm Crazy.";
cout<<"\n\t 4. The computer is cheating.";
cout<<"\n\n\t Ans: ";
cin>>n;
if(n==4)
{
cout<<"\n\n Incorrect! Computer doesn't cheat.";
}
else
{
cout<<"\n\n Correct! Finally you get the answer right.";
}
cout<<"\n\n\n ______________________________________________________________";
if(n==4)
{
cout<<"\n\n\n Your final score: 0 of 10.";
cout<<"\n\n\t Your IQ Rating:   Very Very Poor.";
}
else
{
cout<<"\n\n\n Your final score: 1 of 10.";
cout<<"\n\n\t Your IQ Rating:   Very Poor.";
}
cout<<"\n\n\n HOPE YOU ENJOY THE GAME. ";
}
void help()
{
cout<<"\n\n\t\\t HELP \n\n\n";
cout<<"\t 1. After the game starts, on choosing 1. ";
cout<<"\n\n\t 2. You'll be provided with 10 questions.";
cout<<"\n\n\t 3. Questions maybe multiple choice type or you'll have to type the answer.";
cout<<"\n\n\t 4. After answering all 10 questions, you'll be provided your score & IQ Rating.";
}
void credit()
{
cout<<"\n\n\t\t CREDIT \n\n\n";
cout<<"\t Programmer & Design:  ";
cout<<"\n\n\t Sammy. ";
}
```

game still in BETA stage. any & all suggestions are welcomed.


----------



## azaad_shri75 (Nov 17, 2010)

*Re: Post ur C/C++ Programs Here*

is it a part of the game or complete game in dos mode? and i think you are still using some ancient compiler.


----------



## ico (Nov 17, 2010)

*Re: Post ur C/C++ Programs Here*

^^ well, every school and most colleges still stuck on Turbo C/C++. Can't help it really.


----------



## coderunknown (Nov 17, 2010)

*Re: Post ur C/C++ Programs Here*



azaad_shri75 said:


> is it a part of the game or complete game in dos mode? and i think you are still using some ancient compiler.



whole game in DOS.



ico said:


> ^^ well, every school and most colleges still stuck on Turbo C/C++. Can't help it really.



2yr old piece of code. just posted. run it & don't accuse me if the game insult you


----------



## gkara (Nov 17, 2010)

*Re: Post ur C/C++ Programs Here*



Ron said:


> scanf("%d%d%d",&a,&b,&c);
> New to c++.......Whta those this line means



It means you are asking the end user the values which (s)he wants to have for the variables a, b and c. Once the user enters the values, you are immediately going to store them in the corresponding address of those variables.

&a = address of a
&b = address of b and so on.

%d = an integer value (You can also write as %i).

When you write--
                      scanf("%d", &a);
you are trying to store the integer value the user enters (i.e. the %d) in the address of a.

If it is %f, then, a is taking a float value accordingly to the statement. But if 'a' is not declared as float, then, it would throw an exception/error. The type should be taken care.

Hope you are now clear.


----------



## Piyush (Nov 19, 2010)

*Re: Post ur C/C++ Programs Here*

whats good in C# over c++?


----------



## Vyom (Dec 17, 2010)

*Re: Post ur C/C++ Programs Here*



Piyush said:


> whats good in C# over c++?



C# is a language specialized for .NET framework. C++ is for desktop applications. Thats a major difference between the two, besides many.

Others may correct me, if I am wrong.

For technical differences, this may help C# vs C++ - Eric Gunnerson's Compendium - Site Home - MSDN Blogs


----------



## Liverpool_fan (Dec 17, 2010)

*Re: Post ur C/C++ Programs Here*



Piyush said:


> whats good in C# over c++?


Your question is in context of (what are you looking for)?


----------



## subhransu123 (Dec 18, 2010)

*Re: Post ur C/C++ Programs Here*

A Program to find the largest and second largest of 10 numbers using nested if without using array.


----------



## shoukan (Jan 18, 2011)

*Program to Create a sorted merit list in files*

code:


```
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
#include<stdio.h>

void drawline();

class list
{
int id_no,phy,math,chem,csc,eng,lang;
char sname[30];

public: float perc;
	void readdata(int i)
       {
       cout<<"\nEnter the ID no of candidate "<<i+1<<":";
       cin>>id_no;
       cout<<"\nEnter the name of candidate "<<i+1<<":";

       gets (sname);
       cout<<"\nEnter the marks obtained by candidate in Physics,Chemistry,Maths,Comp.Sci,English,Sec_language:";

       cin>>phy>>chem>>math>>csc>>eng>>lang;
       perc=(phy+chem+math+csc+eng+lang)/6.0;
       }

       void display()
       {
       cout<<setiosflags(ios::left)<<setw(6)<<id_no<<setw(20)<<sname<<setw(6)<<phy<<setw(5)<<chem<<setw(9)<<math<<setw(7)<<
       csc<<setw(4)<<eng<<setw(6)<<lang<<setiosflags(ios::left)<<setw(12)<<perc<<endl;
       }

};

class temp
{
public:
 list z[10];
 void creation();
 void putdata();
 temp();
};


temp::temp()
{
int c,d=3;
do
{
cout<<"\n\n1:Start Program\n2:About\n3:Exit";
cout<<"\nEnter ur Choice:";
cin>>d;
switch(d)
{
case 1:{
do
{
 cout<<"\n\t\t1:Creation\n\t\t2:Display\n\t\t3:Exit";
 cout<<"\n Enter your Choice:";
 cin>>c;
switch(c)
 {
  case 1:clrscr();
	 creation();break;
  case 2:clrscr();
	 putdata();break;
 }d=3;
}
while(c!=3);
}

case 2:clrscr();
       cout<<"\n\tThis program accepts name & marks of a student in various subjects &\n\t sorts them according to their percentage in decending order.";
       cout<<"\n\nNote: The Maximum Marks Obtainable in each subject are 100.\n \tSee that you dont enter marks more than 100.";
       cout<<"\n\n \t Created by: Shoukan & Gautam";

  }
 }
while(d!=3);

}

void temp::creation()
{
int n,i,j;
fstream a;
list x;
a.open("list.dat",ios::out|ios::binary);
cout<<"Enter the no of students:";
cin>>n;

for(i=0;i<=n-1;i++)
z[i].readdata(i);

for(j=1;j<=n-1;j++)
for(i=0;i<=n-j-1;i++)
if(z[i].perc<z[i+1].perc)
{
x=z[i];
z[i]=z[i+1];
z[i+1]=x;
}


for(i=0;i<=n-1;i++)
a.write((char*)&z[i],sizeof(z[i]));

a.close();
}

void temp::putdata()
{
list x;
fstream b;
b.open("list.dat",ios::in|ios::binary|ios::left);
clrscr();
cout<<setiosflags(ios::left)<<setw(8)<<"Id_No"<<setw(17)<<"Name"<<setw(6)<<"Phy"<<setw(5)<<"Chem"<<setw(6)<<"Maths"<<setw(10)<<
       "Comp.sci"<<setw(4)<<"Eng"<<setw(6)<<"lang"<<setw(12)<<"Percentage"<<endl;
drawline();
while(b.read((char*)&x,sizeof(x)))
{
x.display();
drawline();
}
b.close();
}

void main()
{
clrscr();
temp p;
}


void drawline()
{
for(int i=1;i<=80;i++)
cout<<"-";
cout<<endl;
}

code:


#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
#include<stdio.h>

void drawline();

class list
{
int id_no,phy,math,chem,csc,eng,lang;
char sname[30];

public: float perc;
	void readdata(int i)
       {
       cout<<"\nEnter the ID no of candidate "<<i+1<<":";
       cin>>id_no;
       cout<<"\nEnter the name of candidate "<<i+1<<":";

       gets (sname);
       cout<<"\nEnter the marks obtained by candidate in Physics,Chemistry,Maths,Comp.Sci,English,Sec_language:";

       cin>>phy>>chem>>math>>csc>>eng>>lang;
       perc=(phy+chem+math+csc+eng+lang)/6.0;
       }

       void display()
       {
       cout<<setiosflags(ios::left)<<setw(6)<<id_no<<setw(20)<<sname<<setw(6)<<phy<<setw(5)<<chem<<setw(9)<<math<<setw(7)<<
       csc<<setw(4)<<eng<<setw(6)<<lang<<setiosflags(ios::left)<<setw(12)<<perc<<endl;
       }

};

class temp
{
public:
 list z[10];
 void creation();
 void putdata();
 temp();
};


temp::temp()
{
int c,d=3;
do
{
cout<<"\n\n1:Start Program\n2:About\n3:Exit";
cout<<"\nEnter ur Choice:";
cin>>d;
switch(d)
{
case 1:{
do
{
 cout<<"\n\t\t1:Creation\n\t\t2:Display\n\t\t3:Exit";
 cout<<"\n Enter your Choice:";
 cin>>c;
switch(c)
 {
  case 1:clrscr();
	 creation();break;
  case 2:clrscr();
	 putdata();break;
 }d=3;
}
while(c!=3);
}

case 2:clrscr();
       cout<<"\n\tThis program accepts name & marks of a student in various subjects &\n\t sorts them according to their percentage in decending order.";
       cout<<"\n\nNote: The Maximum Marks Obtainable in each subject are 100.\n \tSee that you dont enter marks more than 100.";
       cout<<"\n\n \t Created by: Shoukan & Gautam";

  }
 }
while(d!=3);

}

void temp::creation()
{
int n,i,j;
fstream a;
list x;
a.open("list.dat",ios::out|ios::binary);
cout<<"Enter the no of students:";
cin>>n;

for(i=0;i<=n-1;i++)
z[i].readdata(i);

for(j=1;j<=n-1;j++)
for(i=0;i<=n-j-1;i++)
if(z[i].perc<z[i+1].perc)
{
x=z[i];
z[i]=z[i+1];
z[i+1]=x;
}


for(i=0;i<=n-1;i++)
a.write((char*)&z[i],sizeof(z[i]));

a.close();
}

void temp::putdata()
{
list x;
fstream b;
b.open("list.dat",ios::in|ios::binary|ios::left);
clrscr();
cout<<setiosflags(ios::left)<<setw(8)<<"Id_No"<<setw(17)<<"Name"<<setw(6)<<"Phy"<<setw(5)<<"Chem"<<setw(6)<<"Maths"<<setw(10)<<
       "Comp.sci"<<setw(4)<<"Eng"<<setw(6)<<"lang"<<setw(12)<<"Percentage"<<endl;
drawline();
while(b.read((char*)&x,sizeof(x)))
{
x.display();
drawline();
}
b.close();
}

void main()
{
clrscr();
temp p;
}


void drawline()
{
for(int i=1;i<=80;i++)
cout<<"-";
cout<<endl;
}
```


----------



## somulesnar (Jan 20, 2011)

*Re: Post ur C/C++ Programs Here*

#include<stdio.h>
#include<conio.h>
main()
{
	float principal,time;
	float rate, SI,amount;
	printf("Please enter the principal:- ");
	scanf("%f", &principal);
	printf("Please enter the t4ime:- ");
	scanf("%f", &time);
	printf("Please enter the value of rate:- ");
	scanf("%f", &rate);
	SI=(principal*rate*time)/100;
	amount=principal+SI;
	printf("The Simplae Interest is found to be %f \n", SI);
	printf("And the amount si calculated to be %f \n", amount);

}


----------



## shiwa436 (Feb 3, 2011)

Gigacore said:


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


----------



## Neuron (Feb 10, 2011)

*Re: Post ur C/C++ Programs Here*

My First Game in C++!!!This game is developed with the help of Dark GDK.Its a simple pong game.The code isn't completely mine,I got the inspiration from this website A simple 2D pong game in darkGDK

To compile the code you will need 
1.Visual C++ Compiler

2.Dark GDK [*download.microsoft.com/download/a/a/1/aa1b34e1-e0d4-411a-8045-b732367e0e7e/Dark GDK.msi]

3.Directx SDK Aug 2007 [*download.microsoft.com/download/3/3/f/33f1af6e-c61b-4f14-a0de-3e9096ed4b3a/dxsdk_aug2007.exe]


Copy the attached png files to "Documents/Visual Studio/Projects/Project Name/Project Name/" directory by default

You can get the compiled version here *rapidshare.com/files/447205301/Dark_Pong.rar


code:

```
#include<DarkGDK.h>
#include<process.h>

float ballxvelocity=5,ballyvelocity=5,multfactor;  
int ballxcoord=100,ballycoord=150;  
int bat1xcoord=10,bat1ycoord=150;  
int bat2xcoord=600,bat2ycoord=150,dif,bonus;
long long dfc,score=0;


// the main entry point for the application is this function  
void DarkGDK ( void )  
{  
// turn on sync rate and set maximum rate to 60 fps  
dbSyncOn   ( );  
dbSyncRate ( 60 );  
dbSetWindowTitle("Pong");  
dbSetWindowSize(640	,480);  
dbLoadImage("ball.png",1);
dbLoadImage("bat1.png",2);  
dbLoadImage("bat2.png",3);  
  
   
dbSprite(1,100,150,1);     
dbSprite(2,5,150,2);    
dbSprite(3,600,150,3);    
  
  
  
// our main loop  
while ( LoopGDK ( ) )  
{  
//move the ball  
	if(ballxcoord<10) {   
		ballxvelocity*=-1;
		ballxcoord=50;      //to fix some bug
		dbSprite(1,ballxcoord,ballycoord,1);
		bonus=10;
	}
ballxcoord=dbSpriteX(1) + ballxvelocity;  
ballycoord=dbSpriteY(1) + ballyvelocity;  
dbSprite(1,ballxcoord,ballycoord,1);  

//if you miss the ball
if(ballxcoord>=638) {
	dbCLS();
	for ( int i = 1; i < 4; i++ )  {  
	dbDeleteSprite ( i );  
	dbDeleteImage ( 1 );  
}  
	dbPrint("Game Over\n");
	dbPrint("Your Score is ");
	dbPrint(score);
	dbPrint("A Game By Aj");
	dbSync();
	dbWait(1000);
	exit(0);
}

//to change direction during wall collission
if (ballycoord <= 0 || ballycoord >= 480)   
	ballyvelocity=ballyvelocity*-1;    
if (ballxcoord <= 0 || ballxcoord >= 640)  
	ballxvelocity=ballxvelocity*-1;  
  
  
//check bat collission  
if (dbSpriteHit(1,2)==1)  
{  
    dfc=(dbSpriteY(1)-dbSpriteY(2));
    dfc+=25;
    dif=(dfc-75);
    if (dif>=0&&dif<25) multfactor=2;
    else if(dif>=25&&dif<50) multfactor=1.75;
    else if(dif>=50&&dif<75) multfactor=1.5;
    else if(dif>=75&&dif<100) multfactor=1.25;
    else if(dif>=100&&dif<125) multfactor=1.25;
    else if(dif>=125&&dif<150) multfactor=1.5;
	else if(dif>=150&&dif<175) multfactor=1.75;
	else if(dif>=175&&dif<=200) multfactor=2;
	else multfactor=1;
	  
	ballxvelocity=ballxvelocity*multfactor*-1;  
	if(ballxvelocity==0) ballxvelocity=5;
	score+=multfactor+bonus;
	bonus=0;
}  
if (dbSpriteHit(1,3)==1)  
{  

	dfc=(dbSpriteY(1)-dbSpriteY(3));
	dfc+=25;
	dif=(dfc-75);
	if (dif>=0&&dif<25) multfactor=4;
	if (dif>=0&&dif<25) multfactor=2;
	else if(dif>=25&&dif<50) multfactor=1.75;
	else if(dif>=50&&dif<75) multfactor=1.5;
	else if(dif>=75&&dif<100) multfactor=1.25;
	else if(dif>=100&&dif<125) multfactor=1.25;
	else if(dif>=125&&dif<150) multfactor=1.5;
	else if(dif>=150&&dif<175) multfactor=1.75;
	else if(dif>=175&&dif<=200) multfactor=2;
	else multfactor=1;
	ballxvelocity=ballxvelocity*multfactor*-1;  
	if(ballxvelocity==0) ballxvelocity=5;
	score+=multfactor;
}  

bat1ycoord=ballycoord;
dbSprite(2,bat1xcoord,bat1ycoord,2);
  
//moves player 2 bat  
if (dbUpKey()==1&&bat2ycoord>0)  {  
	bat2ycoord=bat2ycoord-5;  
	dbSprite(3,bat2xcoord,bat2ycoord,3);  
}  

if (dbDownKey()==1&&bat2ycoord<480)  {  
	bat2ycoord=bat2ycoord+5;  
	dbSprite(3,bat2xcoord,bat2ycoord,3);  
}  
  
  
// update the screen  
dbPrint("Score :");
dbPrint(score);
dbSync ( );  
if(ballxvelocity==0) ballxvelocity=5;
} 


// return back to windows  
return;  
}
```


----------



## nims11 (Feb 12, 2011)

*Re: Post ur C/C++ Programs Here*

Prime Number checker using 3 different algorithms-


```
#include<iostream>
#include<math.h>
using namespace std;
int prime1(long unsigned int n); //conventional
int prime2(long unsigned int n); //super fast
int prime3(long unsigned int n); //super fast reduced form
int prime1(long unsigned int n)
{
    for(long unsigned int i=2;i<=n/2;i++)
    {
             if(n%i==0)
             return 0;
    }
    return 1;
}
int prime2(long unsigned int n)
{
    long unsigned i=2;
long unsigned j=n;
while(i<j)
{
    if(n%i==0)
    {
        return 0;
    }else
    j=(n/i);
    i++;
}
return 1;
}
int prime3(long unsigned int n)
{
    int j=sqrt(n);
    for(long unsigned int i=2;i<=j;i++)
    {
             if(n%i==0)
             return 0;
    }
    return 1;
}
int main()
{
    int n;
    cout<<"Enter a Number : ";
    cin>>n;
    if(prime1(n)==1)
    cout<<n<<" is Prime (by algorithm 1)\n";
    else
    cout<<n<<" is not Prime (by algorithm 1)\n";
    if(prime2(n)==1)
    cout<<n<<" is Prime (by algorithm 2)\n";
    else
    cout<<n<<" is not Prime (by algorithm 2)\n";
    if(prime3(n)==1)
    cout<<n<<" is Prime (by algorithm 3)\n";
    else
    cout<<n<<" is not Prime (by algorithm 3)\n";
    return 0;
}
```


----------



## Neuron (Mar 28, 2011)

*Infix to postfix conversion & postfix evaluation*

Infix to postfix converter:


```
#include<stdio.h>
#include<conio.h>

int preced(char c);

char stack[20],post[20],ar[20];
int i=0,j=0,top=0;

void main() {
	printf("\nEnter the infix expression>>>");
	gets(post);

	for(;post[i]!='\0';i++) {
		switch(post[i]) {
			case '(':
				stack[top]=post[i];
				top++;
				break;
			case ')':
				for(top--;stack[top]!='(';top--){
					ar[j]=stack[top];
					j++;
				}
				break;
			case '^':
			case '*':
			case '/':
			case '+':
			case '-':
				if(preced(stack[top-1])<preced(post[i])) {
					stack[top]=post[i];
					top++;
				}
				else {
					while(preced(post[i])<=preced(stack[top-1])) {
						ar[j]=stack[top-1];
						j++;top--;
					}
					if(preced(post[i])>preced(stack[top-1])) {
						stack[top]=post[i];
						top++;
					}
				}
				break;
			default:
				ar[j]=post[i];
				j++;
				break;
		}
	}
	for(top--;top>=0;top--) {
		ar[j]=stack[top];
		j++;
	}
	ar[j]='\0';
	printf("The postfix expression is<<<");
	puts(ar);
	getch();

}

int preced(char c) {
	if(c=='^') return 5;
	else if(c=='*'||c=='/') return 4;
	else if(c=='+'||c=='-') return 3;
	else return 2;
}
```

A simple postfix expression solver


```
#include<stdio.h>
#include<stdio.h>
#include<string.h>
#include<math.h>

char post[50];

float temp1,temp2,stack[50];
int top=0,l,i;

void main()
{
	printf("Enter the postfix expression>>>");
	gets(post);
	l=strlen(post);
	for(i=0;i<l;i++) {
		if(isalpha(post[i])) {
			printf("Enter the value of the variable %c>>>",post[i]);
			scanf("%f",&stack[top]);
			top++;
		}
		else {
			temp2=stack[top-1];
			temp1=stack[top-2];
			switch(post[i]) {
				case '^':
					stack[top-2]=pow(temp1,temp2);
					top--;
					break;
				case '*':
					stack[top-2]=temp1*temp2;
					top--;
					break;
				case '/':
					stack[top-2]=temp1/temp2;
					top--;
					break;
				case '+':
					stack[top-2]=temp1+temp2;
					top--;
					break;
				case '-':
					stack[top-2]=temp1-temp2;
					top--;
					break;
			}
		}
	}
		printf("\nThe result is<<<%f \n",stack[top-1]);
		getch();
}
```

Sample input and output:
       Actual Infix expression         : (a+b)*(c/d)+(e^f)/g
       Equivalent postfix expression: ab+c*d/ef^g/+
if a=2,b=3....,g=8 then output is 34996


----------



## nims11 (Mar 28, 2011)

*Re: Post ur C/C++ Programs Here*

^^ nyc. i had made a program to evaluate postfix expression but it is very long and quite slow as my program directly takes number instead of variables. so i had to make functions to extract the numbers and convert the to from string to "int".

then i decided to make a program that directly evaluates any infix expression which i used with my function plotter to plot graphs(there is a post titled function plotter smwhere in the programming section of this forum). it is quite long so please let me know of any bugs and erroneous values it outputs for any expression. here is the code -


```
#include<iostream>
#include<cstring>
#include<cmath>
#include<stdio.h>
using namespace std;
char expr[100];
float var;
float str2Float(char str[100],int start,int end)
{
      if(start==end && str[start]=='x')
      return var;
      int decimal=-1;
      float result=0;
      if(str[start]!='-')
      {
      for(int i=start;i<=end;i++)
      {
              if(str[i]=='.')
              decimal=i;
      }
      if(decimal==-1)
      {
                for(int i=end;i>=start;i--)
                result+= ((int)str[i]-48)*pow(10,(float)(end-i));
      }else
      {
           int tmp=0;
           for(int i=decimal-1;i>=start;i--)
           result+= ((int)str[i]-48)*pow(10,(float)(decimal-i-1));
           for(int i=end;i>decimal;i--)
           tmp += ((int)str[i]-48)*pow(10,(float)(end-i));
           result += tmp/pow(10,(float)(end-decimal));
      }

      return result;
      }else
      return -1*str2Float(str,start+1,end);
}

int isNum(char ch)
{
    if(ch>=48 && ch<=57 || ch==46 || ch==45 || ch=='x')
    return 1;

    return 0;
}

float boperation(float o1,float o2,char o)
{
      switch(o)
      {
             case '^': return pow(o1,o2);
             case '/': return o1/o2;
             case '*': return o1*o2;
             case '+': return o1+o2;
      }
}

float mod(float o1)
{
      if(o1<0)
      return -1*o1;
      return o1;
}

float uoperation(float o1,int o)
{
      switch(o)
      {
               case 0: return sin(o1);
               case 1: return cos(o1);
               case 2: return tan(o1);
               case 3: return 1/tan(o1);
               case 4: return 1/cos(o1);
               case 5: return 1/sin(o1);
               case 6: return mod(o1);
               case 7: if(o1>0)
               return log(o1);
               else
               return 1000;
               case 8: return floor(o1);
               case 9: return ceil(o1);
      }
}

void solveUnary(char in[100],int size)
{
    char unary[10][6]={"sin","cos","tan","cot","sec","cosec","mod","log","floor","ceil"};
    int unasize=10;
    char tmp[6];
    int count=0;
    for(int i=0;i<size;i++)
    {
       if(in[i]>=97 && in[i]<=122 && in[i]!='x')
       {
          tmp[count++]=in[i];
          tmp[count]='\0';
       }

       if(in[i]>=97 && in[i]<=122 && (isNum(in[i+1]) || in[i+1]=='-'))
       {
          for(int j=0;j<unasize;j++)
          {
             if(!strcmp(unary[j],tmp))
             {
               int q;
               for(q=i+1;isNum(in[q+1]) && in[q+1]!='-';q++);
               float o1=str2Float(in,i+1,q);
               float result=uoperation(o1,j);
               char* str = new char[30];
               sprintf(str, "%.2f", result );
               int strsize=strlen(str);
               int start=i+1-strlen(unary[j]);
               size=strlen(in);
               int end;
               for(end=start+strlen(unary[j]);isNum(in[end+1]) && in[end+1]!='-';end++);
               for(int m=start;m<size;m++)
               in[m]=in[end+1+m-start];
               size=strlen(in);

               for(int m=start;m<start+strsize;m++)
               {
                for(int n=size;n>m;n--)
                in[n]=in[n-1];

                in[m]=str[m-start];
                size++;
                in[size]='\0';
               }
               break;

              }
        }
        count=0;
     }
  }
}

float eval(char in[100])
{
    char ch;
    int size=strlen(in);
    for(int i=0;i<size;i++)
    {
      if(in[i]=='-' && in[i+1]=='-')
      {
         in[i]='+';
         for(int j=i+1;j<=size;j++)
         in[j]=in[j+1];
         i--;
         size--;
      }
    }
   size=strlen(in);
   solveUnary(in,size);
   char pref[4]={'^','/','*','+'};
   for(int i=0;i<size;i++)
   {
     if(in[i]=='-' && isNum(in[i-1]) && (in[i-1]<97 || in[i-1]>122 || in[i-1]=='x'))
     {
      for(int j=size;j>i;j--)
      in[j]=in[j-1];
      in[i]='+';
      size++;
      i++;
      in[size]='\0';
     }
   }
   int noOpr=0,noOpd=0;
   char operators[100][2];
   int start=-1,end=-1,mode=-1;
   float opd[100];
   for(int i=0;i<size;i++)
   {
      if(isNum(in[i]))
      {
       if(start==-1)
       start=i,mode=0;
       if(!isNum(in[i+1]) && mode==0)
       {
         end=i;
         opd[noOpd++]=str2Float(in,start,end);
         mode=start=end=-1;
       }
      }else
      {
         operators[noOpr][0]=in[i];
         operators[noOpr++][1]=noOpr-1;}
      }
      for(int i=0;i<4;i++)
      {
         for(int j=0;j<noOpr;j++)
         if(operators[j][0]==pref[i])
         {
            float *o1,*o2;
            int flag=1;
            int t=0,tmp;
            while(flag)
            {
                if(t==operators[j][1]+2)
                {
                   opd[t-1]=boperation(opd[t-1],opd[t],pref[i]);
                   for(int w=t;w<noOpd-1;w++)
                   opd[w]=opd[w+1];
                   for(int w=j+1;w<noOpr;w++)
                   operators[w][1]--;
                   noOpd--;

                   flag=0;
                 }
                 t++;
            }
         }
     }
     return opd[0];
}

void toPost(int start,int end)
{
    int start2=-1,end2=-1;
    int count=0;
    for(int i=start+1;i<end;i++)
    {
        if(expr[i]=='(')
        {start2=i;count++;
        break;}
    }

    if(start2!=-1)
    {
        for(int i=start2+1;i<end;i++)
        {
            if(expr[i]=='(')
            count++;
            if(expr[i]==')')
            {
                 count--;
                 if(count==0)
                 {
                   end2=i;
                   break;
                 }
            }
        }
    }

    if(start2!=-1 && end2!=-1)
    toPost(start2,end2);
    if(start2==-1 && end2==-1)
    {
       char subpost[100];
       char subin[100];
       int subsize=end-start-1;
       for(int i=start+1;i<end;i++)
       subin[i-start-1]=expr[i];
       subin[end-start-1]='\0';
       char* str = new char[30];
       float x=eval(subin);
       sprintf(str, "%.2f", x );
       int strsize=strlen(str);
       int size=strlen(expr);
       for(int i=start;i<size;i++)
       expr[i]=expr[end+1+i-start];
       size=strlen(expr);
       for(int i=start;i<start+strsize;i++)
       {
          for(int j=size;j>i;j--)
          expr[j]=expr[j-1];

          expr[i]=str[i-start];
          size++;
       }
       expr[size]='\0';
    }

}

float evalu(char exp[100],float x)
{
  var=x;
  strcpy(expr,exp);
  while(expr[0]=='(')
  toPost(0,strlen(expr)-1);
  return str2Float(expr,0,strlen(expr)-1);
}

int main()
{
    char expression[100];
    cout<<"ENTER A VALID EXPRESSION TO EVALUATE -> ";
    cin>>expression;
    int size=strlen(expression);
    for(int i=size;i>0;i--)
    expression[i]=expression[i-1];
    expression[0]='(';
    expression[++size]=')';
    expression[++size]='\0';
    cout<<evalu(expression,0);
    return 0;
}
```

Features -
*supports integers and floats.
*operators and functions supported - +,-,*,/,^,sin(),cos(),other trigo functions,mod(),log(),floor(),ceil().
adding new functions wont be a big deal.
*supports brackets. like 3*(4+11)

known bug
*wrong result in few cases when the expression has a term like ....- f(..)....
where *f* is a unary function like sin(), cos(), log, etc...

unknown bugs
* i guess many which i havent found because i made it quite in a hurry. i need help of you guyz to recognize them.

eg. lets try the same infix expression used by NEURON.
if i give the expression (2+3)*(4/5)+(6^7)/8
the output will be 34996.
another example
(sin(3.22))^2+(cos(3.22))^2
will have the output 1.01 (come on!! its close to 1!!)

i will tweak and improve this as soon as my boards are over.


----------



## Neuron (Mar 28, 2011)

*Re: Post ur C/C++ Programs Here*

^^Good job.I can help.But will take some time 

BTW I noticed that google search in not producing all the available results.Even if i search for something like
'postfix converter' doesn't show the one i posted.Why is that?It would be very helpful if this is fixed.


----------



## nims11 (Mar 28, 2011)

*Re: Post ur C/C++ Programs Here*

^^ since you added this just a day ago, it would take some time before google bots update their indexes...

i will add comments to the code after my boards and engg entrances so that i can get help on improving the code...


----------



## Neuron (Mar 29, 2011)

*Re: Post ur C/C++ Programs Here*

Okay ,a file encryptor and decryptor.


```
#include<conio.h>
#include<stdio.h>
#include<string.h>

void main() {

	FILE *fs,*ft;
	char c=0,n1[89],n2[89],pass[20],pass1[20],p,n3[89],ext[7];
	int passlen,i,skp=0,nlen,tflg=0,slen,k,j=0,l;
	while(1) {
		i=0;
		printf("\n1.Encrypt\t2.Decrypt\t3.Exit\n>>>");
		c=getch();
		switch(c) {
			case '1': 
				printf("Enter the name of the source file>>>");
				scanf("%s",n1);
				strcpy(n2,n1);
				strcat(n2,".ncrpt");
				slen=strlen(n1);
				if(n1[slen-4]=='.'&&n1[slen-3]=='t'&&n1[slen-2]=='x'&&n1[slen-1]=='t')
					tflg=1;
				else tflg=0;

				fs=fopen(n1,"rb");
	
				if(fs==NULL) {
					puts("Unable to open the source file");
					break;
				}
				printf("Enter the password>>>");
				while((p=getch())&&p!=13) {
					pass[i]=p;
					i++;
				}
				pass[i]='\0';
				printf("\nConfirm password>>>");
				i=0;
				while((p=getch())&&p!=13) {
					pass1[i]=p;
					i++;
				}
				pass1[i]='\0';
				if(!strcmp(pass,pass1)) {

					printf("\n\nEncrypting...\n");
					passlen=strlen(pass);
					ft=fopen(n2,"wb");
					if(ft==NULL) {
						puts("Unable to open the destination file");
						break;
					}
					
					i=0;
					if(!feof(fs))
					do 	{
						if(tflg==1) {
							c=fgetc(fs);
							fputc(c+pass[i],ft);
							i++;
							if(i==passlen)
								i=0;
						}
						else if(skp<180) {
							c=fgetc(fs);
							fputc(c,ft);
							skp++;
						}
						else {
							c=fgetc(fs);
							fputc(c+pass[i],ft);
							i++;
							if(i==passlen)
								i=0;
						}
						if(feof(fs))
							break;
					} while(!feof(fs));
				}
				else	{
					printf("\nPassword Confirmation failed");
					break;
				}
				skp=0;
				printf("\nDone!!!\n");
				printf("\n\nThe encrypted file is <<<%s",n2);
				fclose(fs);
				fclose(ft);
				getch();
				break;
			case '2':
				printf("\nEnter the name of the file to be decrypted>>>");
				scanf("%s",n1);
				nlen=strlen(n1);
				if(n1[nlen-6]!='.') {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-5]!='n')  {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-4]!='c')  {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-3]!='r') {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-2]!='p') {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-1]!='t') {
					printf("\nCannot decrypt\n");
					break;
				}
				if(n1[nlen-10]=='.'&&n1[nlen-9]=='t'&&n1[nlen-8]=='x'&&n1[nlen-7]=='t')
					tflg=1;
				printf("\nEnter the password>>>");
				while((p=getch())&&p!=13) {
					pass[i]=p;
					i++;
				}
				pass[i]='\0';
				printf("\nConfirm password>>>");
				i=0;
				while((p=getch())&&p!=13) {
					pass1[i]=p;
					i++;
				}
				pass1[i]='\0';
				passlen=strlen(pass);

				if(!strcmp(pass,pass1)) {
					printf("\n\nDecrypting...\n");

					for(i=0;i<nlen-6;i++)
						n2[i]=n1[i];
					n2[i]='\0';
					for(i=nlen-7,j=0;n2[i]!='.';i--,j++)
						ext[j]=n2[i];
					l=strlen(n2);
					
					ext[j]='\0';
					n2[l-strlen(ext)-1]='_';
					n2[l-strlen(ext)]='.';
					for(i=(l-strlen(ext)+1),j--;j>=0;j--,i++)
						n2[i]=ext[j];
					n2[i]='\0';

					

					fs=fopen(n1,"rb");
	
					if(fs==NULL) {
						puts("Unable to open the source file");
						break;
					}

					ft=fopen(n2,"wb");
					if(ft==NULL) {
						puts("Unable to open the destination file");
						break;
					}
					i=0;

					if(!feof(fs))	
					do 	{
						if(tflg==1) {
							c=fgetc(fs);
							if(!feof(fs))
							fputc(c-pass[i],ft);
							i++;
							if(i==passlen)
								i=0;
						}
						else if(skp<180) {
							c=fgetc(fs);
							fputc(c,ft);
							skp++;
						}
					    else {
							c=fgetc(fs);
							fputc(c-pass[i],ft);
							i++;
							if(i==passlen)
								i=0;
						}
					} while(!feof(fs));
					printf("\nDone!!!\n");
					printf("\n\nThe decrypted file is>>%s",n2);
				
				}
				else {
					printf("\nPassword confirmation failed");
					break;
				}
				fclose(fs);
				fclose(ft);
	
				break;

				case '3':
					exit(0);
				default:
					printf("\nInvalid choice\n");
					break;
			}
	}
}
```

In Vista or Win7 run as admin.
File path format eg: *c:/abc.exe*
No spaces allowed in path.eg: *c:/Program Files/abc.exe* is invalid.


----------



## Neuron (Apr 1, 2011)

*Re: Post ur C/C++ Programs Here*



nims11 said:


> (sin(3.22))^2+(cos(3.22))^2
> will have the output 1.01 (come on!! its close to 1!!)



Fixed a simple but major bug.The inputs of trigonometric functions must be in radians.So to get the correct answer for cos(90 degrees) you will have pass cos(90*3.14/180) as the argument.Replace 

```
float uoperation(float o1,int o)
{
      switch(o)
      {
               case 0: return sin(o1);
               case 1: return cos(o1);
               case 2: return tan(o1);
               case 3: return 1/tan(o1);
               case 4: return 1/cos(o1);
               case 5: return 1/sin(o1);
               case 6: return mod(o1);
               case 7: if(o1>0)
               return log(o1);
               else
               return 1000;
               case 8: return floor(o1);
               case 9: return ceil(o1);
      }
}
```
with


```
float uoperation(float o1,int o)
{
      switch(o)
      {
               case 0: return sin(o1*3.14/180);
               case 1: return cos(o1*3.14/180);
               case 2: return tan(o1*3.14/180);
               case 3: return 1/tan(o1*3.14/180);
               case 4: return 1/cos(o1*3.14/180);
               case 5: return 1/sin(o1*3.14/180);
               case 6: return mod(o1*3.14/180);
               case 7: if(o1>0)
               return log(o1);
               else
               return 1000;
               case 8: return floor(o1);
               case 9: return ceil(o1);
      }
}
```

Now check the output.


----------



## nims11 (Apr 2, 2011)

*Re: Post ur C/C++ Programs Here*

IMO adding a separate function for trigonometric functions taking argument in degree will be good as in many cases, arguments in radians would be required(lyk in plotting a trig func with another function). What about adding new functions by prefixing the trig functions with a 'd' indicating that it takes argument in degree?


----------



## Garbage (Apr 2, 2011)

*Re: Post ur C/C++ Programs Here*

Couldn't resist posting this link here : visual c++ - Why is this program erroneously rejected by three C++ compilers? - Stack Overflow


----------



## The Conqueror (Apr 2, 2011)

*Re: Post ur C/C++ Programs Here*

Anyone for this problem?


The Conqueror said:


> Can you solve this problem?
> 
> Most mobile phones have their own private dictionary of words to allow users to type messages
> quicker. On a typical phone, each number key is assigned a subset of the alphabet
> ...


----------



## nims11 (Apr 3, 2011)

*Re: Post ur C/C++ Programs Here*

Can it be done using this simple method?-
input thw dictionary content. Convert and store them to their nmbr representation on keypad. Output the number with most occurances.


----------



## Neuron (Apr 6, 2011)

*Re: Post ur C/C++ Programs Here*



nims11 said:


> Can it be done using this simple method?-
> input thw dictionary content. Convert and store them to their nmbr representation on keypad. Output the number with most occurances.



That's exactly how it's supposed to be done I guess.

Like this,
a t-----on-----g oo d-----no    
2 8-----66-----4 66 3-----66

66 appears thrice in words

a t-----o n-----g oo d-----n o-----h om e-----g on e
2 8-----6 6-----4 66 3-----6 6-----4 66 3-----4 66 3


66 appears 4 times,but since '4663' has 4 digits and 3 appearances.4663 is selected.Maybe 4*3 > 2*4 logic can be used.


----------



## nims11 (Apr 6, 2011)

*Re: Post ur C/C++ Programs Here*



Neuron said:


> That's exactly how it's supposed to be done I guess.
> 
> Like this,
> a t-----on-----g oo d-----no
> ...



why are you counting 66 three tyms? shouldnt it be just two according to the question?


----------



## Neuron (Apr 7, 2011)

*Re: Post ur C/C++ Programs Here*

^^You are right.I was overthinking.So the solution is a lot more simple.


----------



## The Conqueror (Apr 12, 2011)

Anyone for the source code for that problem[Dictionary] ? Need it to prepare for olympiad. Which books should I refer to gain insight on these algorithms and logic/?


----------



## nims11 (Apr 12, 2011)

^^ zonal computing olympiad?


----------



## arpanmukherjee1 (Apr 12, 2011)

planning algorithms

found this very useful, but very high level topics, not for beginners


----------



## The Conqueror (Apr 13, 2011)

nims11 said:


> ^^ zonal computing olympiad?



Yes. How to prepare for that?



arpanmukherjee1 said:


> planning algorithms
> 
> found this very useful, but very high level topics, not for beginners


Thanks.


----------



## nims11 (Apr 13, 2011)

The Conqueror said:


> Yes. How to prepare for that?



look, there will be 2 questions. one will be easy and you will be easily able to create an algo for it.
the other one is usually tough and you will need to apply some popular algo. it will seem difficult as we r not taught these algos in schools. it usually gives a problem where knapsack and dynamic programming is applicable.
only those who solve both problems are selected(as i wasnt selected in two ZCOs where i had solved only one problem as i wasnt aware of knapsack algo).

the MIT OCW has a good lecture on knapsack problems and application of dynamic programming on such probs.
also there are many tutorials for it.

i also suggest you to learn "dijkstra algorithm"(for shortest path problems) from somewhere(i cant find the page from which i learnt it, so google it)


----------



## Neuron (Apr 13, 2011)

nims11 said:


> i also suggest you to learn "dijkstra algorithm"(for shortest path problems) from somewhere(*i cant find the page from which i learnt it*, so google it)



wikipedia?


----------



## nims11 (Apr 13, 2011)

^^ nah.. it was some tutorial which took some cities as example which were showed as some colored circles with links between them. looks like a typical dijkstra algorithm tutorial but it explained really well.


----------



## mohityadavx (Apr 13, 2011)

Hi!

I have made a calculator but i am not able to debug it as it is not accepting the password i have set for it. Please help me out.

```
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<string.h>

int addition(int x ,int y)
{
int d;
d=x+y;
return(d);
}


int subtraction(int x ,int y)
{
int d;
if(x>y)
d=x-y;
else
y-x;
return(d);
}


float division(float x ,float y)
{
float d;
d=x/y;
return(d);
}


int multiplication(int x ,int y)
{
int d;
d=x*y;
return(d);
}


float sqrt(float x)
{
float d;
d=sqrt(x);
return(d);
}

float nlog(float x)
{
float d;
d=log(x);
return(d);
}

float tlog(float x)
{
float d;
d=log10(x);
return(d);
}

float antilog(float x)
{
float d,e; int z = 10;
e=log(x);

d=pow(z,e);
return(d);
}

int fact(int x)
{
int i;
for(i=1;i<=x;i++)
x=x*i;
return(x);
}

float sin(float x)
{
float d;
d= sin(x);
return(d);
}

float cos(float x)
{
float d;
d= cos(x);
return(d);
}

float tan(float x)
{
float d;
d= tan(x);
return(d);
}

float asin(float x)
{
float d;
d= asin(x);
return(d);
}

float acos(float x)
{
float d;
d= acos(x);
return(d);
}

float atan(float x)
{
float d;
d= atan(x);
return(d);
}


void main()
{
textcolor(RED);
clrscr();
int a,b,ch,i=0; char pass[10]; 
float q,w;
Again:

cout<<"This file is password protected"<<endl;
cout<<endl<<"Enter password"<<endl;

while((pass[i]=getch())!='\r')
{
cout<<"*";
i++;
}

clrscr();

if(strcmp(pass,"mohit")==0)
{
cout<<'/t'<<'/t'<<'/t'<<"MAIN MENU"<<endl<<endl;

cout<<endl<<"1 Standard Calculator"<<endl;
cout<<endl<<"2 Scientific calculator"<<endl;


cout<<endl<<"Enter your choice (1 or 2)"<<endl;
cin>>ch;

if(ch==1)
{
int ch1,k;
float k1;

cout<<"1 Addition"<<endl;
cout<<"2 Subtraction"<<endl;
cout<<"3 Divison"<<endl;
cout<<"4 Multiplication"<<endl;
cout<<"5 Square Root"<<endl;

cout<<endl<<"Enter your choice"<<endl;
cin>>ch1;

switch(ch1)
{
int k;
case 1:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
k=addition(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<k;
break;

case 2:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
k=subtraction(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<k;
break;


case 3:
cout<<endl<<"Enter first number"<<endl;
cin>>q;
cout<<endl<<"Enter second number"<<endl;
cin>>w;
k1=division(q,w);
cout<<endl<<"Your Solution is -"<<'/t'<<k1;
break;

case 4:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
k=multiplication(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<k;
break;

case5:
cout<<endl<<"Enter number"<<endl;
cin>>q;
k1=sqrt(q);
cout<<endl<<"Your Solution is -"<<'/t'<<k1;
break;
}
}

if(ch==2)
{
int ch2,l;
cout<<"1 Addition"<<endl;
cout<<"2 Subtraction ( |x-y|)"<<endl;
cout<<"3 Divison"<<endl;
cout<<"4 Multiplication"<<endl;
cout<<"5 Square Root"<<endl;
cout<<"6 Natural Logaritham"<<endl;
cout<<"7 Logaritham (Base 10)"<<endl;
cout<<"8 Antilogaritham (Base 10)"<<endl;
cout<<"9 Factorial"<<endl;
cout<<"10 Sine"<<endl;
cout<<"11 Cosine"<<endl;
cout<<"12 Tangent"<<endl;
cout<<"13 Arc Sine"<<endl;
cout<<"14 Arc Cosine"<<endl;
cout<<"15 Arc Tangent"<<endl;


cout<<endl<<"Enter your choice"<<endl;
cin>>ch2;

switch(ch2)
{
int l;
float l1;

case 1:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
l=addition(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<l;
break;

case 2:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
l=subtraction(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<l;
break;


case 3:
cout<<endl<<"Enter first number"<<endl;
cin>>q;
cout<<endl<<"Enter second number"<<endl;
cin>>w;
l1=division(q,w);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;


case 4:
cout<<endl<<"Enter first number"<<endl;
cin>>a;
cout<<endl<<"Enter second number"<<endl;
cin>>b;
l=multiplication(a,b);
cout<<endl<<"Your Solution is -"<<'/t'<<l;
break;


case 5:
cout<<endl<<"Enter number"<<endl;
cin>>a;
l1=sqrt(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 6:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=nlog(a);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 7:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=tlog(a);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 8:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=antilog(a);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 9:
cout<<endl<<"Enter number"<<endl;
cin>>a;
l=fact(a);
cout<<endl<<"Your Solution is -"<<'/t'<<l;
break;

case 10:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=sin(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 11:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=cos(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 12:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=tan(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;
 
case 13:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=asin(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 14:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=acos(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;

case 15:
cout<<endl<<"Enter number"<<endl;
cin>>q;
l1=atan(q);
cout<<endl<<"Your Solution is -"<<'/t'<<l1;
break;
}
}
}

else
{
cout<<"Access Denied! Incorrect Password"<<endl;
goto Again;
}
getch();
}
```


----------



## arpanmukherjee1 (Apr 13, 2011)

```
........
cout<<"*";
i++;
}
[B]pass[i]='\0';[/B]

if(strcmp(pass,"mohit")==0)
......
```

add the above line 

also DO NOT use GOTO


----------



## mohityadavx (Apr 13, 2011)

arpanmukherjee1 said:


> ```
> ........
> cout<<"*";
> i++;
> ...



thanx i cant understood why are u making the  i element as null character and its still not working


----------



## nims11 (Apr 13, 2011)

> float division(float x ,float y)
> {
> float d;
> d=x/y;
> ...


add a condition to check if y!=0 to avoid runtime error.


----------



## mohityadavx (Apr 13, 2011)

nims11 said:


> add a condition to check if y!=0 to avoid runtime error.



thanx there would be many more such error and bug once i am able to get through password problem


----------



## The Conqueror (Apr 13, 2011)

nims11 said:


> look, there will be 2 questions. one will be easy and you will be easily able to create an algo for it.
> the other one is usually tough and you will need to apply some popular algo. it will seem difficult as we r not taught these algos in schools. it usually gives a problem where knapsack and dynamic programming is applicable.
> only those who solve both problems are selected(as i wasnt selected in two ZCOs where i had solved only one problem as i wasnt aware of knapsack algo).
> 
> ...


So If I learn those basic algorithms and data structures in say- in the month of May. My basics about arrays,pointers etc are perfect. Can I expect something good that I will be able to attempt it well at ZCO?


----------



## Neuron (Apr 13, 2011)

*@mohityadavx* : Dude sorry to say but your program contain plenty of errors,like you are redefining the library functions like sin ,cos etc.It appears like you are low on the basics.Start learning from a good text book.I'd recommend *C++ ,The Complete Reference by Herbert Schildt*.It contains everything you need to know.Either buy one or search your school/college library.Good Luck


----------



## mohityadavx (Apr 13, 2011)

Neuron said:


> *@mohityadavx* : Dude sorry to say but your program contain plenty of errors,like you are redefining the library functions like sin ,cos etc.It appears like you are low on the basics.Start learning from a good text book.I'd recommend *C++ ,The Complete Reference by Herbert Schildt*.It contains everything you need to know.Either buy one or search your school/college library.Good Luck



ya u r right about the bugs 

its not like that neuron this program would be now modified for complex function by my friend ( i am just preparing the basic outline)  like square(sinx) + sin( square x) and i don't want to clutter main() 

what about password bug


----------



## Neuron (Apr 13, 2011)

Like arpanmukherjee1 said you will have to add the *pass='\0'*_ statement and it should work perfectly._


----------



## mohityadavx (Apr 13, 2011)

Neuron said:


> Like arpanmukherjee1 said you will have to add the *pass='\0'*_ statement and it should work perfectly._


_

like i said before its still not working_


----------



## Liverpool_fan (Apr 13, 2011)

Why are you checking for carriage return '\r' for checking newline? Try checking for newline with '\n'.


----------



## Neuron (Apr 13, 2011)

@Liverpool_fan:'\r' works fine.



mohityadavx said:


> like i said before its still not working


It must, because that block of code is faultless and is running perfectly on my compiler.
Did you try running that piece of code alone?What error did you get? or why are you saying that it's not working?


----------



## mohityadavx (Apr 13, 2011)

i m trying to say that when i put this piece of code it says password incorrect access denied


----------



## Neuron (Apr 13, 2011)

Run this and post your output.

```
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<math.h>

void main()
{
char pass[10];
int i=0;
cout<<"Enter password"<<endl;
while((pass[i]=getch())!='\r')
{
cout<<"*";
i++;
}
pass[i]='\0';
cout<<endl;
if(strcmp(pass,"mohit")==0)
cout<<"Password Comparison Successfull"<<endl;
else
cout<<"Failed Password is "<<pass<<endl;

getch();
}
```


----------



## mohityadavx (Apr 13, 2011)

Neuron said:


> Run this and post your output.
> 
> ```
> #include<iostream.h>
> ...


 
thanx neuron i am extremely sorry for my stupidity but i had caps turned on while typing the password and didn't noticed it.

anyway can u tell me something why doesn't string take the last character as null by default it does s when we use cin command etc


----------



## Liverpool_fan (Apr 13, 2011)

Why would it take the last character as '\0' when you are coding the input manually character by character using getch?

BTW be informed that the code you have written is largely out of date, non-portable and does not conform to ANSI standards. If you are studying C++ independently, you are advised to learn ANSI C++ and use a modern compiler rather than the antiquated junk Turbo C++.


----------



## arpanmukherjee1 (Apr 13, 2011)

^^^+1.   could have said it better myself.

*@mohityadavx* use GCC or DevC++. majority of the errors and warnings will be pointed by the compiler.

also treat warnings as errors, that is a good practice


----------



## mohityadavx (Apr 14, 2011)

Neuron said:


> *@mohityadavx* : Dude sorry to say but your program contain plenty of errors,like you are redefining the library functions like sin ,cos etc.It appears like you are low on the basics.Start learning from a good text book.I'd recommend *C++ ,The Complete Reference by Herbert Schildt*.It contains everything you need to know.Either buy one or search your school/college library.Good Luck



Thanx for the advice never knew sumita arora was that bad that most of you are simply rejecting the code !!!! I will use Dev C++ as i like its layout more then GCC!!!


----------



## nims11 (Apr 14, 2011)

mohityadavx said:


> Thanx for the advice never knew sumita arora was that bad that most of you are simply rejecting the code !!!! I will use Dev C++ as i like its layout more then GCC!!!



sumita arora is not recommended for anyone who wants to do programming. 

btw Dev-C++ is an IDE and GCC is a compiler.


----------



## dead.night7 (Apr 27, 2011)

*Re: Post ur C/C++ Programs Here*



Yamaraj said:


> scanf() is a C input function, which is considered unsafe except for formatted data. .




Prove this yaar


----------



## Liverpool_fan (Apr 27, 2011)

*Re: Post ur C/C++ Programs Here*



dead.night7 said:


> Prove this yaar


Things to Avoid in C/C++ -- scanf, Part 5 - GIDNetwork


----------



## nims11 (May 2, 2011)

typing test, pretty lame, but i like it! 


```
//TYPING TEST
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <fstream.h>
#include <string.h>
using namespace std;
void fileChk(char filename[10])
{
    ifstream fin(filename);
    if(!fin.is_open())
    {
       ofstream fout("scores.dat");
       fout<<0<<endl;
       fout.close();
    }
    fin.close();
}
void writeScores(double score)
{
       fileChk("scores.dat");
       ifstream fin("scores.dat");
     int n,i;
     char names[10][20];
     double scores[10];
     fin>>n;
     for(i=0;i<n;i++)
     {
                     fin>>names[i];
                     fin>>scores[i];
     }
     if(n==0)
     {
             n=1;
             fin.close();
     remove("scores.dat");
     ofstream fout("scores.dat");
     fout<<1;
     cout<<"\nCongratulations!!!, You made it to the HALL OF FAME\n\n";
         char name[20];
         cout<<"Enter you name - ";
         cin>>name;
     fout<<name<<" "<<score<<endl;
     }else{
     if(n<10)
     n++;
     fin.close();
     remove("scores.dat");
     ofstream fout("scores.dat");
     fout<<n<<endl;
     int flag=1;
     for(i=0;i<n;i++)
     {
       if((scores[i]>score || (i==n-1 && scores[n-1]>score)) && flag==1)
       {
         flag=0;
         n=n-1;
         cout<<"\nCongratulations!!!, You made it to the HALL OF FAME\n\n";
         char name[20];
         cout<<"Enter you name - ";
         cin>>name;
         fout<<name<<" "<<score<<endl;
       }
       fout<<names[i]<<" "<<scores[i]<<endl;
     }
     fout.close();
     }
}
void dispScores()
{
     system("cls");
     ifstream fin("scores.dat");
     int n,i;
     fin>>n;
     cout<<"name \ttime\n\n";
     for(i=0;i<n;i++)
     {
                     char name[20];
                     fin>>name;
                     double score;
                     fin>>score;
                     cout<<name<<"\t"<<score<<endl;
     }
}
int main()
{
  cout<<"TYPING SPEED TESTER BY NIMS13\nPress any key to continue....";
  getch();
  system("cls");
  char c;
  clock_t start, end;
  char str[100]="the quick brown fox jumps over the lazy dog";
  int len=strlen(str),i,errors=0;
  cout<<"Hello!! ,Type the following as fast as you can\n(The time will start when you type the first letter and will automatically end when you complete the sentence.\nDON'T PRESS ENTER WHEN YOU FINISH WRITING) -\n\nthe quick brown fox jumps over the lazy dog\n\n";
  int flag=1;
  while(flag)
  {
  c=getch();
  if(tolower(c)==str[0])
  {
                        cout<<c;
                        flag=0;
  start = clock();
}else
errors++;
}
  for(i=1;i<len;i++)
  {
     int flag=1;
     while(flag)
     {
     c=getch();
     if(tolower(c)==str[i])
     {
     cout<<c;
     flag=0;
     }else
errors++;
     }
  }
  end = clock();
  double duration=(double(end-start))/((double)CLOCKS_PER_SEC);
  system("cls");
  for(i=0;i<10;i++)
  {
     cout<<"Processing Data";
     cout<<"/";
     for(int j=0;j<10000000;j++);
     system("cls");
     cout<<"Processing Data";
     cout<<"-";
    for(int j=0;j<10000000;j++);
    system("cls");
    cout<<"Processing Data";
     cout<<"\\";
     for(int j=0;j<10000000;j++);
     system("cls");
     cout<<"Processing Data";
     cout<<"|";
     for(int j=0;j<10000000;j++);
     system("cls");
  }
  cout<<"\nTotal Time - "<<duration<<" secs!!\n";
  cout<<"\nMistakes made- "<<errors;
  for(long j=0;j<100000000;j++);
  cout<<"\nPress Any Key to See the Hall of Fame....";
  getch();
  system("cls");
  writeScores(duration);
  dispScores();
  cin>>i;
  return 0;
}
```

compiled exe


----------



## Neuron (May 7, 2011)

^^ lol,nice program.

Finally learning some Windows programming.This one is nothing.Just a line drawing program.
But you guys can expect some games from me pretty soon .


```
#include<windows.h>
#include<string>
#include<vector>

using namespace std;



HWND hwnd;
MSG msg;
WNDCLASSEX wndclass;
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM );
PAINTSTRUCT ps;
HDC hdc;


int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{

	LOGBRUSH lb;
	lb.lbStyle=BS_SOLID;
	lb.lbColor=RGB(125,123,123);
	HBRUSH BlueBrush=CreateBrushIndirect(&lb);

	wndclass.cbClsExtra=0;
	wndclass.cbSize=sizeof(wndclass);
	wndclass.cbWndExtra=0;
	wndclass.hbrBackground=(HBRUSH)BlueBrush;
	wndclass.hCursor=LoadCursor(0,IDC_ARROW);
	wndclass.hIcon=LoadIcon(0,IDI_APPLICATION);
	wndclass.hIconSm=LoadIcon(0,IDI_APPLICATION);
	wndclass.hInstance=hInstance;
	wndclass.lpfnWndProc=WndProc;
	wndclass.lpszClassName="Wind";
	wndclass.lpszMenuName=0;
	wndclass.style=CS_HREDRAW|CS_VREDRAW;
	

	RegisterClassEx(&wndclass);


	hwnd=CreateWindow("Wind","Windo",WS_HSCROLL|WS_VSCROLL,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL);

	ShowWindow(hwnd,nShowCmd);
	UpdateWindow(hwnd);

	ZeroMemory(&msg,sizeof(msg));

	while(GetMessage(&msg,0,0,0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

}




struct tLine {
	POINT P0;
	POINT P1;
};

vector<tLine> aLines;
tLine tLines;
bool mousedown=true;





LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM Wparam,LPARAM Lparam) 
{
	switch(msg) {

		case WM_LBUTTONDOWN:
			tLines.P0.x=LOWORD(Lparam);
			tLines.P0.y=HIWORD(Lparam);
			SetCapture(hwnd);
			mousedown = true;			
			return 0;
		
		case WM_LBUTTONUP:
			ReleaseCapture();
			mousedown=false;
			tLines.P1.x=LOWORD(Lparam);
			tLines.P1.y=HIWORD(Lparam);
			aLines.push_back(tLines);
			return 0;

		case WM_MOUSEMOVE:
			if(mousedown) {			
				InvalidateRect(hwnd, 0, true);
				hdc=BeginPaint(hwnd,&ps);
				MoveToEx(hdc,tLines.P0.x,tLines.P0.y,0);
				LineTo(hdc,LOWORD(Lparam),HIWORD(Lparam));			
				EndPaint(hwnd,&ps);			
			}
				
			for(int i=0;i<aLines.size();i++) {
				InvalidateRect(hwnd, 0, false);
				hdc=BeginPaint(hwnd,&ps);
				MoveToEx(hdc,aLines[i].P0.x,aLines[i].P0.y,0);
				LineTo(hdc,aLines[i].P1.x,aLines[i].P1.y);
				EndPaint(hwnd,&ps);								
			}			
			return 0;

		case WM_RBUTTONDOWN:
			hdc=BeginPaint(hwnd,&ps);
			InvalidateRect(hwnd,0,true);
			aLines.clear();
			EndPaint(hwnd,&ps);
			return 0;

		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
		case WM_KEYDOWN:
			if(Wparam==VK_ESCAPE) {
				if(MessageBox(0,"Are you sure you want to exit?","Message",MB_YESNO)==IDYES){
					PostQuitMessage(0);
					return 0;
				}
			}
			break;
	}
	return DefWindowProc(hwnd,msg,Wparam,Lparam);

}
```


----------



## Neuron (May 8, 2011)

Here is an updated version of my game which I posted earlier.Fixed some bugs.This is the compiled version.
You can get the code from post #635 .

Resumable Link.
DarkPong1.1

Rapidshare.
DarkPong1.1


----------



## himanshu1114 (Jun 15, 2011)

*Program to print R character in C.Is their anyone to give answer.*

I'm getting problem while making R alphabet with * program.
Plz give any solution.


----------



## nims11 (Jun 16, 2011)

*Re: Program to print R character in C.Is their anyone to give answer.*



himanshu1114 said:


> I'm getting problem while making R alphabet with * program.
> Plz give any solution.



its easy and basic coordinate geometry. apply the equation of circle to draw the upper half of "R" and the rest part is simple.

here- *codepad.org/lcoB15iZ
i wrote it for you. figure out how i used the circle equation. to increase the size of "R" drawn in the program,just increase the value of variable "upper".


----------



## Neo (Jun 23, 2011)

can someone post a 'merge sort' program.
Thanx


----------



## Liverpool_fan (Jun 23, 2011)

royal.tarun said:


> can someone post a 'merge sort' program.
> Thanx



Nope. Unless you post your attempt, then you can be helped otherwise not.


----------



## Ron (Jun 24, 2011)

I m learning DATA STRUCTURE WITH C++...
But dont hv any gud  material...Does anyone know gud sites for learnin DS


----------



## Neo (Jun 24, 2011)

*Program to mutiply two matrices.*



> #include<iostream.h>
> #include<conio.h>
> int main()
> {
> ...


_






			#include<iostream.h>
#include<conio.h>
int main()
{
 int mat1[3][3],mat2[3][3],mat3[3][3];
 /*entering values in the first array*/
 cout<<"enter the numbers of first matrix : "<<endl;
 for(int i=0;i<3;i++)
 {
         for(int j=0;j<3;j++)
         {
         cin>>mat1[j];
         }       
 }        

 /*entering values in the second array*/

 cout<<"enter the numbers of second matrix : "<<endl;

  for(int k=0;k<3;k++)
 {
         for(int l=0;l<3;l++)
         {
         cin>>mat2[k][l];
         }       
 }        

 /*performing multiplication*/
 for(int m=0;m<3;m++)
 {
    for(int n=0;n<3;n++)     
        { 
         mat3[m][n]=0;
           for(int o=0;o<3;o++)
               {
               mat3[m][n]=mat3[m][n]+(mat1[m][o]*mat2[o][n]);    
               }
        }
 } 

 /*printing the result*/

  cout<<"product of the matrices is : "<<endl;

  for(int s=0;s<3;s++)
 {
         for(int t=0;t<3;t++)
         {
         cout<<mat3[t]<<"         ";
         }
         cout<<endl;     
 }



 getch();
}


Click to expand...



_


----------



## Vyom (Jun 24, 2011)

14+ YouTube Playlists To Watch & Learn Computer Programming Quickly
*Including C++. * Might be helpful for learners here.

*14+ YouTube Playlists To Watch & Learn Computer Programming Quickly*


----------



## vickybat (Aug 14, 2011)

Guys i have a simple query: Whilst using* linked lists*, how to display char strings?

I mean i've written the following code and it displays the last char of each string.


```
#include<iostream>
#include <limits>
#include <string>
using namespace std;
struct emp
{
  char name[5];
  struct emp *next;
};
int main()
{
   emp*start =NULL;
   emp emp1 ,emp2,emp3,emp4,emp5;
   start = &emp1;
   emp1.name[5] = 'llana';
   emp1.next = &emp2;
   emp2.name[5] =  'kim';
   emp2.next = &emp3;
   emp3.name[5] = 'lara';
   emp3.next = &emp4;
   emp4.name[5] =  'alice';
   emp4.next = &emp5;
   emp5.name[5] = 'trish';
   emp5.next = NULL;
   
   for (int i=1;i<=5;i++)
   {
       cout<<"The employee names are:"<< start-> name[5]<<endl;
       start =start->next;
   
     
     }
     cin.ignore();
     cin.get();
   
    return 0;  
}
```

IT GENERATES THE FOLLOWING OUTPUT:

The employee names are : a
The employee names are : m
The employee names are : a
The employee names are : e
The employee names are : h

These are the last characters of the strings. Need to display the full char.


----------



## Liverpool_fan (Aug 14, 2011)

^^ Why are you using name[5] = 'lara', etc.? to save values on the character array string? Since you are coding in C++, I would recommend you to use std::string as the string variable in the class. Also why are you using single quotes for strings? In C/C++ single quotes are for characters, double quotes are for strings.

Something like this. Does this give you the output you desire?


```
#include<iostream>
#include<string>

using namespace std;
struct emp
{
  string name;
  struct emp *next;
};
int main()
{
   emp*start =NULL;
   emp emp1 ,emp2,emp3,emp4,emp5;
   start = &emp1;
   emp1.name = "llana";
   emp1.next = &emp2;
   emp2.name =  "kim";
   emp2.next = &emp3;
   emp3.name = "lara";
   emp3.next = &emp4;
   emp4.name =  "alice";
   emp4.next = &emp5;
   emp5.name = "trish";
   emp5.next = NULL;
   
   for (int i=1;i<=5;i++)
   {
       cout<<"The employee names are:"<< start->name<<endl;
       start =start->next;
   
     
     }
     cin.ignore();
     cin.get();
   
    return 0;  
}
```
EDIT: Added <string>, dependance on compiler-specific is fail.

And if you keen to use C style string "character arrays", then you use the array name just "name" instead of name[5] to assign values. And yeah you'll probably need somethink like strcpy, or the function in STL which does equivalent of creating a string from array of characters (don't remember it) to copy strings to character arrays. Also note you need to allocate atleast the space needed + 1 char memory to store termination character('\0') with a char array in C/C++. Your program here will need at least 6 characters "alice\0", etc.
And there's no need to use so many headers.


----------



## Neuron (Aug 14, 2011)

^^Have to include the "string" header too in the code you posted.


----------



## Liverpool_fan (Aug 14, 2011)

^^I thought that too but it worked regardless
 Ideone.com | Online C++ Compiler & Debugging Tool

Anyway, ideally it should be included.
*www.cplusplus.com/forum/beginner/13356/


----------



## Neuron (Aug 14, 2011)

^^Couldn't compile it on visual studio 2008 express and 2010 pro without the string header.


----------



## Liverpool_fan (Aug 14, 2011)

Yeah relying it to work with just <iostream> is compiler specific (which is fail). Anyway fixed.


----------



## vickybat (Aug 14, 2011)

*@ Liverpool_fan , Neuron*

Thanks a lot guys. Yeah the code worked this time. Silly me. I have really forgotten a lot of basics. Btw i'm from electronics and communication background and i'm brushing up my c++.

Might need more help from you guys.


----------



## vickybat (Aug 26, 2011)

Guys wrote a simple code on determining the maximum and minimum number in an array using class concept in c++.

But the exe is crashing when executed. Here's the code:


```
include <iostream>
using namespace std;

class compare 
{
      int a[10];
       int i;
       int mx;
       int mn;
      
      public:
             void max();
            
};

   void compare::max()
   {
        cout <<"enter the number:"<<endl;
        cin>> a[i];

        mx = a[0];
        mn = a[0];
        
        for (i=0;i<10;i++)
         {
        if (a[i] > mx)
          {
                mx = a[i];
                }
               else if(a[i]< mn)
		{
			mn = a[i];
		}
     }

}


int main()
{
    compare d1;
    d1.max();
    
    
    cout<<"the max number is:"<< mx<<endl;
    cout<<"the min number is:"<<mn <<endl;
    
    cin.ignore();
     cin.get();

    
    return 0;
    
};
```

Need a solution.


----------



## sakumar79 (Aug 26, 2011)

1. The class concept is being used only theoretically here. You are simply putting a procedure into the class and returning the solution...
2. In max procedure, you are inputting a_ but it is not inside a loop...
3. In main procedure, you are outputting mx and mn, but these are variable of the class compare, how can you directly print them...

IMHO, your class should include a public procedure for inputting the data, a private procedure for running the comparison, public procedures to get max and min... Otherwise, there is nothing different between this program and a program without classes...

Arun_


----------



## vickybat (Aug 26, 2011)

^^ Okay buddy thanks for your valuable comments. I finally figured it out:


```
#include<iostream>
using namespace std;

class compare
{
  int a[10];
  int max;
  int min;
  int i;

  public:
  
  void get_data();
  void show_data();
  void compute();
};
  

  void compare::get_data()
  {
    
   for (i=0;i<10;i++)

   {
      cout<<"Enter the numbers in the array:"<<endl;
       cin>>a[i];
    }
}

 void compare::show_data()
{

cout<<"The maximum number is:"<<max<<endl;
cout<<"The minimum number is:"<<min<<endl;
}



void compare::compute()

{


        max = a[0];
        min = a[0];
        
        for (i=0;i<10;i++)
         {
        if (a[i] > max)
          {
                max = a[i];
                }
               else if(a[i]< min)
		{
			min = a[i];
		} 

              }

           }

int main()
{
    compare d1;
    d1.get_data();
    d1.compute();
    d1.show_data();
    
    
    cin.ignore();
     cin.get();

    
    return 0;
    
};
```

Its working.


----------



## sakumar79 (Aug 26, 2011)

Thats much better... 

A small suggestion - have a boolean variable to check if finding max/min is done - this should be set to false initially, again set to false after receiving input data, and set to true after sorting. Now, in show data module, check if this boolean variable is true (to check if max/min is found) and if not, call the comparing module from inside show data module... This way, if someone calls show data module without running the compare module, it will not give error... Also, if the data is changed after comparing is done, it will know that the data is changed and will recheck the maximum/minimum

Further suggestions:
1. If you want, you can set size of i dynamically by asking number of numbers and assigning array size accordingly. You can have a variable for that also if you want...
2. Depending on requirement, comparing module can be made private...

    Do get suggestions from others also... I am personally not a professional programmer though I have more done than 10 years of casual small scale programming

Arun


----------



## mayoorite (Sep 10, 2011)

*Pattern by a beginner*


```
#include<iostream.h>
#include<conio.h>
main()
{

	clrscr();
	int i,j,n;
	char ch,l;
	cout<<"Enter an alphabet:";
	cin>>ch;
	l=ch;
	for(i=0;i<=(l-64) && ch<='z' && ch>='A';i++)
       {        for(n=40;n>i;n--)
		cout<<" ";
		for(j=0,ch='A';j<i;j++,ch++)
		cout<<ch<<" ";
		cout<<endl;
       }

	getch();
}
```
*i51.tinypic.com/ifsrpd.jpg
Please suggest some changes in it to make it more cooler.


----------



## SlashDK (Sep 10, 2011)

*Re: Pattern by a beginner*

What do you mean by make it cooler?


----------



## mayoorite (Sep 10, 2011)

*Re: Pattern by a beginner*

I
mean making it more simpler(code) & adding more different patterns/shape,symbols. ​


----------



## abhijangda (Sep 10, 2011)

*Re: Pattern by a beginner*

one major improvement is to stop using  Turbo C++ and use any latest compiler!!


----------



## Liverpool_fan (Sep 10, 2011)

*Re: Pattern by a beginner*

Merged with the C/C++ Programs thread.


abhijangda said:


> one major improvement is to stop using  Turbo C++ and use any latest compiler!!



This.


----------



## arpanmukherjee1 (Sep 12, 2011)

i am shocked to know even big companies use Turbo C for training purposes, and no emphasis on coding style or C standards at all !!!!!


----------



## Liverpool_fan (Sep 12, 2011)

You'll be even more surprised to find such people here in TDF as well, and they are like "aise hi chalta hai, et al". And they are IT "professionals" apparently.


----------



## nims11 (Sep 12, 2011)

arpanmukherjee1 said:


> i am shocked to know even big companies use Turbo C for training purposes, and no emphasis on coding style or C standards at all !!!!!



Even the biggies!! depressing...


----------



## arpanmukherjee1 (Sep 12, 2011)

^^ yep, even the biggies !!


----------



## Garbage (Sep 12, 2011)

I haven't seen any biggies using TC++ in their trainings. Heck, I haven't seen any biggies training in C / C++.


----------



## somulesnar (Sep 23, 2011)

guys need a little help.. i recently wrote a program to implement the piglatin concept but unfortunately the program doesnt give output... here is the code


```
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void initialize(char[],char[]);
void readinput(char english[]);
int countwords(char english[]);
void convert(int words, char english[], char piglatin[]);
void writeoutput(char piglatin[]);
int main()
{
	char english[80], piglatin[80];
	int words;
	printf("Welcome to the Piglatin Generator\n\n");
	printf("Type \'END\'when finished\n\n");
	do {
		/*process a new line of text*/
		initialize(english, piglatin);
			printf("now before read input");
		readinput(english);
		printf("now after read input");
		/*count the no of words in the line*/
 		  words=countwords(english);
 		/*convert english to piglatin*/
 		printf("now before writeoutput");
		 writeoutput(piglatin);
 		break;
		}
	while(words>=0);
	printf("\naveh aa icena ayda (Have a nice day)\n");
}
/*intialize the character arrays with blank spaces*/
void initialize(char english[],char piglatin[])
{
	int count;
	for(count=0;count<80;++count)
	english[count]=piglatin[count]=' ';
}
/*read one line of English text*/
void readinput(char english[])
{
	int count=0;
	char c;
	while(count < 15)
	{
		c=getchar();
		english[count]=c;
		++count;
	}
	printf("now in read input");
	return;
}
/*scan the english text and determine the number of words*/
int countwords(char english[])
{
	int count, words=1;
	for(count=count<79;++count;)
	if(english[count]==' '&& english[count+1] !=' ')
	++words;
	return(words);
}
/*convert each word into piglatin*/
void convert(int words,char english[],char piglatin[])
{
	int n, count;
	int m1=0;
	int m2;
	/*convert each word*/
	for(n=1;n<=words;++n)
	{
		/*locate the end of the current word*/
		count=m1;
		while(english[count]!=' ')
		m2=count++;
		/*transpoes the first letter and add a*/
		for(count=m1;count<m2;++count)
		piglatin[count+(n-1)]=english[count+1];
		piglatin[m2+(n-1)]=english[m1];
		piglatin[m2+n]='a';
		/*reset the initial maarker*/
		m1=m2+2;
		
	}
	return;
}
/*display the line of text in piglatin*/
void writeoutput(char piglatin[])
{
	int count=0;
	for(count=0;count<80;++count)
	putchar(piglatin[count]);
	printf("\n");
	return;
}
```


i am using turbo c++ compiler right now...... plz need suggestion urgently( program code is in c language so need answers in the same)..
cheers...


----------



## Neuron (Sep 23, 2011)

for making FLAT ATFLAY

1.read the word.
2.determine the number of letters in the word.
3.find the start position of the consonant cluster.
4.copy the words before the cluster to a temporary string.
5.print the output as right side of the cluster start position+temporary string+ay.


----------



## somulesnar (Sep 26, 2011)

@neuron 

Dont really get u buddy sorry but i am a novice......
so plz try helping me by writing code itself..... or pointing my mistakes in my code.....

hey guys here's another simple bubble sort program..........

here the values are given by default u can also code it to enter the values manually.......

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={25,17,31,13,2};
int i,j,temp;
clrscr();
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("The array after sorting is: ");
for(i=0;i<=4;i++)
printf("%d\n",arr_);
getch();
}

cheers...._


----------



## Neuron (Sep 26, 2011)

The major problem is with the convert() function.I don't understand what you are trying to implement .Especially these 2 statements

```
piglatin[count+(n-1)]=english[count+1];
piglatin[m2+(n-1)]=english[m1]
```

Secondly, in the code you posted the convert() function isn't called from the main() function.


----------



## vickybat (Sep 26, 2011)

*@ somulesnar*

I have written a very simple *english(word) to piglatin *converter code in c++. It uses the string concept which i'm still learning.

It simply rotates the input string and concatenates "ay".

For example- *"batman"*

piglatin- *"atmanbay"*



```
[B]# include <iostream>
#include <string>

using namespace std;
 
string str;
 string pstr;
string piglatin( string pstr);

int main()

{
    
    cout<<"enter the string:"<<endl;
    cin>>str;
    cout << " The piglatin form of the input string is:"<<piglatin(str)<<endl;
     cin.ignore();
     cin.get();
    
    return 0;
    
}

string piglatin(string pstr)

{
      string::size_type len=pstr.length();
	  string rstr;
      rstr=pstr.substr(1,len-1)+pstr[0];//[B] [COLOR="Blue"]rotates the string[/COLOR][/B]
      
      pstr = rstr + "ay";
	
       return pstr;
      
      
       
       cin.get();
    cin.ignore();
       
       }[/B]
```


Guys give your expert opinions on it.


----------



## Liverpool_fan (Sep 26, 2011)

Why the cin.get() and cin.ignore() in piglatin()? These statements will have no effect, since control is returned before them.
And let me guess their presence in main() is to trap keyboard to see output? You need a better IDE in that case.
And why are you using global variables in the program? They are certainly not needed.


----------



## Neuron (Sep 26, 2011)

@vickybat:There is a small problem with the piglatin concept you used.It's not like the first letter is brought to the end and an 'ay' is added,but its a consonant cluster that is rotated to the end. ie,scram should produce 'amscray' and not 'cramsay' since the first consonant cluster is 'scr'.


----------



## vickybat (Sep 26, 2011)

Neuron said:


> @vickybat:There is a small problem with the piglatin concept you used.It's not like the first letter is brought to the end and an 'ay' is added,but its a consonant cluster that is rotated to the end. ie,scram should produce 'amscray' and not 'cramsay' since the first consonant cluster is 'scr'.



Yeah but wikipedia gave me this:


> *
> Pig Latin is a language game of alterations played in English. To form the Pig Latin form of an English word the first consonant (or consonant cluster) is moved to the end of the word and an ay is affixed (for example, pig yields ig-pay and computer yields omputer-cay). The object is to conceal the meaning of the words from others not familiar with the rules. The reference to Latin is a deliberate misnomer, as it is simply a form of jargon, used only for its English connotations as a "strange and foreign-sounding language."*



Its doing the same thing that i did. Can you throw some more light on this fact mate?


----------



## Neuron (Sep 26, 2011)

Search the same wikipedia page for the word 'scram'.


----------



## vickybat (Sep 26, 2011)

Liverpool_fan said:


> Why the cin.get() and cin.ignore() in piglatin()? These statements will have no effect, since control is returned before them.
> And let me guess their presence in main() is to trap keyboard to see output? You need a better IDE in that case.
> And why are you using global variables in the program? They are certainly not needed.



You got that right friend. I'm using dev-c++ and its forcing me to add cin.ignore and cin.get to trap keyboard to see output like you said.

Yes i had added them unnecessarily to the piglatin function.

About IDE, mate i had a lot of trouble with code::blocks today. It refused to compile and threw an error stating that iostream is not part of the directory.

Now i searched here and there in the web and found out a few solutions which stated to give the minigw path manually.

But everything went in vain and it just didn't compile anything and i had to revert back to dev c++.

Suggest me what to do mate??



Neuron said:


> Search the same wikipedia page for the word 'scram'.



Yeah saw it. Scram is amscray. Why is that?

Oh- you mean i have to add a vowel check method to turn the consonant cluster??


----------



## Neuron (Sep 26, 2011)

pig is igpay because the 2nd letter itself is a vowel(i).So the left of 'i' is rotated.Same with computer o is a vowel.So c alone is there to be rotated.
Similarly in scram ,the left of the firstly found vowel is rotated,ie,the left of a,'scr'.If it was
cjkdkomputer then the piglatin will be omputercjkdkay.


----------



## vickybat (Sep 26, 2011)

Neuron said:


> pig is igpay because the 2nd letter itself is a vowel(i).So the left of 'i' is rotated.Same with computer o is a vowel.So c alone is there to be rotated.
> Similarly in scram ,the left of the firstly found vowel is rotated,ie,the left of a,'scr'.If it was
> cjkdkomputer then the piglatin will be omputercjkdkay.



Oh got it mate. Thanks for that. I will modify the code accordingly.

I guess a switch case to check vowels will do isn't it? 
And to do that we have to check each and every character of the string.
Loops will also be needed.


----------



## Liverpool_fan (Sep 26, 2011)

vickybat said:


> Suggest me what to do mate??


Try Geany. Make sure your paths  are configured, and g++ and gcc works from the command line.



vickybat said:


> Oh got it mate. Thanks for that. I will modify the code accordingly.
> 
> I guess a switch case to check vowels will do isn't it?
> And to do that we have to check each and every character of the string.
> Loops will also be needed.



STL will make it much simpler. (Not necessarily most efficient).


----------



## somulesnar (Sep 27, 2011)

@ neuron

sorry buddy actually i was on the wrong path......thnx for making me realise the actual piglatin concept. I will too try my level best to write on the way u told...........

one more help can u plz check out the bubble sort program of mine mentioned earlier and write me the same using recursion......


----------



## Garbage (Sep 27, 2011)

somulesnar said:


> @ neuron
> one more help can u plz check out the bubble sort program of mine mentioned earlier *and write me the same using recursion......*



You should not ask someone else to write a program for you if you want to "learn" programming.


----------



## somulesnar (Sep 27, 2011)

^^ buddy i have already mentioned that i am a novice in c c++ programming language.

Yet if i am wrong then plz atleast plz suggest me the logic that i shud use for the stated program...


----------



## mitraark (Sep 27, 2011)

somulesnar said:


> ^^ buddy i have already mentioned that i am a novice in c c++ programming language.
> 
> Yet if i am wrong then plz atleast plz suggest me the logic that i shud use for the stated program...



I know this might feel a little harsh but never try to get your homework done from Net instead if you go through the book trying to find the answer you;ll leanr not only that but many other important things as well. 

Since you are trying to get Bubble Sort using recursion , you can definitely start to read up on "Recursion" chapter in the C / C++ Book you got.


----------



## Garbage (Sep 28, 2011)

A bit offtopic, but I found this site interesting - Computational Fairy Tales: Posts by Topic

It teaches algorithm like a fairy tales. 

And this site visualize the different sorting algorithms - Sorting Algorithm Animations


----------



## somulesnar (Sep 28, 2011)

mitraark said:


> I know this might feel a little harsh but never try to get your homework done from Net instead if you go through the book trying to find the answer you;ll leanr not only that but many other important things as well.
> 
> Since you are trying to get Bubble Sort using recursion , you can definitely start to read up on "Recursion" chapter in the C / C++ Book you got.




@ mitraark

if i wud rely mostly on books then for what is this thread made for. It is made for the learners in c and c++ programmers. So if u have learned enough of it then my kind request to u is to plz stop posting unnecessary posts into it. If u r not willing to help then its well and fine. 

BTW i didnt ask my prob to u personally i asked to the members who are willing to help me with my prob. So plz stop commenting on others posts.....


----------



## mitraark (Sep 28, 2011)

somulesnar said:


> @ mitraark
> 
> if i wud rely mostly on books then for what is this thread made for. It is made for the learners in c and c++ programmers. So if u have learned enough of it then my kind request to u is to plz stop posting unnecessary posts into it. If u r not willing to help then its well and fine.
> 
> BTW i didnt ask my prob to u personally i asked to the members who are willing to help me with my prob. So plz stop commenting on others posts.....



I am sorry but i did not mean to have offended you in any way. It is just that the problem you presented is a textbook problem  of recursion , probably every book out there that covers Recursion has the answers as an example. So i thought maybe a book will come in handy for you


----------



## somulesnar (Sep 28, 2011)

^^ its alright buddy. Actually ur post started of with an irritating take off. U r right in ur point but the thing is that i am on the go so i dont have any books on with me so plz co-operate.


----------



## Liverpool_fan (Sep 28, 2011)

You don't have books, but you can always google.
Anyway your problem is with recursion concept and just this problem?


----------



## somulesnar (Sep 28, 2011)

^^ yes of course i searched a lot of sites but cant get a proper one for the above program....

All the codes are written in the sites in more or less C++ language wich i am not friendly with. So plz help..


----------



## Garbage (Sep 28, 2011)

somulesnar said:


> @ mitraark
> 
> *if i wud rely mostly on books then for what is this thread made for.* It is made for the learners in c and c++ programmers. So if u have learned enough of it then my kind request to u is to plz stop posting unnecessary posts into it. If u r not willing to help then its well and fine.
> 
> BTW i didnt ask my prob to u personally i asked to the members who are willing to help me with my prob. So plz stop commenting on others posts.....



Mind you, this thread is NOT made for asking to solve your homework questions directly, without even reading books or searching Google.
People who ask for help without even trying are not *learners*.
I would say, this is a very bad attitude towards learning and towards the community.

And I think you need to read through following link BEFORE you ask any more questions. It would help you in your online stay.

How To Ask Questions The Smart Way



> Before asking a technical question by e-mail, or in a newsgroup, or on a website chat board, do the following:
> 
> 
> Try to find an answer by searching the archives of the forum you plan to post to.
> ...


----------



## somulesnar (Sep 28, 2011)

^^ ok fine i ll first try to sort out tjis question wen i return home then ill post in this thread... till then good bye TDF members....


----------



## asingh (Sep 28, 2011)

Guys....have we gone nuts in the head or what...? How can you ascertain that it is homework which is being requested here. And if it is..? So..? The world has changed, if a problem is assigned to a student the teacher know quite well that external sources can be looked upon. Day of reckoning comes when the person takes a test behind 4 walls.

So let us not be so condescending and try to deter members when they ask queries. I personally have created SQL queries and Excel spreadsheets and MDB DB's for users whose handle ID was all I knew..?

If someone does not want to help, they can at least guide or explain a couple of concepts. Somulesnar, started his post with a decent code snippet, so it is not that he is asking TDF to do the work.

Thanks.


----------



## Liverpool_fan (Sep 28, 2011)

*somulesnar*

Answer this.


Liverpool_fan said:


> Anyway your problem is with recursion concept and just this problem?


----------



## Garbage (Sep 28, 2011)

asingh said:


> Guys....have we gone nuts in the head or what...? How can you ascertain that it is homework which is being requested here. And if it is..? So..? The world has changed, if a problem is assigned to a student the teacher know quite well that external sources can be looked upon. Day of reckoning comes when the person takes a test behind 4 walls.
> 
> So let us not be so condescending and try to deter members when they ask queries. I personally have created SQL queries and Excel spreadsheets and MDB DB's for users whose handle ID was all I knew..?
> 
> ...



If it would have been *only* about solving the problem and NOT about learning, then I am 100% agree with you. But I am sure, just solving the problem for someone will not help that someone in learning. Will it?


----------



## sakumar79 (Sep 28, 2011)

^^ Exactly  - If the OP posts sample code of what he/she has tried and the problems faced, setting them on the right path helps the OP understand where the mistake is and this transforms the original failure to solve the problem into a learning process. When the OP had earlier asked help in sorting out the piglatin problem, there were useful suggestions given to help the OP in getting to the solution. That is the right way to help the OP learn IMHO...

Arun


----------



## somulesnar (Sep 28, 2011)

@ asingh

Thnx a lot sir. The same thing i was trying to convey to the other members but i think they didnt get tht perfectly. Anyways i would try to solve this prob myself and if i cant i will let u know guys....

Cheers....



Liverpool_fan said:


> *somulesnar*
> 
> Answer this.




yes my prob is with the recursion concept of this prob only...


----------



## vickybat (Sep 28, 2011)

asingh said:


> Guys....have we gone nuts in the head or what...? How can you ascertain that it is homework which is being requested here. And if it is..? So..? The world has changed, if a problem is assigned to a student the teacher know quite well that external sources can be looked upon. Day of reckoning comes when the person takes a test behind 4 walls.
> 
> So let us not be so condescending and try to deter members when they ask queries. I personally have created SQL queries and Excel spreadsheets and MDB DB's for users whose handle ID was all I knew..?
> 
> ...



Even i mostly agree to this.


----------



## asingh (Sep 28, 2011)

Garbage said:


> If it would have been *only* about solving the problem and NOT about learning, then I am 100% agree with you. But I am sure, just solving the problem for someone will not help that someone in learning. Will it?



He had posted some code, so telling him what was wrong would help.  See if someone has expertise why not tell..?



sakumar79 said:


> ^^ Exactly  - If the OP posts sample code of what he/she has tried and the problems faced, setting them on the right path helps the OP understand where the mistake is and this transforms the original failure to solve the problem into a learning process. When the OP had earlier asked help in sorting out the piglatin problem, there were useful suggestions given to help the OP in getting to the solution. That is the right way to help the OP learn IMHO...
> 
> Arun



If at times someone is not getting it..we can nudge him and give more specific answers. That is how it works...at least I thought so when teaching stuff about programming.


----------



## Liverpool_fan (Sep 29, 2011)

All right.
First of all Bubble Sort is not exactly the most naturally expressed in recursive algorithm. However any iterative algorithm can be made recursive crudely at least. Is the following you desire? 

I would still say at least iteratively compare the adjacent items in the function send_max_to_rear, the resulting code stuck with recursion only is very clumsy in my opinion, unless someone does it better.



Spoiler





```
#include <stdio.h>

#define LEN 25

void send_max_to_rear(int *l, int pos, int len); 
void pass(int *l, int len); 

int main(void)	{
	int i;
	int list[LEN];

	for(i = 0; i < LEN; ++i)	{
		printf("Enter for %d: ", i+1);
		scanf("%d", &list[i]);
	}

	pass(list, LEN);

	for(i = 0; i < LEN; ++i)	{
		printf("%d ", list[i]);
	}
	puts(""); // Put a newline at the end of program's stdin

	return 0;
}

void send_max_to_rear(int *l, int pos, int len)	{
	/*
		This function sends the largest member of the sublist to the rear.
	*/
	
	/* Compare the members at `pos` and `pos+1` and swap if necessary */
	if (l[pos] > l[pos+1])	{
		int temp = l[pos];
		l[pos] = l[pos+1];
		l[pos+1] = temp;
	}

	/* As long as there are two elements to compare in the (sub)list, call compare the next two elements. */
	if (pos < len - 2)	{
		send_max_to_rear(l, pos+1, len); // Move to the next position to compare.
	}
}

void pass(int *l, int len)	{
	/*
		This function recursively calls unsorted part of the list, after each pass.
	*/

	/* As long as array is has two unsorted elements, bubble sort it. */
	if (len > 1	)	{
		send_max_to_rear(l, 0, len);
		pass(l, len - 1);
	}
}
```




P.S.: Divide and Conquer based algorithms are more suitable for recursive implementation, I'll suggest try QuickSort.

P.P.S.: Double test the code just in case, sleepy head you know.


----------



## somulesnar (Sep 29, 2011)

^^ thnx a lot. Ok now i got the right logic. Thnx for everything guys.

Cheers...


----------



## clmlbx (Oct 18, 2011)

Guys, Here is my Programme  to calculate Pixel per Inch(ppi) of any screen with Classes in different files.


```
// this is main.cpp, actual Programme (Name = main.cpp)

#include <iostream>
#include "PPI.h"

using namespace std;

int main()
{
    PPI ppiobj;
    ppiobj.Welcome();
    ppiobj.GetData();
    ppiobj.Calculateppi();
    ppiobj.Output();

}
```



```
// this is class File/self made header File./ where everything is Declared (Name is = PPI.h)


#ifndef PPI_H
#define PPI_H


class PPI
{
    public:

        PPI();
        void Welcome();
        void GetData();
        void Calculateppi();
        void Output();
        ~PPI();
    protected:
    private:
        int Width;
        int Height;
        int DR;
        float  ppi;
        float root;
        float Size;
};

#endif // PPI_H
```



```
// This is where all class Function is Defined..(Name = PPI.cpp)

#include "PPI.h"
#include <iostream>
#include <math.h>
#include<iomanip>

using namespace std;

PPI::PPI()
{
    //ctor
}

void PPI::Welcome(){

    cout<<setw(40)<<"Welcome"<<endl<<endl;
    cout<<"This Programme Will help you to calculate Pixel Per Inch (PPI) Of your screen"<<endl ;
    cout<<"\n\nThings you should have : "<<endl<<endl<<"1. Resloution"<<endl<<"2. Size of Screen in Inches"<<endl;

}

void PPI::GetData()
{

cout<<"\n\nEnter Resolution in this Format (1280 720) ::  ";
cin>> Width>> Height;

cout<<endl<<"\nEnter sice Of screen ::   ";
cin>>Size;
}


void PPI::Calculateppi(){

DR = (Width * Width) + (Height * Height);

root= sqrt(DR);

ppi = root/Size;


}


void PPI:: Output(){

cout<< "\n\nPPI of your Screen is :: " <<ppi<<endl;
}


PPI::~PPI()
{
    cout<<"\n\n Thank You for using this Programme."<<endl;
    cout <<"\n\nFor any feedback Pls Contact :: feedback@No-one.com";
}
```


Edit: oops I find out My own mistake.. I made constructor and that Welcome Data was supposed to be in Constructor function.. but while Writing I code I made another Function for it (welcome Function)


----------



## somulesnar (Oct 19, 2011)

hey guys here's a c program to merge two single linked lists.... i ve used switch case to get on over wid this prob can u suggest me an easier way....



Spoiler



#include<stdio.h>
#include<conio.h>
#define null 0
void create();
void display();
void insert();
void delet();
void erase();
void create2();
void display2();
void insert2();
void delet2();
void erase2();
void link1();
void link2();
void merge();
struct node
{
int info;
struct node *next;
}*start,*ptr,*temp,*prev;
struct node2
{
int info;
struct node2 *nex;
}*start2,*ptr2,*temp2,*prev2;
void main()
{
int op;
clrscr();
do
{
printf("\n1.link1\n2.link2\n3.merge\n4.exit");
printf("\nEnter your option");
scanf("%d",&op);
switch(op)
{
case 1:
link1();
break;
case 2:
link2();
break;
case 3:
merge();
break;
case 4:
break;
default:
printf("\nEnter correct option");
}
}while(op!=4);
getch();
}
void create()
{
int data;
printf("\nEnter the data");
scanf("%d",&data);
do
{
ptr=malloc(sizeof(struct node));
ptr->info=data;
ptr->next=NULL;
if(start==NULL)
start=ptr;
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
printf("\nEnter the data & Press 0 to terminate");
scanf("%d",&data);
}while(data!=0);
}
void display()
{
temp=start;
if(start==NULL)
printf("\nList is empty");
else
{
printf("\nElements of list:\n");
while(temp->next!=NULL)
{
printf("%d\t",temp->info);
temp=temp->next;
}
printf("%d\t",temp->info);
}
}
void insert()
{
int data,pos;
printf("\nEnter data & position to insert the element");
scanf("d",&data,&pos);
temp=start;
ptr=malloc(sizeof(struct node));
ptr->info=data;
while(temp->next!=NULL)
{
if(temp->info==pos)
{
ptr->next=temp->next;
temp->next=ptr;
break;
}
else
temp=temp->next;
}
if(temp->next==NULL)
{
temp->next=ptr;
ptr->next=NULL;
}
}
void delet()
{
int pos,flag=0;
if(start==NULL)
printf("List is empty");
else
{
printf("Enter element to be deleted");
scanf("%d",&pos);
temp=start;
if(start->info==pos)
{
flag=1;
start=start->next;
free(temp);
}
else
{
while(temp->next!=NULL)
{
prev=temp;
temp=temp->next;
if(temp->info==pos)
{
flag=1;
prev->next=temp->next;
free(temp);
break;
}
}
}
if(flag==0)
printf("\nElement is not present in list");
}
}
void erase()
{
if(start==NULL)
printf("\nList is empty");
else
{
while(start->next!=NULL)
{
temp=start;
start=start->next;
free(temp);
}
temp=start;
start=start->next;
free(temp);
printf("list is erased");
}
}
void create2()
{
int data;
printf("\nEnter the data");
scanf("%d",&data);
do
{
ptr2=malloc(sizeof(struct node2));
ptr2->info=data;
ptr2->nex=NULL;
if(start2==NULL)
start2=ptr2;
else
{
temp2=start2;
while(temp2->nex!=NULL)
{
temp2=temp2->nex;
}
temp2->nex=ptr2;
}
printf("\nEnter the data & Press 0 to terminate");
scanf("%d",&data);
}while(data!=0);
}
void display2()
{
temp2=start2;
if(start2==NULL)
printf("\nList is empty");
else
{
printf("\nElements of list:\n");
while(temp2->nex!=NULL)
{
printf("%d\t",temp2->info);
temp2=temp2->nex;
}
printf("%d\t",temp2->info);
}
}
void insert2()
{
int data,pos;
printf("\nEnter data & position to insert the element");
scanf("d",&data,&pos);
temp2=start2;
ptr2=malloc(sizeof(struct node2));
ptr2->info=data;
while(temp2->nex!=NULL)
{
if(temp2->info==pos)
{
ptr2->nex=temp2->nex;
temp2->nex=ptr2;
break;
}
else
temp2=temp2->nex;
}
if(temp2->nex==NULL)
{
temp2->nex=ptr2;
ptr2->nex=NULL;
}
}
void delet2()
{
int pos,flag=0;
if(start2==NULL)
printf("List is empty");
else
{
printf("Enter element to be deleted");
scanf("%d",&pos);
temp2=start2;
if(start2->info==pos)
{
flag=1;
start2=start2->nex;
free(temp2);
}
else
{
while(temp2->nex!=NULL)
{
prev2=temp2;
temp2=temp2->nex;
if(temp2->info==pos)
{
flag=1;
prev2->nex=temp2->nex;
free(temp2);
break;
}
}
}
if(flag==0)
printf("\nElement is not present in list");
}
}
void erase2()
{
if(start2==NULL)
printf("\nList is empty");
else
{
while(start2->nex!=NULL)
{
temp2=start2;
start2=start2->nex;
free(temp2);
}
temp2=start2;
start2=start2->nex;
free(temp2);
printf("list is erased");
}
}
void link1()
{
int op;
start=NULL;
do
{
printf("\n1.create\n2.display\n3.insert\n4.delete\n5.erase\n6.exit");
printf("\nEnter your option");
scanf("%d",&op);
switch(op)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert();
break;
case 4:
delet();
break;
case 5:
erase();
break;
case 6:
break;
default:
printf("\nEnter correct option");
}
}while(op!=6);
getch();
}
void link2()
{
int op;
start2=NULL;
do
{
printf("\n1.create\n2.display\n3.insert\n4.delete\n5.erase\n6.exit");
printf("\nEnter your option");
scanf("%d",&op);
switch(op)
{
case 1:
create2();
break;
case 2:
display2();
break;
case 3:
insert2();
break;
case 4:
delet2();
break;
case 5:
erase2();
break;
case 6:
break;
default:
printf("\nEnter correct option");
}
}while(op!=6);
getch();
}
void merge()
{
if(start==NULL)
{
start=start2;
}
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=start2;
}
temp=start;
if(start==NULL)
printf("\nList is empty");
else
{
printf("\nElements of list:\n");
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->next;
}
}
getch();
}


----------



## raj100 (Nov 27, 2011)

*Armstrong value program*

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
	int save,number,digit,count=0,rev=0,m,n,save2;
   clrscr();
   printf("Enter number to print=");
   scanf("%d",&number);
   save=number;
   save2=number;
   while(number!=0)
   {
   	m=number%10;
      digit=m/m;
      count=count+digit;
      number=number/10;
   }
   printf("\n %d",count);
   while(save!=0)
   {
      n=save%10;
      rev=rev+pow(n,count);
      save=save/10;
   }
   printf("\n %d",rev);
   if(rev==save2)
   {
   	printf("\nEnter number is Armstrong");
   }
   else
   {
   	printf("\nEnter number is not armstrong");
   }
   getch();
   }


----------



## nims11 (Nov 27, 2011)

*Re: Armstrong value program*



Spoiler






raj100 said:


> #include<stdio.h>
> *#include<conio.h>*
> #include<math.h>
> void main()
> ...






live in present buddy!


----------



## priyaranjan (Nov 27, 2011)

*Re: Post ur C/C++ Programs Here*



Ron said:


> scanf("%d%d%d",&a,&b,&c);
> New to c++.......Whta those this line means



scanf() takes input from standard input(key board) and stores in some variables.

%d is called format specifier for integer variable, it tells compiler that coming input from the keyboard is  an integer . 

next is &a , this is the address of the variable "a" which needs to be passed to the scanf()
to store the input data in variable "a".

so by combing all compiler now knows that input data needs to be stored in an integer variable and the variable is a.

now in your question there are three inputs coming from your key board so you have 3 %d  and the three address of the variables that is &a,&b,&c.


----------

