Post your C/C++ Programs Here

Status
Not open for further replies.

gkara

Right off the assembly line
Trigonometric functions using C

Hi,

A C program that would perfom the basic trigonometric function would have the below possible look:

Code:
#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

Retired Forum Mod
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.

Code:
#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.
 
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

Super Moderator
Staff member
Re: Post ur C/C++ Programs Here

^^ well, every school and most colleges still stuck on Turbo C/C++. Can't help it really.
 

gkara

Right off the assembly line
Re: Post ur C/C++ Programs Here

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.
 

Vyom

The Power of x480
Staff member
Admin
Re: Post ur C/C++ Programs Here

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
 

subhransu123

Journeyman
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

Right off the assembly line
Program to Create a sorted merit list in files

code:

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;
}
 
Last edited by a moderator:

somulesnar

Journeyman
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

Broken In
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

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



For three numbers : this will be a good one i think

void main()
{
int a,b,c,i sum;
printf("Enter the three numbers");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
for(i=0;1<sum;i++)
{
if(i==a||i==b||i==c)
printf("\t %d",i);
}
}
 

Neuron

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

BIOS Terminator
Re: Post ur C/C++ Programs Here

Prime Number checker using 3 different algorithms-

Code:
#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

Electronic.
Infix to postfix conversion & postfix evaluation

Infix to postfix converter:

Code:
#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

Code:
#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

BIOS Terminator
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 -

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

Electronic.
Re: Post ur C/C++ Programs Here

^^Good job.I can help.But will take some time :smile:

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.
 
Last edited:

nims11

BIOS Terminator
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...
 
Status
Not open for further replies.
Top Bottom