Skip to main content

Posts

Showing posts from June, 2012

Function Objects in C++

Both C and C++ support function pointers, which provide a way to pass around instructions on how to perform an operation. But function pointers are limited because functions must be fully specified at compile time. What do I mean? Let's say that you're writing a mail program to view an inbox, and you'd like to give the user the ability to sort the inbox on different fields--to, from, date, etc. You might try using a sort routine that takes a function pointer capable of comparing the messages, but there's one problem--there are a lot of different ways you might want to compare messages. You could create different functions that differ only by the field of the message on which the comparison occurs, but that limits you to sorting on the fields that have been hard-coded into the program. It's also going to lead to a lot of if-then-else blocks that differ only by the function passed into the sort routine. What you'd really like is the ability to pass in a thir

So you want to write a game?

The best way to learn how to write games is, alas, to get a solid grounding in the basics of computer science. Graphics There is perhaps no single area of gaming in which players standards have risen more than in the field of graphics. While players in the 70s and 80s were accustomed to screens of text or 16-bit black-and-white graphics, the users of today demand Riven-quality, 3D graphics, complete with lighting effects, textures, and scale. Unfortunately, graphics are hard to do. They require math, at least on the level of multivariable calculus, and a great deal of time. But if you aren't quite a math wizard yet, don't despair; for more casual games, most people are willing to accept simple 2D sprites. Anyone who's ever been addicted to Tetris knows that while simple graphics may not cut it on the shelves any more, they're no barrier to a satisfying gaming experience. For more info on graphics programming, check out our tutorial on creating graphics with OpenGL

Switch case in C and C++

Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. switch ( <variable> ) { case this-value:   Code to execute if <variable> == this-value   break; case that-value:   Code to execute if <variable> == that-value   break; ... default:   Code to execute if <variable> does not equal the value following any of the cases   break; } Posted By :- Cplusplusprogramming

What are pointers? Why should you care?

Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes of various sizes at a local bank. Each safety deposit box will have a number associated with it so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box. Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelry. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables. The cool thing is that once you can talk about the address of a variable, you'll then b

How is Graphic used

First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.  void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver); Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0. *graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type. *graphmode Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type. *path

Laws of Boolean Algebra

T1 : Commutative Law (a) A + B = B + A (b) A B = B A T2 : Associate Law (a) (A + B) + C = A + (B + C)  (b) (A B) C = A (B C) T3 : Distributive Law (a) A (B + C) = A B + A C (b) A + (B C) = (A + B) (A + C) T4 : Identity Law (a) A + A = A  (b) A A = A T5 : (a)  (b)  T6 : Redundance Law            (a) A + A B = A              (b) A (A + B) = A T7 :             (a) 0 + A = A             (b) 0 A = 0 T8 :            (a) 1 + A = 1             (b) 1 A = A T9 : (a)    (b)  T10 : (a)    (b)  T11 : De Morgan's Theorem (a)  (b)  Posted By :- Cplusplusprogramming

Moving Car C++ Program

#include <graphics.h> #include <dos.h> int main() {    int i, j = 0, gd = DETECT, gm;    initgraph(&gd,&gm,"C:\\TC\\BGI");    settextstyle(DEFAULT_FONT,HORIZ_DIR,2);    outtextxy(25,240,"Press any key to view the moving car");    getch();    for( i = 0 ; i <= 420 ; i = i + 10, j++ )    {       rectangle(50+i,275,150+i,400);       rectangle(150+i,350,200+i,400);       circle(75+i,410,10);       circle(175+i,410,10);       setcolor(j);       delay(100);       if( i == 420 )          break;       if ( j == 15 )          j = 2;       cleardevice(); // clear screen    }    getch();    closegraph();    return 0; } Posted By :-  Cplusplusprogramming

Swapping of two numbers in c

#include <stdio.h> int main() {    int x, y, temp;    printf("Enter the value of x and y\n");    scanf("%d%d", &x, &y);    printf("Before Swapping\nx = %d\ny = %d\n",x,y);    temp = x;    x = y;    y = temp;    printf("After Swapping\nx = %d\ny = %d\n",x,y);    return 0; } Posted By :- Cplusplusprogramming

Linear search for multiple occurrences

In the code below we will print all the locations at which required element is found and also the number of times it occur in the list. #include<stdio.h>   main() {    int array[100], search, c, n, count = 0;      printf("Enter the number of elements in array\n");    scanf("%d",&n);      printf("Enter %d numbers\n", n);      for ( c = 0 ; c < n ; c++ )       scanf("%d",&array[c]);      printf("Enter the number to search\n");    scanf("%d",&search);      for ( c = 0 ; c < n ; c++ )    {       if ( array[c] == search )           {          printf("%d is present at location %d.\n", search, c+1); count++;       }    }    if ( count == 0 )       printf("%d is not present in array.\n", search);    else       printf("%d is present %d times in array.\n", search, count);      return 0; } OUTPUT Posted By :- Cplusplusprogramming

Linear search c program

#include<stdio.h> main() {    int array[100], search, c, number;    printf("Enter the number of elements in array\n");    scanf("%d",&number);    printf("Enter %d numbers\n", number);    for ( c = 0 ; c < number ; c++ )       scanf("%d",&array[c]);    printf("Enter the number to search\n");    scanf("%d",&search);    for ( c = 0 ; c < number ; c++ )    {       if ( array[c] == search )     /* if required element found */       {          printf("%d is present at location %d.\n", search, c+1); break;       }    }    if ( c == number )       printf("%d is not present in array.\n", search);        return 0; } OUTPUT Posted By :- Cplusplusprogramming

It is a C program to convert it in C++ just instead of given two header files

‎/* Written by : SAURABH DHORMARE */ /* it is a C program to convert it in C++ just instead of given two header files*/ /* just put #include<iostream.h> */ /*and instead of printf(""); write cout<<""; it is very easy,isn't it? */ /* Run it & see what happens !!! */ /* stop it after run if you can; without closing output window */ #include<stdio.h> #include<conio.h> void main() { int i; int j=1; int k=2,l=7,m=11; for(i=0;i<=j;i++) { printf("SAURABH\n\n"); if(i==k) { printf(" Neo\n\n\n"); k=k+2; } if(i==l) { printf(" I'm\n\n\n"); l=l+7; } if(i==m) { printf(" Matrix"); m=m+11; } j++; /* getch(); */ /*if problem try getch();*/ } } Writen By :- Saurabh.dhormare Posted By :- Cplusplusprogramming

Character and string literals

There also exist non-numerical constants, like: 'z' 'p' "Hello world" "How do you do?" The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes ("). When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: x 'x' x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'. Character and string literals have certain peculiarities, like the esca

Floating Point Numbers

They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character: 3.14159    // 3.14159 6.02e23    // 6.02 x 10^23 1.6e-19    // 1.6 x 10^-19 3.0        // 3.0  These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal. The default type for floating point literals is double. If you explicitly want to express a float or a long double numerical literal, you can use the f or l suffixes respectively: 3.14159L   // long double 6.02e23f   // float  Any of the letters that can be part of a floating-point numerical co

VARIABLE DATA TYPES

The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence written on the screen as result. It certainly would have been much faster to type the output sentence by ourselves. However, programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work we need to introduce the concept of variable. Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorize also the number 2 at the same time. You have just stored two different values in your memory. Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Values that we could now -for example- subtract and obtain 4 as result

LINKED LIST

Linked list is a very common data structure often used to store similar data in memory. While the elements of an array occupy contiguous memory locations, those of a linked list are not constrained to be stored in adjacent location. The individual elements are stored “somewhere” in memory, rather like a family dispersed, but still bound together. The order of the elements is maintained by explici t links between them. Thus, a linked list is a collection of elements called nodes, each of which stores two item of information—an element of the list, and a link, i.e., a pointer or an address that indicates explicitly the location of the node containing the successor of this list element. Write a program to build a linked list by adding new nodes at the beginning, at the end or in the middle of the linked list. Also write a function display( ) which display all the nodes present in the linked list.solve in C++ Posted By :-  Cplusplusprogramming

Guessing Game

The following program will act as a guessing game in which the user has eight tries to guess a randomly generated number. The program will tell the user each time whether he guessed high or low: #include <stdlib.h> #include <iostream> using namespace std; int main() { int number=rand()___; int guess=-1; int trycount=0; while(guess__number __ trycount<8) { cout__"Please enter a guess: "; cin__guess; __(guess_number) cout<<"Too low"<<endl;  __(guess_number) cout<<"Too high"<<endl; _______________; _ if(guess==number) cout<<"You guessed the number"; ____ cout<<"Sorry, the number was: "<<_____; ______ 0; _ Posted By :- Cplusplusprogramming

Array Challenge

When completed, the following program should first fill in (by asking the user for input) and then list all the elements in an array: #include <_____>             using namespace std;       ___ main() {   int array[8]___   for(int x=_; x<_; ___)   cin>>______;   for(____; x<____; ___)   cout<<_____;   return __; ____ Posted By :- Cplusplusprogramming

PASS -BY-REFERENCE

#include <iostream.h> #include <stdlib.h> int exp (int,int); void readnums (int&, int&); void main () {   int b, e;   readnums(b,e);   cout << b << " to the " << e << " = " << exp(b,e) << endl; } void readnums (int& b, int& e) {   int correctInput;   cout << "Enter the base and the exponent: ";   cin >> b >> e;   if (!cin) {     cout << "Disaster! Terminating program." << endl;     exit(-1);   }   correctInput = (b >= 0) && (e >= 0);   while (!correctInput) {     cout << "Something wrong! Try again ..." << endl;     cout << "Re-enter base and exponent: ";     cin >> b >> e;         if (!cin) {       cout << "Disaster! Terminating program." << endl;       exit(-1);     }     correctInput = (b >= 0) && (e >= 0);   }   }

Program to construct a 3-dimensional bar

#include <conio.h> #include <graphics.h> #include <stdlib.h> #include <stdio.h> void main (int) { int gdriver=DETECT,gmode,errorcode; //Requesting auto-detection. int midx,midy,x; //Initializing graphics and local variables. initgraph(&gdriver,&gmode,"d:\\bc3\\bgi"); //Reading result of initialization. errorcode=graphresult(); if(errorcode!=grOk) //An error occurred. { printf("Graphics error occurred : %s \n",grapherrormsg(errorcode)); printf("Press any key to stop : "); getch(); exit(1); //Terminate the program due to error. } setfillstyle(EMPTY_FILL,0); /*The above statement means that the setfillstyle function is used to set the fill style of the 3-d bar as a blank.*/ bar3d(200,200,300,450,10,1); getch(); closegraph(); } Posted By :- Cplusplusprogramming

Program to draw 2 rectangles and fill 1 of them

#include <iostream.h> #include <conio.h> #include <graphics.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> void main() {   clrscr();   int gd = DETECT,gm,errorcode; //Requesting auto-detection.   //Initializing graphics and local variables.   initgraph (&gd, &gm, "d:\\bc3\\bgi"); //Path where graphics drivers are installed   //Read result of initialization.   errorcode = graphresult();   //An error occured.   if (errorcode != grOk)     {       cout << "Graphics error occured : \n" << grapherrormsg(errorcode) << endl;       cout << "Press any key to stop : ";       getch();       exit(1);     }   /*Drawing a rectangle having top LHS vertex at (300, 300)   and bottom RHS vertex at (600, 400)*/   rectangle(300, 300, 600, 400);   rectangle(100, 100, 200, 200);   getch();   floodfill(120, 120, WHITE);   getch();   closegraph(); } Posted By :-

Program to enter the sale value and print the agent's commission

#include <iostream.h> #include <conio.h> void main() { clrscr(); long int svalue; float commission; cout << "Enter the total sale value : " << endl; cin>>svalue; if(svalue<=10000) { commission=svalue*5/100; cout << "For a total sale value of $" << svalue << ", "; cout << "the agent's commission is $" << commission; } else if(svalue<=25000) { commission=svalue*10/100; cout << "For a total sale value of $" << svalue << ", "; cout << "the agent's commission is $" << commission; } else if(svalue>25000) { commission=svalue*20/100; cout << "For a total sale value of $" << svalue << ", "; cout << "the agent's commission is $" << commission; } getch(); } Posted By :- Cplusplusprogramming

Hello World!

Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ #include <iostream> using namespace std; int main () {   cout << "Hello World!";   return 0; } Hello World! Posted By :- Cplusplusprogramming

Program to enter a character and output its ASCII code

#include <iostream.h> #include <conio.h> void main() { clrscr(); char charac; cout << "Enter the character : " << endl; cin>>charac; int num1=charac; cout << "The ASCII code for " << charac << " is " << num1 << "." << endl; getch(); } Posted By :-  Cplusplusprogramming

C++ LIBRARY MANAGEMENT SYSTEM

#include<fstream.h> #include<conio.h> #include<stdio.h> #include<process.h> #include<string.h> #include<iomanip.h> //*************************************************************** //                   CLASS USED IN PROJECT //**************************************************************** class book { char bno[6]; char bname[50]; char aname[20];   public: void create_book() { cout<<"\nNEW BOOK ENTRY...\n"; cout<<"\nEnter The book no."; cin>>bno; cout<<"\n\nEnter The Name of The Book "; gets(bname); cout<<"\n\nEnter The Author's Name "; gets(aname); cout<<"\n\n\nBook Created.."; } void show_book() { cout<<"\nBook no. : "<<bno; cout<<"\nBook Name : "; puts(bname); cout<<"Author Name : "; puts(aname); } void modify_book() { cout&

C++ HANGMAN GAME

#include <iostream.h> #include <stdlib.h> #include <string.h> #include <conio.h> const int MAXLENGTH=80; const int MAX_TRIES=5; const int MAXROW=7; int letterFill (char, char[], char[]); void initUnknown (char[], char[]); int main () { char unknown [MAXLENGTH]; char letter; int num_of_wrong_guesses=0; char word[MAXLENGTH]; char words[][MAXLENGTH] = { "india", "pakistan", "nepal", "malaysia", "philippines", "australia", "iran", "ethiopia", "oman", "indonesia" }; //choose and copy a word from array of words randomly randomize(); int n=random(10); strcpy(word,words[n]);     // Initialize the secret word with the * character. initUnknown(word, unknown); // welcome the user cout << "\n\nWelcome to hangman...Guess a country Name"; cout << "\n\nEach letter is repre