Thursday 31 January 2013

C Programming Language Homepage


http://cprogramminglanguage.net/c-hello-world.aspxC Programming Language Homepage

Getting Started with C

Getting Started with C

In this article, you are going to develop the first program in C. You will learn how the sequence of a C program works.

The C program is a set of functions.  A C program always starts executing in a special function which is known as main function. Here is the simple but famous "Hello World" program that prints a greeting message on screen.
1#include <stdio.h>
2main()
3{
4    printf("Hello World!\n");
5    return 0;
6}
Let's examine the program above in details.
  • First, you see #include directive in the first line. Every directive in C is denoted by a sign (#).  C program uses this directive to load external function library - stdio is c library which provides standard input/output. printf () is a function which is declared in the header file called stdio.h
  • Next, you see the main() function - It is the first entry point of a C program. A C program logic starts from the beginning of main function to the its ending.
  • Finally, you notice that we use printf() function which accepts a string as a parameter. The printf() function is used to print out the message on the screen. The main() function is supposed to return an integer number so we put return 0 statement at the end of the program.
In the following section, we will show you step by step running this program in CodeBlock IDE. If you don't have IDE to run the program, you can install CodeBlocks by following the step-by-step tutorial.
Launch the IDE, and create your first project from File > New > Project...
New Console Project
Choose Console appliction



Choose C language

Enter project name and folder to create project in.


Click Run button you will see the console window display the message "Hello world!"

Congratulation! You've developed the first program in C. Let's go to the next tutorials to explore the power of C programming language, enjoy programming!

 

All Programming Tutorials

All Programming Tutorials  
http://r4r.co.in/c/basic_tutorials/01/ 

R4R

R4R

R4R

R4R



R4R

R4R

R4R

R4R

Teaching Programming for Kids with C-Jump, Alice, Kids Corner


Teaching Programming for Kids with C-Jump, Alice, Kids Corner

http://www.madrasgeek.com/2010/11/teaching-programming-for-kids-with-c-jump-alice-kids-corner.html

http://www.simplecodeworks.com/website.html

C-Jump


C-Jump is a board game which is aimed at kids of 11 years and older to learn programming languages. You can start learning from basic programming lang to complicated as c, c++ and java. Fun education tool to download. Download C-Jump

 

Wednesday 30 January 2013

Computer Graphics Projects

Computer Graphics Projects
http://studyhelpline.net/Projects.aspx

TajMahalDraw Tajmal using C or CPP
Drawing Tajmahal using Computer Graphics is Simple and easy firstly you need to draw pic on graphs then implement using computer graphics functions.
Draw Sai Baba using C
Drawing SaiBaba using Computer Graphics is Simple and easy firstly you need to draw pic on graphs then implement using computer graphics functions.
Draw Lord Ganesha using C
Drawing Lord Ganesha using Computer Graphics is Simple and easy firstly you need to draw pic on graphs then implement using computer graphics functions.
Draw Animated Tajmahal using C
Drawing Animated TajMahal using Computer Graphics is Simple and easy firstly you need to draw pic on graphs then implement using computer graphics functions.
Show Animated Flight using C
This Project of Computer Graphics Show Flight Take Off to Flight Blast and then Person in Flight Landing through Parasuit.
Draw Animated ScreenSaver using C
This Animated ScreenSaver shows moving of ball thought out the screen. Pressing 'Esc' Key stop the movement and then press any key to Exit.
Showing Space with your Name using C
This program is used to show space with lots of stars and your name in that space. This is very usefull program to make your Project Starting page.
Showing Space with moving saucer using C
This Program is used to show a moveing space saucer that is moving here and there in the space.

Monday 28 January 2013

Short Notes For Engineering Students from all over

Short Notes For Engineering Students from all over


http://loremate.com/

100,000+ topics! | 150+ Universities!

Introduction to Windows - Programming for Windows

Introduction to Windows - Programming for Windows

History - DOS
Disk Operating System aka DOS was one of the earlier operating systems, it was a single task system, where the whole system and the OS was devoted to executing a single program and was basically a text based OS.

With the advent of the Windows Operating System, multiple process or applications could be run and it became a graphical OS (interface). So in order to support new features the basic structure of C/C++ programs changed from the main(){...} procedure to
something of a program as shown below and the a new compiler is required for compiling and generating Windows Executables, Visual C++ is such an example.


/*Program to
Display a Window on Windows
Test Compiled using Visual C++
*/

#include <windows.h>

LRESULT CALLBACK WindowFunc(HWND, UINT, WPARAM, LPARAM);

char szWinName[] = "MyWin";

int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgs,
int nWinMode)
{
 HWND hwnd;
 MSG msg;
 WNDCLASSEX wcl;

 wcl.cbSize = sizeof(WNDCLASSEX);
 wcl.hInstance = hInstance;
 wcl.lpszClassName = szWinName;
 wcl.lpfnWndProc = WindowFunc;
 wcl.style = 0;
 wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
 wcl.hIconSm = NULL;
 wcl.hCursor = LoadCursor(NULL, IDC_ARROW);

 wcl.lpszMenuName = NULL;
 wcl.cbClsExtra = 0;
 wcl.cbWndExtra = 0;

 wcl.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);

 if(!RegisterClassEx(&wcl))  return 0;

 hwnd = CreateWindow(szWinName,"Windows XP",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL);


 ShowWindow(hwnd,nWinMode);
 UpdateWindow(hwnd);

 while(GetMessage(&msg,NULL,0,0))
 {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }
 return msg.wParam;
}

LRESULT CALLBACK WindowFunc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam)
{
 switch(message)
 {
 case WM_DESTROY:
  PostQuitMessage(0);
  break;
 default:
  return DefWindowProc(hwnd,message,wparam,lparam);
 }
 return 0;
}
 
 
 
 
 
Windows OS Skeleton
Windows is called so because all things 
you see on your desktop is broken into small Windows. A Window can have 
many child windows, parent window, and many other windows on the same 
level.

Getting Started to Windows Programming in C(++)?
A minimal Windows program must have atleast 2 functions
  • WinMain()
  • WindowFunc()


the WinMain() Function
The WinMain() function is the entry point to your program, i.e, the execution of your program starts with WinMain().
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgs,int WinMode)

The WinMain function must
  1. Define a window class

  2. Register the class (RegisterClassEx)

  3. Create Window (CreateWindowEx)

  4. Display Window (ShowWindow)

  5. Get the message loop running(while(GetMessage(...)))


The contents in italics is the functions used for doing the specified actions. Check them out in the code.

the Window Procedure
The window Procedure is the link between your program and windows. It is the window procedure that windows calls to send messages to your application.

That's all for now
 
 
 

 

Beginning Windows programming in C

Beginning Windows programming

http://www.win32developer.com/tutorial/windows/windows_tutorial_1.shtm

Welcome to the world of Windows, or also known as Win32, programming. Programming under windows can be an initially daunting task. Within the next few tutorials, you should have a better understanding of how to program on the Win32 platform.

These tutorials assume a basic understanding of C or C++ and are designed to compile and run under Visual Studio.net 2005 and 2008.
 

Windows programming is very different to programming a console application. But, it certainly can be an exciting and rewarding challenge to take up. Once a few fundamentals are learnt you will be well on your way. If I can do it, so can you.

Important note: These tutorials use Multi-Byte character set. If you use Unicode these projects will not compile (without minor alteration). If you are unsure, please setup your project as per 'Pre-requisites 2' on the main tutorial page.
If you have any questions or suggestions. Please feel free to email me (see the 'Contact Me' page) or post a discussion in the forums.

Prerequisites

Project type: Windows
Include files: windows.h
Library files: N/A



The most basic Windows program - The 'Message box'

The first thing I should point out is that, with console applications the entry point was something like so;

int main(int argc,char *argv[])

In a Win32 application the entry point to a program is more like;
INT WINAPI wWinMain(HINSTANCE hInst,
 HINSTANCE hPrevInst,
 LPWSTR lpCmdLine,
 INT nShowCmd)

The only real differences are that the first parameter holds the instance of the program being executed, the second parameter is the previous instance, which isn't really used any more as it was for compatibility with really old applications in the 16 bit days. The third parameter holds any command line arguments (eg. 'application.exe -SomeSwitches') and the last parameter tells the program how to start, ie. maximised, minimised, etc..

Now we have that out of the way we can move on...

What better way tho start our Win32 programming journey than a really simple Windows application. We will go through the steps in creating a simple message box. Message boxes are handy as they can alert the user to important information, for example error messages, simple notifications, or even as the user a question.

An example of a message box can be seen below.

Windows Win32 message box

Creating a Windows message box is achieved by using the MessageBox() function. To replicate the message box seen above we would type the following;

MessageBox(NULL,"Do you really want to continue?","Are you sure?",MB_ICONQUESTION);
The message box function is defined as follows;

int MessageBox(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
hWnd - is the handle to the window that you are working with
lpText - is the text that is to be displayed in the message box
lpCaption - is the title of the message box
uType - defines various properties like the icon and types on input (eg, Yes, No, Cancel, etc..)

The last parameter is of particular interest as this is the main influence on how the message box looks and acts. In the example above we used 'MB_ICONQUESTION' to tell the message box to display the question mark icon. We could have used any of the following types;

MB_ICONQUESTIONMB_ICONQUESTION
MB_ICONWARNINGMB_ICONWARNING
MB_ICONINFORMATIONMB_ICONINFORMATION
MB_ICONERRORMB_ICONERROR

The other main elements of interest are the types input buttons available to the user (ie, Yes, No, Cancel, etc..)

MB_ABORTRETRYIGNOREAbort, Retry, and Ignore
MB_CANCELTRYCONTINUECancel, Try Again, and Continue
MB_HELPHelp
MB_OKOK
MB_OKCANCELOK and Cancel
MB_RETRYCANCELRetry and Cancel
MB_YESNOYes and No
MB_YESNOCANCELYes, No, and Cancel

To define what icons and message buttons we want to use at the same time, we just separate the options with |.
For example MB_ICONQUESTION|MB_OKCANCEL will display the question mark icon with the buttons labelled 'OK' and 'Cancel'.

The message box function will return the value of the button that was pressed. The return values are actually integers, but it is best to use the 'defines' as listed below for readability and fault finding.

IDABORTAbort button was pressed
IDCANCELCancel button was pressed
IDCONTINUEContinue button was pressed
IDIGNOREIgnore button was pressed
IDNONo button was pressed
IDOKOK button was pressed
IDRETRYRetry button was pressed
IDTRYAGAINTry Again button was pressed
IDYESYes button was pressed

There are many other parameters related to text formatting and so on, which is best left visiting MSDN (linked at bottom of page).

In the next tutorial we will move on to basic Window creation and progress to more involved applications down the track.

The Full Code

#include <windows.h>

INT WINAPI wWinMain(HINSTANCE hInst,
   HINSTANCE hPrevInst,
   LPWSTR lpCmdLine,
   INT nShowCmd)

{
 int nResult=MessageBox(NULL,
   "An example of Cancel,Retry,Continue",
   "Hello Message Box!",
   MB_ICONERROR|MB_ABORTRETRYIGNORE);
 
 switch(nResult)
 {
  case IDABORT:
   // 'Abort' was pressed
   break;
  case IDRETRY:
   // 'Retry' was pressed
   break;
  case IDIGNORE:
   // 'Ignore' was pressed
   break;
 }

 return 0;
}


Things to try

Try adding another message box in the switch cases to display a response to the button being pressed. Don't forget to visit the forums to post your solutions!

Additional information

For additional information we have provided the following links.

Microsoft (MSDN) - Message boxes


Next tutorial

Tutorial 2 - Creating a basic window

 

Download Turbo C++ for Windows 7 Full screen Read original Article: Download Turbo C++ for Windows 7 Full screen bug fixed

Download Turbo C++ for Windows 7 Full screen

As we all know that old Turbo C ++ compiler does not work properly on windows 7 properly i.e. it work in windowed mode which annoys most of students and programmers who had windows 7 operating system installed on their PC. So people started opting of other C and C++ compilers available online but problem still persists when point comes to running graphics programs in C Language.  Several techniques came in the market like Dosbox C programming emulator and others but dealing with them is quite hectic and difficult too because in most cases it turned out a fail attempt. So to resolve this problem and put away all hectic stuff, Ccodechamp has came up with one click Turbo C++ installer with dosbox inbuilt, means no extra setting has to be done. Just click the installer it will install the turbo C++ compiler on machine and best point is in Full screen mode. Hence you all can enjoy your old Turbo C++ compiler in full mode on windows 7 also. So download turbo C++ for windows 7 full screen bug fixed.
Turbo C++ for windows 7 Full screen bug fixed
Turbo C++ for windows 7 Full screen bug fixed

Turbo C++ for Windows 7 64 Bit Edition:

So here we are with a pre emulated and fully working Turbo C++ compiler for Windows 7 and Windows Vista 64 Bit edition.It is a one click installation setup which enables you to use Turbo C++  on Windows 7 64 Bit in full screen mode.The setup package which we are providing here is a simple pre-emulated Turbo C++ setup which is already to run on Windows 7.
Just install it as a simple software and then run normally.It will start in full screen mode.Its fully tested and 100% working!
Click here to Download Turbo C++ for windows 7 full screen

How To Install Turbo C++?

Download the package given above. Extract it using any Windows file compression software, for eg., 7zip,WinRar etc.
Run the setup file and go through the installation process step by step (:P just going to ask next one time). After installation finishes,click Finish button and now Run Turbo C++ from Start ->All Programs Menu or :P from your desktop icon.
That’s all. Enjoy ! Turbo C++ in full screen mode without any bug.
Happy C and C++ programming ! Feel free to request any C program or code. I love to code stuff and will provide you in less than a day on Ccodechamp portal. If you like my articles and programs , then push a little effort in clicking Google + button and Facebook like :P and if you wish to receive such updates daily in your mails then feel comfortable with subscribing us by email.

Friday 25 January 2013

LIBRARY FUNCTION

LIBRARY FUNCTION

# Include Directive
The # include directive instructs the compiler to read and include another file in the current file. The compiler compiles the entire code. A header file may be included in one of two ways.
include <iostream.h>
or
include "iostream.h"
The header file in angle brackets  means that file reside in standard include directory. The header file in double quotes means that file reside in current directory.
LIBRARY FUNCTION
C++ provides many built in functions that saves the programming time

Mathematical Functions
Some of the important mathematical functions in header file math.h are
Function Meaning
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1 (x) where x (measured in radians)
acos(x) Cos-1 (x) where x (measured in radians)
exp(x) Exponential function of x (ex)
log(x) logarithm of x
log 10(x) Logarithm of number x to the base 10
sqrt(x) Square root of x
pow(x, y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x
Character Functions
All the character functions require ctype.h header file. The following table lists the function.
Function Meaning
isalpha(c) It returns True if C is an uppercase letter and False if c is lowercase.
isdigit(c) It returns True if c is a digit (0 through 9) otherwise False.
isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic character (either uppercase or lowercase) otherwise False.
islower(c) It returns True if C is a lowercase letter otherwise False.
isupper(c) It returns True if C is an uppercase letter otherwise False.
toupper(c) It converts c to uppercase letter.
tolower(c) It converts c to lowercase letter.
String Functions
The string functions are present in the string.h header file. Some string functions are given below:
strlen(S) It gives the no. of characters including spaces present in a string S.
strcat(S1, S2) It concatenates the string S2 onto the end of the string S1. The string S1 must have enough locations to hold S2.
strcpy(S1, S2) It copies character string S2 to string S1. The S1 must have enough storage locations to hold S2.
strcmp((S1, S2)==0)
strcmp((S1, S2)>0)
strcmp((S1, S2) <0)
It compares S1 and S2 and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2.
strcmpi((S1, S2)==0)
strcmpi((S1, S2)>0)
strcmpi((S1, S2) <0)
It compares S1 and S2 ignoring case and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2.
strrev(s) It converts a string s into its reverse
strupr(s) It converts a string s into upper case
strlwr(s) It converts a string s into lower case
Console I/O functions
The following are the list of functions are in stdio.h
getchar() It returns a single character from a standard input device (keyboard). It takes no parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to output device. It also returns this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream stdin.
puts() It takes a string which is to be sent to output device.
General purpose standard library functions
The following are the list of functions are in stdlib.h
randomize() It initializes / seeds the random number generator with a random number
random(n) It generates a random number between o to n-1
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string
Some More Functions
The getch() and getche() functions
The general for of the getch() and getche() is
ch=getche();
ch1=getch();
ch and ch1 are the variables of type character. They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character and press enter key. The value of the character returned from getche() is assigned to ch. The getche() fuction echoes the character to the screen. Another function, getch(), is similar to getche() but does not echo character to the screen.

 

FLOW OF CONTROL

FLOW OF CONTROL

Statements

Statements are the instructions given to the computer to perform any kind of action. Action may be in the form of data movement, decision making etc. Statements form the smallest executable unit within a C++ program. Statements are always terminated by semicolon.

Compound Statement

A compound statement is a grouping of statements in which each individual statement ends with a semi-colon. The group of statements is called block. Compound statements are enclosed between the pair of braces ({}.). The opening brace ({) signifies the beginning and closing brace (}) signifies the end of the block.

Null Statement

Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is quite useful when the syntax of the language needs to specify a statement but the logic of the program does not need any statement. This statement is generally used in for and while looping statements.

Conditional Statements

Sometimes the program needs to be executed depending upon a particular condition. C++ provides the following statements for implementing the selection control structure.
  • if statement
  • if else statement
  • nested if statement
  • switch statement

if statement

syntax of the if statement
if (condition)
{
  statement(s);
}
From the flowchart it is clear that if the if condition is true, statement is executed; otherwise it is skipped. The statement may either be a single or compound statement.
if-else

if else statement

syntax of the if - else statement
if (condition)
  statement1;
else
  statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the condition is true, statement1  is executed. If the condition is false, statement2 is executed. It should be kept in mind that statement and statement2 can be single or compound statement.
if example if else example
if (x == 100)
    cout << "x is 100";
if (x == 100)
    cout << "x is 100";
else
    cout << "x is not 100";

Nested if statement

The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement
if(condition 1)
{
  if(condition 2)
  {
    statement(s);
  }
}
if(condition 1)
  statement 1;
else if (condition 2)
  statement2;
else
  statement3;

 
if-else-if example
if(percentage>=60)
     cout<<"Ist division";
else if(percentage>=50)
     cout<<"IInd division";
else if(percentage>=40)
     cout<<"IIIrd division";
else
     cout<<"Fail" ;

switch statement

The if and if-else statements permit two way branching whereas switch statement permits multiple branching. The syntax of switch statement is:
switch (var / expression)
{
   case constant1 : statement 1;
   break;
   case constant2 : statement2;
   break;
   .
   .
   default: statement3;
   break;
}
The execution of switch statement begins with the evaluation of expression. If the value of expression matches with the constant then the statements following this statement execute sequentially till it executes break. The break statement transfers control to the end of the switch statement. If the value of expression does not match with any constant, the statement with default is executed.
Some important points about switch statement
  • The expression of switch statement must be of type integer or character type.
  • The default case need not to be used at last case. It can be placed at any place.
  • The case values need not to be in specific order.

 

OPERATORS

OPERATORS

Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators,  Logical operators, Unary operators, Assignment operators, Conditional operators, Comma operator

Arithmetical operators

Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation. You can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or remainder % operator is used only with the integral data type.
Operators that have two operands are called binary operators.

Relational operators

The relational operators are used to test the relation between two values. All relational operators are binary operators and therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true. The following table shows the relational operators.
Relational Operators Meaning
Less than
<= Less than or equal to
== Equal to
Greater than
>= Greater than or equal to
! = Not equal to

Logical operators

The logical operators are used to combine one or more relational expression. The logical operators are
Operators Meaning
|| OR
&& AND
! NOT

Unary operators

C++ provides two unary operators for which only one variable is required.
For Example a = - 50;
a = + 50;
Here plus sign (+) and minus sign (-) are unary because they are not used between two variables.

Assignment operator

The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m = 5; The operator takes the expression on the right, 5, and stores it in the variable on the left, m. x = y = z = 32; This code stores the value 32 in each of the three variables x, y, and z.
in addition to standard assignment operator shown above, C++ also support compound assignment operators.

Compound Assignment Operators

Operator Example Equivalent to
+ = A + = 2 A = A + 2
- = A - = 2 A = A - 2
% = A % = 2 A = A % 2
/= A/ = 2 A = A / 2
*= A * = 2 A = A * 2

Increment and Decrement Operators

C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i;     //add one to i, store the result back in x
y= j++;     //store the value of j to y then add one to j
cout<<x;    //11
cout<<y;   //10

Conditional operator

The conditional operator ?: is called ternary operator as it requires three operands. The format of the conditional operator is:
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2 is evaluated. int a = 5, b = 6;
big = (a > b) ? a : b;
The condition evaluates to false, therefore biggets the value from b and it becomes 6.

The comma operator

The comma operator gives left to right evaluation of expressions. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i
Would first assign the value of a to i, and then assign value of b to variable i. So, at the end, variable i would contain the value 2.

The sizeof operator

As we know that different types of Variables, constant, etc. require different amounts of memory to store them The sizeof operator can be used to find how many bytes are required for an object to store in memory. For example
sizeof (char) returns 1
sizeof (int) returns 2
sizeof (float) returns 4
If k is integer variable, the sizeof (k) returns 2.
the sizeof operator determines the amount of memory required for an object at compile time rather than at run time.

The order of Precedence

The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is called the order of precedence. The following table shows the order of precedence.
Order Operators
First
Second
Third
()
*, /, %
+, -
The following table shows the precedence of operators.
++, --(post increment/decrement)
Highest
To

Lowest
++ (Pre increment) -- (Pre decrement), sizeof ( ), !(not), -(unary), +(unary)
*,/, %
+, -
<, <=, >, >=
==,!=
&&
? :
=
Comma operator

STRUCTURE OF C++ PROGRAM

STRUCTURE OF C++ PROGRAM

#include<header file>
main ()
{
...........
...........
...........
}
A C++ program starts with function called main ( ). The body of the function is enclosed between curly braces. The program statements are written within the braces. Each statement must end by a semicolon;(statement terminator). A C++ program may contain as many functions as required. However, when the program is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be executed.

// This is my first program is C++
/* this program will illustrate different components of
a simple program in C++ */

# include <iostream.h>
int main ( )
{
   cout <<"Hello World!";
   return 0;
}
When the above program is compiled, linked and executed, the following output is displayed on the VDU screen.
Hello World!
Various components of this program are discussed below:

Comments

First three lines of the above program are comments and are ignored by the compiler. Comments are included in a program to make it more readable. If a comment is short and can be accommodated in a single line, then it is started with double slash sequence in the first line of the program. However, if there are multiple lines in a comment, it is enclosed between the two symbols /* and */

#include <iostream.h>

The line in the above program that start with # symbol are called directives and are instructions to the compiler. The word include with '#' tells the compiler to include the file iostream.h into the file of the above program. File iostream.h is a header file needed for input/ output requirements of the program. Therefore, this file has been included at the top of the program.

int main ( )

The word main is a function name. The brackets ( ) with main tells that main ( ) is a function. The word int before main ( ) indicates that integer value is being returned by the function main (). When program is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be executed.

Curly bracket and body of the function main ( )

A C++ program starts with function called main(). The body of the function is enclosed between curly braces. The program statements are written within the brackets. Each statement must end by a semicolon, without which an error message in generated.

cout<<"Hello World!";

This statement prints our "Hello World!" message on the screen. cout understands that anything sent to it via the << operator should be printed on the screen.

return 0;

This is a new type of statement, called a return statement. When a program finishes running, it sends a value to the operating system. This particular return statement returns the value of 0 to the operating system, which means “everything went okay!”.
/* This program illustrates how to
declare variable, read data and display data. */

#include <iostream.h>
int main()
{
   int rollno; //declare the variable rollno of type int
   float marks; //declare the variable marks of type float
   cout << "Enter roll number and marks :";
   cin >> rollno >> marks; //store data into variable rollno & marks
   cout << "Rollno: " << rollno<<"\n";
   cout << "Marks: " << marks;
   return 0;
}
Sample Run: In this sample run, the user input is shaded.
Enter roll number and marks :102 87.5
Rollno: 102
Marks: 87.5

DATA HANDLING

DATA HANDLING

BASIC DATA TYPES

C++ supports a large number of data types. The built in or basic data types supported by C++ are integer, floating point and character. These are summarized in table along with description and memory requirement
Type Byte Range Description
int 2 -32768 to +32767 Small whole number
long int 4 -2147483648 to +2147483647 Large whole number
float 4 3.4x10-38 to 3.4x10+38 Small real number
double 8 1.7x10-308 to 1.7x10+308 Large real number
long double 10 3.4x10-4932 to 3.4x10+4932 Very Large real number
char 1 0 to 255 A Single Character

VARIABLES

It is a location in the computer memory which can store data and is given a symbolic name for easy reference. The variables can be used to hold different values at different times during the execution of a program.
To understand more clearly we should study the following statements:
Total = 20.00; In this statement a value 20.00 has been stored in a memory location Total.

Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the compiler to make available the appropriate type of location in the memory.
float Total;
You can declare more than one variable of same type in a single single statement
int x,y;
Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable with some initial value.
int a = 20;

 

INPUT/OUTPUT (I/O)

C++ supports input/output statements which can be used to feed new data into the computer or obtain output on an output device such as: VDU, printer etc. The following C++ stream objects can be used for the input/output purpose.
cin console input
cout console output
cout is used in conjuction with << operator, known as insertion or put to operator.
cin is used in conjuction with >> operator, known as extraction or get from operator.
cout << “My first computer"; Once the above statement is carried out by the computer, the message "My first computer" will appear on the screen.
cin can be used to input a value entered by the user from the keyboard. However, the get from operator>> is also required to get the typed value from cin and store it in the memory location.
Let us consider the following program segment:
int marks;
cin >> marks;
In the above segment, the user has defined a variable marks of integer type in the first statement and in the second statement he is trying to read a value from the keyboard.

 

TYPE CONVERSION

The process in which one pre-defined type of expression is converted into another type is called conversion. There are two types of conversion in C++.

1. Implicit conversion
2. Explicit conversion

Implicit conversion
Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;

When two operands of different type are encountered in the same expression, the lower type variable is converted to the higher type variable. The following table shows the order of data types.
Order of data types
Data type
long double
double
float
long
int
char
order

(highest) To

(lowest)
The int value of b is converted to type float and stored in a temporary variable before being multiplied by the float variable c. The result is then converted to double so that it can be assigned to the double variable a.
Explicit conversion
It is also called type casting. It temporarily changes a variable data type from its declared data type to a new one. It may be noted here that type casting can only be done on the right hand side the assignment statement.
T_Pay = double (salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is first converted to double data type and then added to the variable bonus.

CONSTANTS

A number which does not change its value during execution of a program is known as a constant. Any attempt to change the value of a constant will result in an error message. A constant in C++ can be of any of the basic data types, const qualifier can be used to declare constant as shown below:
const float pi = 3.1415; The above declaration means that Pi is a constant of float types having a value 3.1415.
Examples of valid constant declarations are:
const int rate = 50;
const float pi = 3.1415;
const char ch = 'A';

C++ BASICS

C++ BASICS

C++ CHARACTER SET

Character set is a set of valid characters that a language can recognize.
Letters A-Z, a-z
Digits 0-9
Special Characters Space  +  -  *  /  ^  \  ()  []  {}  =  !=  <>  ‘  “  $  ,  ;  :  %  !  & ? _  #  <=  >=  @ 
Formatting characters backspace, horizontal tab, vertical tab, form feed, and carriage return

TOKENS

A token is a group of characters that logically belong together. The programmer can write a program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

1. Keywords

These are some reserved words in C++ which have predefined meaning to compiler called keywords. Some commonly used Keyword are given below:
asm auto break case catch
char class const continue default
delete do double else enum
extern inline int float for
friend goto if long new
operator private protected public register
return short signed sizeof static
struct switch template this Try
typedef union unsigned virtual void
volatile while      

2. Identifiers

Symbolic names can be used in C++ for various data items used by a programmer in his program. A symbolic name is generally  known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rule for the formation of an identifier are:
  • An identifier can consist of alphabets, digits and/or underscores.
  • It must not start with a digit
  • C++ is case sensitive that is upper case and lower case letters are considered different from each other.
  • It should not be a reserved word.

3. Literals

Literals (often referred to as constants) are data items that never change their value during the execution of the program. The following types of literals are available in C++.
  • Integer-Constants
  • Character-constants
  • Floating-constants
  • Strings-constants

Integer Constants

Integer constants are whole number without any fractional part. C++ allows three types of integer constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0 (zero). For example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For example. 014, 012.
Hexadecimal integer constant: It consists of sequence of digits preceded by ox or OX.

Character constants

A character constant in C++ must contain one or more characters and must be enclosed in single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by using an escape sequence. An escape sequence represents a single character. The following table gives a listing of common escape sequences.
Escape Sequence Nongraphic Character
\a Bell (beep)
\n Newline
\r Carriage Return
\t Horizontal tab
\0 Null Character

Floating constants

They are also called real constants. They are numbers having fractional parts. They may be written in fractional form or exponent form. A real constant in fractional form consists of signed or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.

String Literals

A sequence of character enclosed within double quotes is called a string literal. String literal is by default (automatically) added with a special character ‘\0' which denotes the end of the string. Therefore the size of the string is increased by one character. For example "COMPUTER" will re represented as "COMPUTER\0" in the memory and its size is 9 characters.

4. Punctuators

The following characters are used as punctuators in C++.
Brackets [   ] Opening and closing brackets indicate single and multidimensional array subscript.
Parentheses (   ) Opening and closing brackets indicate functions calls,; function parameters for grouping expressions etc.
Braces {   } Opening and closing braces indicate the start and end of a compound statement.
Comma , It is used as a separator in a function argument list.
Semicolon ; It is used as a statement terminator.
Colon : It indicates a labeled statement or conditional operator symbol.
Asterisk * It is used in pointer declaration or as multiplication operator.
Equal sign = It is used as an assignment operator.
Pound sign # It is used as pre-processor directive.

5. Operators

Operators are special symbols used for specific purposes. C++ provides six types of operators. Arithmetical operators, Relational operators,  Logical operators, Unary operators, Assignment operators, Conditional operators, Comma operator

GETTING STARTED c++

GETTING STARTED C++

A computer cannot understand our language that we use in our day to day conversations, and likewise, we cannot understand the binary language that the computer uses to do it’s tasks. It is therefore necessary for us to write instructions in some specially defined language like C++ which is like natural language and after converting with the help of compiler the computer can understand it.

C++ COMPILER

A C++ compiler is itself a computer program which’s only job is to convert the C++ program from our form to a form the computer can read and execute. The original C++ program is called the “source code”, and the resulting compiled code produced by the compiler is usually called an “object file”.
Before compilation the preprocessor performs preliminary operations on C++ source files. Preprocessed form of the source code is sent to compiler.
After compilation stage object files are combined with predefined libraries by a linker, sometimes called a binder, to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled “object code” that provides operations that are done repeatedly by many computer programs.
compling and linking process c++ program

Using Turbo C++ Compiler

The first and frequently used method for creating program is Turbo C++'s Integrated Developement Enviornment (IDE). To start IDE type TC at DOS prompt. Or seach the file TC.EXE in your computer and Run it.
Your IDE will look like this..
IDE
1. Now type sample program on Editor
2. Click on Compile menu choose Compile option or press Alt+F9
3. Click on Run menu choose Run option or press Ctrl+F9
4. If there is no error output will be displayed on User Screen
Before we begin to learn to write meaningful programs in C++ language, let us have a look at the various buliding block of C++ language, also called elements of C++ language....

A Brief History of C++

A Brief History of C++

C++ was written by  Bjarne Stroustrup  at Bell Labs during 1983-1985. C++ is an extension of C.  Prior to 1983, Bjarne Stroustrup added features to C and formed what he called "C with Classes". He had combined the Simula's use of classes and object-oriented features with the power and efficiency of C. The term C++ was first used in 1983.
C++ was developed significantly after its first release.1 In particular, "ARM C++" added exceptions and templates, and ISO C++ added RTTI, namespaces, and a standard library.1
C++ was designed for the UNIX system environment. With C++ programmers could improve the quality of code they produced and reusable code was easier to write.
Bjarne Stroustrup had studied in the doctoral program at the Computing Laboratory at Cambridge University prior to joining Bell Labs. Now, Bell Labs no longer has that name since part of Bell Labs became AT&T Labs.  The other half became Lucent Bell labs.
Prior to C++, C was a programming language developed at Bell Labs circa 1969-1973. The UNIX operating system was also being developed at Bell Labs at the same time. C was originally developed for and implemented on the UNIX operating system, on a PDP-11 computer by Dennis Ritchie. He extended the B language by adding types in 1971. He called this NB for New B. Ritchie credited some of his inspiration from theAlgol68 language. Ritchie restructured the language and rewrote the compiler and gave his new language the name "C"  in 1972. 90% of UNIX was then written in C. The committee that wrote the 1989 ANSI Standard for C had started work on the C Standard project in 1983 after having been established by ANSI in that year. There were quite a number of versions of C at that time and a new Standard was necessary.
C is portable, not tied to any particular hardware or operating system. C combines the elements of high-level languages with the functionality of assembly language and has occasionally been referred to as a middle-level computer language. C makes it easy to adapt software for one type of computer to another.
C was a direct descendant of the language B. The language B was developed by Ken Thompson in 1970 for the new UNIX OS. B was a descendant of the language BCPL designed by Martin Richards, a Cambridge University student visiting MIT.1

 

Features of C++

Features of C++

The Features of C++
C++ is the multi paradigm, compile, free form , general purpose, statistically typed programming language. This is known as middle level language as it comprises of low level and high level language features.
And there are some other things and advantages of this language over the C. This language of invented by Bjarne Stroustrup was working on the “C with classes” as his Ph.D.  topic. The first commercial implementation of the C++ was released in 1985 and before that the name of language was changed to “C++”. And some new features were added to the language and The main features of the C++ are
  • Classes
  • Inheritance
  • Data abstraction and encapsulation
  • Polymorphism
  • Dynamic Binding
  • Message Passing
Lets elaborate each topic in this post…common friends lets do it…
1)      Classes: By using classes we can create user defined data types. In other words the class is the collection of set of data and code. The class allows us to do some things which are polymorphism, inheritance, abstraction, encapsulation which are our next features. The objects are the instances of classes.
The syntax for class is :
Class <class-name>
{
//Body of class;
};

2)      Inheritance: Inheritance allows one data type to acquire properties of other data types. Inheritance from a base class may be declared as public, protected, or private. If the access specifier is omitted, a “class” inherits privately, while a “struct” inherits publicly. This provides the idea of reusability that means we can add the new features to an existing class without modifying it.

3)      Data Abstraction and Encapsulation: Encapsulation means hiding of data from the data structures or in other words wrapping up of data in single entity is known as Encapsulation. In this the data is not accessible to outside world and only the  functions are allowed to access it.  When we want to write the class in which we don’t have the knowledge about the arguments used to instantiate it then we can use templates in C++. Abstraction can be defined as the act of representing essential features without including background details.


4)      Polymorphism: it means that the one interface can be used for many implementation so that object can behave differently for each implementation. The different types of polymorphism are static (Compile time) and dynamic (Run time).

5)      Dynamic Binding: It means that the linking of a procedure call to code to be executed in response to the call. A function call associated with a polymorphic reference depends on the dynamic type that reference. And at run-time the code matching the object under current reference will be called.

6)      Message Passing: An object oriented program consists of the set of objects that communicate with each other. objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to direct model or simulate their real world counterparts.

 

Characteristics Of C++

Characteristics Of C++

Why C++?
C++ has certain characteristics over other programming languages. The most remarkable ones are:

Object-oriented programming:
The possibility to orientate programming to objects allows the programmer to design applications from a point of view more like a communication between objects rather than on a structured sequence of code. In addition it allows a greater reusability of code in a more logical and productive way.

Portability:
You can practically compile the same C++ code in almost any type of computer and operating system without making any changes. C++ is the most used and ported programming language in the world.

Brevity:
Code written in C++ is very short in comparison with other languages, since the use of special characters is preferred to key words, saving some effort to the programmer (and prolonging the life of our keyboards!).

Modular programming:
An application's body in C++ can be made up of several source code files that are compiled separately and then linked together. Saving time since it is not necessary to recompile the complete application when making a single change but only the file that contains it. In addition, this characteristic allows to link C++ code with code produced in other languages, such as Assembler or C.

C Compatibility:
C++ is backwards compatible with the C language. Any code written in C can easily be included in a C++ program without making any change.

Speed:
The resulting code from a C++ compilation is very efficient, due indeed to its duality as high-level and low-level language and to the reduced size of the language itself.
 

BEST C++ study Materials










GETTING STARTED

Need of Programming Language, Source Code, Object code, C++ Compiler, Preprocessor, Linker, Using Turbo C++ Compiler

C++ BASICS

C++ Character Set, Tokens, Keywords, Identifiers, Literals, Integer constants, Character constants, Floating constants, Strings constants, Escape Sequence, Punctuators, Operators

DATA HANDLING

Basic data types, Variables, Input/Output (I/O), Type conversion, type casting, Constants, Structure of C++ Program, Comments

OPERATORS

Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment operator, Compound Assignment Operators, Conditional operator

FLOW OF CONTROL

Conditional Statements, if statement, if else , nested if, switch statement, Looping statement, while loop, do-while loop, for loop, Jump Statements, goto, break, continue

LIBRARY FUNCTION

#Include Directive, Mathematical Functions, Character Functions, String Functions, Console I/O functions, General purpose standard library functions, Some More Functions

FUNCTION

Prototyping, defining and calling a function, actual parameters and formal parameters, return type of a function, call by value, call by reference, inline function, default argument, global variable local variable

ARRAY

Declaration, Initialization of 1-D Array, Referring to array elements, using loop to input array from user, array as Parameter, traverse, Read, Linear Search, Binary Search, Bubble, Insertion Sort, Selection Sort, Merge

STRING

Declaration, Initializing, Reading strings, Printing strings, cin, gets(), cout, puts() counting number of characters in string, count number of words, length of string, copy contents of string, concatenate, compare string

2-D ARRAY

read a 2-D array, display content of a 2-D array, sum of two 2-D arrays, multiply two 2-D arrays, sum of rows & sum of columns of 2-D array, sum of diagonal elements of square matrix, transpose of a 2-D array

STRUCTURE

Defining a structure, Declaring Variables of Type struct, Accessing of its data members, Initialization of structure variable,Nested structure, typedef, Enumerated data type, #define, Macros

OOP CONCEPTS

Procedural Paradigm, Object Oriented programming, Object, Class, Data Abstraction, Encapsulation, Modularity, Advantages of Object oriented programming

CLASSES & OBJECTS

Classes and Objects, declaring a class, private members, protected members, public members, Example of a class

CONSTRUCTOR

Constructor, Types of Constructor, Default Constructor, Para-meterized Constructor Copy Constructor, Constructor overloading, Destructor

INHERITANCE

Inheritance, Base Class, Derived Class, Single Inheritance, Multiple, Hierarchical, Multilevel and Hybrid Inheritance, Visibility Mode, Containership, Overriding of function in inheritance, Virtual Base Class

DATA FILE HANDLING

File, Stream, Text file, Binary file, ofstream, ifstream, fstream class, Opening a file, Closing file, Input and output operation, File pointer and their manipulation

TEXT & BINARY FILE

Program to write, read, display, count number of characters, words,lines in text file. In binary file write, display records, search, delete and modify a record

POINTER

C++ Memory Map, Defining Pointer Variable, Pointer Arithmetics, Pointers and Arrays, Pointers and strings, Pointers to Structures, Dynamic memory, Memory Leak, Self Referential Structure

STATIC STACK

Stack as an Array, Defining member function PUSH() - to push data to the stack, POP() - to remove data from the stack.

CIRCULAR QUEUE

Array implemented circular queue containing data values, function to insert and delete data from the queue

DYNAMIC STACK

Defining structure of node for the linked stack, Defining member function PUSH() - to push a node to the stack which is allocated dynamically, POP() - to remove a node from the stack and release the memory.

DYNAMIC QUEUE

linked list implemented queue containing data values, function to insert and delete a number from the queue