Smart C++ Programs example

// *****************************************

// cplusplus language tutorial

// section 2.1

//

// "Guess the number"

// Shows:

// - do-while

// - if-else

//

// Briefing:

// The computer generates a random number

// between 1 and MAX_RANGE. The user must

// guess the number. Each time the user

// makes an attempt the computer tells if

// the number is greater or less than.

// *****************************************

#include <iostream.h>

#include <stdlib.h>

#include <time.h>

// Define the greatest possible value:

#define MAX_RANGE 100

main ()

{

int counter=0;

long value,input;

srand ( time (NULL) ); // Initialize random generator

value = rand()%MAX_RANGE+1; // Get random between 1 and MAX_RANGE

cout << "\nInsert a value between 1 and " << MAX_RANGE << " : ";

do {

cin >> input; // Get user input

counter++; // increase attempts counter

if (value>input) // is value grater than the input?

cout << "Value is greater than " << input << ". Try again : ";

else if (value<input) // if not, is it less?

cout << "Value is less than " << input << ". Try again : ";

else { // else it is the correct number!

cout << "That's right! Value was " << input;

cout << "\nYou have needed " << counter <<" attempts.";

}

} while (value!=input);

return 0;

}

/ *****************************************

// cplusplus language tutorial

// section 2.2

//

// "Stone, Scissors or Paper"

// Shows:

// - The use of functions

// - switch-case and if-else statements

//

// Briefing:

// In this game, the user and the computer

// choose each one an option between stone,

// scissors and paper.

// Stone wins over scissors, scissors over

// paper and paper over stone:

// stone -> scissors -> paper -> stone...

// The first who wins WINSCORE times is

// the competition winner.

// *****************************************

#include <iostream.h>

#include <stdlib.h>

#include <time.h>

#define WINSCORE 3

// Function PickRandomOption

// * Returns a random character between 's', 'x', and 'p'

char PickRandomOption (void)

{

char option;

srand ( time (NULL) ); // (re)initialize random number generator

int value = rand()%3; // Generate random number between 0 and 2

switch (value) {

case 0: option='s'; break;

case 1: option='x'; break;

case 2: option='p'; break;

}

return option;

}

// Function WhoWins

// * check which of the characters passed wins.

// return values:

// 0= tie, 1=the first, 2=the second, -1=error

int WhoWins (char a, char b)

{

switch (a)

{

case 's':

if (b=='x') return 1;

else if (b=='p') return 2;

else return 0;

case 'x':

if (b=='p') return 1;

else if (b=='s') return 2;

else return 0;

case 'p':

if (b=='s') return 1;

else if (b=='x') return 2;

else return 0;

default:

return -1;

}

// NOTE: no break instructions were included in this switch statement

// because a break instruction at the end of a case would never

// been executed because there would always be a return statement

// executed before.

// For the same reason this peculiar function has no explicit ending

// return statement.

}

main ()

{

char you, me;

int mypoints=0;

int yourpoints=0;

int winner;

do {

//prompt user.

cout << "\nEnter s, x or p ";

cout << "(s=stone, x=scissors, p=paper): ";

cin >> you;

//decide computer's option and say it

me = PickRandomOption();

cout << "I say: " << me << "\n";

// check who is the winner

winner = WhoWins (you,me);

// show appropiate message:

if (winner==0) cout << "Tied\n";

else if (winner==1) { cout << "You win\n"; yourpoints++; }

else if (winner==2) { cout << "I win\n"; mypoints++; }

else cout << "Sorry. You entered an Invalid option\n";

// show current scoreboard.

cout << "POINTS: You:" << yourpoints;

cout << " Me:" << mypoints << "\n";

} while (yourpoints<WINSCORE && mypoints<WINSCORE);

if (yourpoints>mypoints) cout << "You win the competition!\n";

else cout << "I win the competition!\n";

return 0;

}

// *****************************************

// cplusplus language tutorial

// section 3.2

//

// "The Secret Word"

// Shows:

// - strings

// - arrays of strings

// - cstring functions: strcpy and strlen

//

// Briefing:

// The user has to discover all the letters

// in a secret keyword.

// Each letter said that is in the keyword

// is shown in its rightful location.

// He/She has the opportunity to fail up

// to FAILS_ALLOWED times.

// *****************************************

#include <iostream.h>

#include <stdlib.h>

#include <time.h>

#include <string.h>

#define N_KEYS 12

#define KEY_MAX_WIDTH 20

#define FAILS_ALLOWED 7

// Possible keywords. You may inser new ones if you increase N_KEYS.

char possiblekeys [N_KEYS][KEY_MAX_WIDTH] = {

"mushroom", "pineapple", "neighborhood", "citizen",

"programming", "darkness", "fundamental", "encyclopedia",

"businessman", "restaurant", "observatory", "civilization"

};

// This will store the key

char key [KEY_MAX_WIDTH];

// This will store the string shown on screen with letters already discovered.

char outstring [KEY_MAX_WIDTH];

int CheckLetter (char letter);

main ()

{

char input;

int valid;

int fails = FAILS_ALLOWED,discoverd;

unsigned int discovered = 0;

unsigned int n;

// Select a key.

srand ( time (NULL) ); // Initialize random number generator

int value = rand()%N_KEYS; // Get random between 0 and NKEYS-1

strcpy (key,possiblekeys[value]); // Copy key

// Set outstring to '-' characters plus terminating null-character

for (n=0; n<strlen(key); n++) outstring[n]='-';

outstring[n]='\0';

do {

// Prompt user

cout << "\nDiscover the secret key: " << outstring << "\n";

cout << "Enter a letter (You may fail " << fails << " times): ";

cin >> input; cin.ignore (100,'\n');

// check if letter is valid

valid = CheckLetter (input);

// it it is valid, increase dicovered letters counter.

// if not, decrease allowed fails

if (valid!=0) discovered+=valid;

else fails--;

} while (discovered < strlen(key) && fails>0);

// The loop ends if key is discovered or fails are exhausted.

// Display CORRECT! only if key was discovered.

if (discoverd == strlen(key)) cout << "CORRECT! ";

cout <<"Key was '" << key <<"\n";

return 0;

}

// Function that checks if letter is in key.

// returns the number of times the letter was found in key

int CheckLetter (char letter)

{

unsigned int n;

int found=0;

for (n=0; n<strlen(key); n++)

if (key[n]==letter && outstring[n]=='-')

{

found++;

outstring[n]=key[n];

}

return found;

}

//////////////////////////////////TABLE//////////////////////////

#include <stdio.h>

int main()

{

int table_size = 12;

int row = 0;

int col = 0;

for(col=0 ; col<=table_size ; col++){

printf(" %4d", col);

}

printf("\n");

for(col=0 ; col<=table_size ; col++){

printf("_____");

}

for(row = 0 ; row<=table_size ; row++){

printf("\n");

for(col = 0 ; col<=table_size ; col++) {

if(row == 0) {

if(col == 0){

printf(" ");

}else{

printf("|%4d", col);

}

}else{

if(col == 0){

printf("%4d", row);

}else{

printf("|%4d", row*col);

}

}

}

}

printf("\n");

}

/////////////////////// Execute any dos command using c code//////////////////////

#include <stdio.h>

# include <conio.h>

void main()

{

char *s;

printf("\n Enter Dos Command With Path");

gets(s);

system(s);

getch();

}

#include <iostream.h>

#include <stdlib.h>

int main()

{ int height, width, tmp, tmp2;

cout << "Please Enter The Height Of A Rectangle (whole numbers only): "; height: cin >> height;

if(height<1){cout << " Please Enter A Height Of Between 1 And 20: "; goto height;}

cout << "Please Enter The Width Of A Rectangle (whole numbers only): "; width: cin >> width;

if(width<1) {cout << " Please Enter A Width Of Between 1 And 38: "; goto width;}

cout << ' '; // Add a space at the start (to neaten top)

for(tmp=0; tmp!=width; tmp++) cout << "__"; // Top Of Rectangle

for(tmp=0; tmp!=(height-1); tmp++) {cout << "\n|"; // Left Side Of Rectangle

for(tmp2=0; tmp2!=width; tmp2++) cout << " "; // Create A Gap Between Sides

cout << "|";} // Right Side Of Rectangle

cout << "\n|"; // Left Side Of Bottom Of Rectangle to neaten bottom)

for(tmp=0; tmp!=width; tmp++) cout << "__"; // Bottom Of Rectangle

cout << '|'; // Right Side Of Bottom Of Rectangle (to neaten bottom)

cout << "\n\n"; system("PAUSE"); return 0;

}

# include <iostream.h>

# include <iomanip.h> // library that has the setw output manipulator

int main ()

{

char letter; // letter is the symbol or letter made into a giant triangle

int width; // width is how far to go into the center of screen

int base; // base is how many symbols are on bottom line

int a; // a is how many lines down the triangle is

int b = 1; // b is how many symbols are displayed on each line

int counter = 0; // counter is how many times the loop executed

cout<<"This program will make a triangle of the symbol entered."<<endl;

cout<<"It must be an odd number for the triangle to form properly."<<endl;

cout<<"If an even number is entered, it will be lowered to the previous odd."<<endl;

while(cin) // This allows the program to loop until the user closes the window

{

cout<<"Enter a symbol or character."<<endl;

cin>>letter;

cout<<"Enter the number of characters the base should have."<<endl;

cin>>base;

width = (base / 2) + 5 - counter; // This is how far into the center it should space until it starts outputting the symbol

// It must first be given a value before it enters the loop

a = 1; // a is how many lines down the triangle is, and natuarally it starts on the first line

while(width > 5) // It will loop and continue to output the symbol until it reaches 5 spaces from the left margin...

// so that everything isn't jammed against the side

{

width = (base / 2) + 5 - counter; // This is how far into the center it should space until it starts outputting the symbol

cout<<setw(width); // setw is an output manipulator in the <iomanip.h> library. this tell the compiler how many lines

// to move until it first sends a character to the screen. It is currently set to move the value of

// "width" spaces to the right before it outputs.

while(b > 0) // This while loop will continue to output the desired symbol to the current line until it is equal to 1

{

cout<<letter; // outputs the letter or symbol entered

b--; // b is decremented so only so many letters are outputted per line

}

cout<<endl; // an endl is used to jump to the next line to output the next part of the triangle

b = (a * 2) - 1; // the number of symbols per line is found using this equation

width--; // the width is decremented so that everything is spaced properly

b = b + 2; // b is given 2 more symbols because it is on the next line, and every line has 2 more than the previous

a++; // this is how many lines into the triangle it is

counter++; // the counter is used to ensure proper spacing done by the width variable

}

cout<<endl<<endl; // endl is used to add some space between each time the program is executed

b = 1; // b is returned to 1 because the program started over

counter = 0; // counter is returned to 0 because the program started over

}

return 0;

}

Program to Find the IP Address of a System

#include <stdio.h>

#include <WinSock.h>

#include <stdlib.h>

#pragma comment (lib, "wsock32.lib")

int main()

{

WORD wVersionRequested;

WSADATA wsaData;

char caHostname[255+1];

PHOSTENT hostData;

char *pIP;

int i=0;

wVersionRequested=MAKEWORD(1,1);

if(WSAStartup(wVersionRequested, &wsaData)!=0)

{

printf("Error......code is not compartible with platform\n");

exit(EXIT_FAILURE);

}

if(gethostname(caHostname, sizeof caHostname)!=0)

printf("Error......Hostname not found\n");

printf("HOSTNAME : %s\n",caHostname);

if((hostData=gethostbyname(caHostname))==NULL)

{

printf("Error......code is not compartible with platform\n");

exit(EXIT_FAILURE);

}

while(hostData->h_addr_list[i])

{

pIP = inet_ntoa(*(struct in_addr *)hostData->h_addr_list[i]);

printf("IP ADDRESS %d: %s\n", ++i, pIP);

}

return 0;

}