Saturday, May 16, 2009

example program with c++

#define N 100 //creates a variable N with constant value 100
#define A 2 //creates a variable A with constant value 2

main() //start of the program
{
int a; //variable a declaration
a = A; //assigns value 2 to a

while (a < N) //while value of a is less than N
{ //evaluate or do the following
printf(“%d \n”,a); //print the current value of a
a *= a; //shorthand form of a = a * a
} //end of the loop
} //end of the program

Integer Arithmetic Floating point arithmetic

Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers. Then the integer operation leads to the following results.

x + y = 32
x – y = 22
x * y = 115
x % y = 2
x / y = 5

In integer division the fractional part is truncated.



Floating point arithmetic
When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands.

Let x = 14.0 and y = 4.0 then

x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50



Mixed mode arithmetic
When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus 15/10.0 = 1.5

C Programming - Operators

In this tutorial you will learn about Operators, Arithmetic operators, Relational Operators, Logical Operators, Assignment Operators, Increments and Decrement Operators, Conditional Operators, Bitwise Operators and Special Operators.

Examples of arithmetic operators are
x + y
x - y
-x + y
a * b + c
-a * b

etc., here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which evaluates the remainder of the operands after division. Example

#include //include header file stdio.h void main() //tell the compiler the start of the program { int numb1, num2, sum, sub, mul, div, mod; //declaration of variables

scanf (“%d %d”, &num1, &num2); //inputs the operands sum = num1+num2; //addition of numbers and storing in sum.

printf(“\n Thu sum is = %d”, sum); //display the output sub = num1-num2; //subtraction of numbers and storing in sub.

printf(“\n Thu difference is = %d”, sub); //display the output mul = num1*num2; //multiplication of numbers and storing in mul.

printf(“\n Thu product is = %d”, mul); //display the output div = num1/num2; //division of numbers and storing in div.

printf(“\n Thu division is = %d”, div); //display the output mod = num1%num2; //modulus of numbers and storing in mod.

printf(“\n Thu modulus is = %d”, mod); //display the output }

Wednesday, May 13, 2009

Declaring Variable as Constant

The values of some variable may be required to remain constant through-out the program. We can do this by using the qualifier const at the time of initialization.

Example:

Const int class_size = 40;

The const data type qualifier tells the compiler that the value of the int variable class_size may not be modified in the program.


Volatile Variable

A volatile variable is the one whose values may be changed at any time by some external sources.

Example:

volatile int num;

The value of data may be altered by some external factor, even if it does not appear on the left hand side of the assignment statement. When we declare a variable as volatile the compiler will examine the value of the variable each time it is encountered to see if an external factor has changed the value.

Declaration of Storage Class

Variables in C have not only the data type but also storage class that provides information about their location and visibility. The storage class divides the portion of the program within which the variables are recognized.

auto : It is a local variable known only to the function in which it is declared. Auto is the default storage class.

static : Local variable which exists and retains its value even after the control is transferred to the calling function.

extern : Global variable known to all functions in the file

register : Social variables which are stored in the register.



Defining Symbolic Constants
A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value. The general form of a symbolic constant is

# define symbolic_name value of constant

Valid examples of constant definitions are :

# define marks 100
# define total 50
# define pi 3.14159

These values may appear anywhere in the program, but must come before it is referenced in the program.

It is a standard practice to place them at the beginning of the program.

User defined type declaration

In C language a user can define an identifier that represents an existing data type. The user defined datatype identifier can later be used to declare variables. The general syntax is

typedef type identifier;

here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to the data type.

Example:

typedef int salary;
typedef float average;

Here salary symbolizes int and average symbolizes float. They can be later used to declare variables as follows:

Units dept1, dept2;
Average section1, section2;

Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2 are indirectly float data type.

The second type of user defined datatype is enumerated data type which is defined as follows.

Enum identifier {value1, value2 …. Value n};

The identifier is a user defined enumerated datatype which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this ‘new’ type as below.

enum identifier V1, V2, V3, ……… Vn

The enumerated variables V1, V2, ….. Vn can have only one of the values value1, value2 ….. value n

Example:

enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;

Floating point types and void type

Floating Point Types :
Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space.



Void Type :
Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function.

data type in C : Integer Type

Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values.

Data Types in C Programming Language

In this tutorial you will learn about C language data types, Primary data type, Integer Type, Floating Point Types, Void Type, Character Type, Size and Range of Data Types on 16 bit machine, derived data type, Declaration of Variables, User defined type declaration, Declaration of Storage Class, auto, static, extern, register, Defining Symbolic Constants, Declaring Variable as Constant and Volatile Variable

A C language programmer has to tell the system before-hand, the type of numbers or characters he is using in his program. These are data types. There are many data types in C language. A C programmer has to use appropriate data type as per his requirement.

C language data types can be broadly classified as
Primary data type
Derived data type
User-defined data type

Variables in C Language

A variable is a value that can change any time. It is a memory location used to store a data value. A variable name should be carefully chosen by the programmer so that its use is reflected in a useful way in the entire program. Variable names are case sensitive. Example of variable names are

Sun
number
Salary
Emp_name
average1

Any variable declared in a program should confirm to the following
1. They must always begin with a letter, although some systems permit underscore as the first character.
2. The length of a variable must not be more than 8 characters.
3. White space is not allowed and
4. A variable should not be a Keyword
5. It should not contain any special characters.

Examples of Invalid Variable names are
123
(area)
6th
%abc

Backslash Character Constants [Escape Sequences]

Backslash character constants are special characters used in output functions. Although they contain two characters they represent only one character. Given below is the table of escape sequence and their meanings.

Constant and Meaning
'\a' Audible Alert (Bell)
'\b' Backspace
'\f' Formfeed
\n' New Line
'\r' Carriage Return
'\t' Horizontal tab
'\v' Vertical Tab
'\'' Single Quote
'\"' Double Quote
'\?' Question Mark
'\\' Back Slash
'\0' Null

Real Constants in C Language

Real Constants consists of a fractional part in their representation. Integer constants are inadequate to represent quantities that vary continuously. These quantities are represented by numbers containing fractional parts like 26.082. Example of real constants are

0.0026
-0.97
435.29
+487.0

Real Numbers can also be represented by exponential notation. The general form for exponential notation is mantissa exponent. The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer number with an optional plus or minus sign.

Integer Constants in C Language

An integer constant is a sequence of digits. There are 3 types of integers namely decimal integer, octal integers and hexadecimal integer.

Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or - sign. Spaces, commas and non digit characters are not permitted between digits. Example for valid decimal integer constants are

123
-31
0
562321
+ 78

Some examples for invalid integer constants are
15 750
20,000
Rs. 1000

Octal Integers constant consists of any combination of digits from 0 through 7 with a O at the beginning. Some examples of octal integers are

O26
O
O347
O676

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid hexadecimal integers are

OX2
OX8C
OXbcd
Ox

constants and identifiers must conform to following

The identifiers must conform to the following rules.

1. First character must be an alphabet (or underscore)
2. Identifier names must consists of only letters, digits and underscore.
3. A identifier name should have less than 31 characters.
4. Any standard C language keyword cannot be used as a variable name.
5. A identifier should not contain a space.

ConstantsA constant value is the one which does not change during the execution of a program. C supports several types of constants.
1. Integer Constants
2. Real Constants
3. Single Character Constants
4. String Constants

Keywords and Identifiers

Every word in C language is a keyword or an identifier. Keywords in C language cannot be used as a variable name. They are specifically used by the compiler for its own purpose and they serve as building blocks of a c program.

The following are the Keyword set of C language.

auto ,else ,register ,union
.break .enum .return ,unsigned
.case .extern .short .void
.char .float .signed .volatile
.const .for .size of .while
.continue .goto .static .
.default .if .struct .
.do .int .switch .
.double .long .typedef .

C Character-Set

Letters Digits
Upper Case A to Z 0 to 9
Lower Case a to z

Special Characters
, .Comma

& .Ampersand


. .Period

^ .Caret
; .Semicolon

* .Asterisk

: .Colon

- .Minus Sign

? .Question Mark

+ .Plus Sign


'.Aphostrophe

< .Opening Angle (Less than sign)


".Quotation Marks

> .Closing Angle (Greater than sign)


!.Exclaimation Mark

(.Left Parenthesis


| .Vertical Bar

).Right Parenthesis


/ .Slash

[ .Left Bracket


\.Backslash

].Right Bracket


~.Tilde

{.Left Brace


-.Underscore

} .Right Bracket

$.Dollar Sign

# .Number Sign

% .Percentage Sign

Constants and Variables in C Language

In this tutorial you will learn about Character Set, C Character-Set Table, Special Characters, White Space, Keywords and Identifiers, Constants, Integer Constants, Decimal Integers, Octal Integers, Hexadecimal integer, Real Constants, Single Character Constants, String Constants, Backslash Character Constants [Escape Sequences] and Variables.

Instructions in C language are formed using syntax and keywords. It is necessary to strictly follow C language Syntax rules. Any instructions that mis-matches with C language Syntax generates an error while compiling the program. All programs must confirm to rules pre-defined in C Language. Keywords as special words which are exclusively used by C language, each keyword has its own meaning and relevance hence, Keywords should not be used either as Variable or Constant names.

Character Set
The character set in C Language can be grouped into the following categories.

1. Letters
2. Digits
3. Special Characters
4. White Spaces

White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers.

Basic structure of C programs

.....Documentation Section
.....
.....Link Section
.....
.....Definition Section
.....
.....Global declaration Section
.....
.....main() function section
.....{
..........Declaration Section
.....
..........Executable Section
.....}
.....Sub-program Section
.....function1
.....{
..........Statements
.....}
.....function2
.....{
..........Statements
.....}
.....function3
.....{
..........Statements
.....}

The documentation section consists of a set of comment lines giving the name of the program, the author and other details such as a short description of the purpose of the program.

The link section provides instructions to the compiler to link functions from the system library.

The definition section defines all the symbolic constants. The variables can be declared inside the main function or before the main function.

Declaring the variables before the main function makes the variables accessible to all the functions in a C language program, such variables are called Global Variables.

Declaring the variables within main function makes the usage of the variables confined to the main function only and it is not accessible outside the main function.

Every C program must have one main function. Enclosed in the main function is the declaration and executable parts.

In the declaration part we have all the variables.

There is atleast one statement in the executable part.

The two parts must appear between the opening and closing braces

The sub-program section contains all the user-defined functions that are called in the main function.

User-defined functions are generally placed immediately after the main function although they may appear in any order.

How To Executing a C Program

The following basic steps is carried out in executing a C Program.
1. Type the C lanuage program.
2. Store the program by giving a suitable name and following it with an extension .c
3. Compile the program
4. Debug the errors if any, that is displayed during compile.
5. Run the program.

Sample program of C Language

Sample program
Printing a message
Consider the following message

#include
main()
{
...../* Printing begins here */
.....printf (“C is a very good programming language.”);
...../* Printing ends here */
}

The first line is a preprocessor command which adds the stdio header file into our program. Actually stdio stands for standard input out, this header file supports the input-output functions in a program.

In a program, we need to provide input data and display processed data on standard output – Screen. The stdio.h header file supports these two activities. There are many header files which will be discussed in future.

The second line main() tell the compiler that it is the starting point of the program, every program should essentially have the main function only once in the program. The opening and closing braces indicates the beginning and ending of the program. All the statements between these two braces form the function body. These statements are actually the C code which tells the computer to do something. Each statement is a instruction for the computer to perform specific task.

The /* .... */ is a comment and will not be executed, the compiler simply ignores this statement. These are essential since it enhances the readability and understandability of the program. It is a very good practice to include comments in all the programs to make the users understand what is being done in the program.

Overview of C programming language

Overview of C
C is a programming language. It is most popular computer language today because it is a structured high level, machine independent language. Programmers need not worry about the hardware platform where they will be implemented.

Dennis Ritchie invented C language. Ken Thompson created a language which was based upon a language known as BCPL and it was called as B. B language was created in 1970, basically for unix operating system Dennis Ritchie used ALGOL, BCPL and B as the basic reference language from which he created C.

C has many qualities which any programmer may desire. It contains the capability of assembly language with the features of high level language which can be used for creating software packages, system software etc. It supports the programmer with a rich set of built-in functions and operators. C is highly portable. C programs written on one computer can run on other computer without making any changes in the program. Structured programming concept is well supported in C, this helps in dividing the programs into function modules or code blocks.

C Language

Developed originally at Bell Labs by Ken Thompson and Dennis Ritchie in the second half of the 1980’s, the C Language has become a high-level programming language responsible for almost all operating systems of today. Together with the object-oriented successor of C, C++, these two languages have become commercial software’s first choice in programming language. UNIX runs on C Language and is becoming commercially acceptable on a mass scale.

Venture capital seems to be financing C Language-based software development as it is gaining interest in the job market and receiving support from large corporations and big business markets. Communications and Information Technology are some of the employment opportunities available for the expert C Language programmer.

Like any language learning exercise, the C Language begins with Variables and Constants. These Variables and Constants of basic data types create words and sentences of C, forming the C programming language. A set of instructions and rules for writing in the C Language exists, as is part of any computer programming language. These instructions are explained in online tutorials defining Statements, Expressions, Operators, Managing Input/Output Operations, Strings, Arrays, Functions, Pointers, Dynamic Memory allocation and more.

Using Preprocessor directives, Macros, define identifier string, Simple macro substitution, Macros as arguments, Nesting of macros, Un-defining a macro and File inclusion, the C Language programmer becomes familiar with the terms and functions of this complex programming language. The preprocessor in the C Language is examined in tutorials that describe modifying and reading C Language and discuss efficiency and portability.

Saturday, May 2, 2009

C++ Training

you can download source code and studies in C language in my blog