Post your C/C++ Programs Here

Status
Not open for further replies.

Desi-Tek.com

In the zone
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.

#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?
thats why we use long

multi threading mini web server in java
Code:
 //***************************************
// 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 "";
	
    }
    
}
 
Last edited:

QwertyManiac

Commander in Chief
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 :lol:
 

shady_inc

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

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

mortal kombat
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

Beware of the innocent
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

left this forum longback
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

Console Junkie
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

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

shady_inc said:
Code:
#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*/
    
  }
cin.get();
}         
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++
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.
 
Last edited:

The_Devil_Himself

die blizzard die! D3?
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

C# Be Sharp !
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.

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

Hope this helps.
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

die blizzard die! D3?
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

In the zone
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.
 

timemachine

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

aditya.shevade

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