27
C PROGRAMMING LANGUAGE HISTORY C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA. It is also called as 'Procedure oriented programming language.' C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications. The C language has following numerous features as: Portability Flexibility Effectiveness and efficiency Reliability Interactivity Execution of C Program : C program executes in following 4 (four steps). 1. Creating a program : An editor like notepad or wordpad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only. 2. Compiling the program : The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code. 3. Linking a program to library : The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension. 4. Execution of program : The final executable file is then run by dos command prompt or by any other software. 1

Basic C Language

Embed Size (px)

DESCRIPTION

Basic C lanugage

Citation preview

C Programming LanguageHISTORY

C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA. It is also called as 'Procedure oriented programming language.'

C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.

The C language has following numerous features as:

Portability

Flexibility

Effectiveness and efficiency

Reliability

InteractivityExecution of C Program :C program executes in following 4 (four steps).

1. Creating a program :

An editor like notepad or wordpad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only.

2. Compiling the program :

The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code.

3. Linking a program to library :

The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension.

4. Execution of program :

The final executable file is then run by dos command prompt or by any other software.

CHARACTER SET :

A character refers to the digit, alphabet or special symbol used to data represetation.

1. Alphabets : A-Z, a-z

2. Digits : 0-9

3. Special Characters :~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " '

4. White Spaces : Horizontal tab, Carriage return, New line, form feed

IDENTIFIER :

Identifier is the name of a variable that is made up from combination of alphabets, digits and underscore.

VARIABLE :

It is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored.

Rules for variables:

First character should be letter or alphabet.

Keywords are not allowed to use as a variable name.

White space is not allowed.

C is case sensitive i.e. UPPER and lower case are significant.

Only underscore, special symbol is allowed between two characters.

The length of identifier may be upto 31 characters but only the first 8 characters are significant by compiler.

(Note: Some compilers allow variable names whose length may be upto 247 characters. But, it is recommended to use maximum 31 characters in variable name. Large variable name leads to occur errors.)

KEYWORDS :Keywords are the system defined identifiers. All keywords have fixed meanings that do not change. White spaces are not allowed in keywords. Keyword may not be used as an identifier.It is strongly recommended that keywords should be in lower case letters.

There are totally 32(Thirty Two) keywords used in a C programming.

intfloatdoublelong

shortsignedunsignedconst

ifelseswitchbreak

defaultdowhilefor

registerexternstaticstruct

typedefenumreturnsizeof

gotounionautocase

voidcharcontinuevolatile

Escape Sequence Characters (Backslash Character Constants) in C:

C supports some special escape sequence characters that are used to do special tasks.

These are also called as 'Backslash characters'.

Some of the escape sequence characters are as follow:Character ConstantMeaning

\bBackspace

\tHorizontal Tab

\fForm feed

\aAlert (alerts a bell)

\rCarriage Return

\vVertical Tab

\?Question Mark

\'Single Quote

\''Double Quote

\\Backslash

\0Null

Structure of C Program

The basic structure of C program is as follow:

Document Section

Links Section (File)

Definition Section

Global variable declaration Section

void main()

{Variable declaration sectionFunction declaration sectionexecutable statements;}

Function definition 1

---------------------

---------------------

Function definition n

Document Section : It consists of set of comment lines which include name of a program, author name, creation date and other information.

Links Section (File) : It is used to link the required system libraries or header files to excute a program.

Definition Section : It is used to define or set values to variables.

Global variable declaration Section : It is used to declare global or public variable.

void main() : Used to start of actual C program. It includes two parts as declaration part and executable part.

Variable declaration section : Used to declare private variable.

Function declaration section : Used to declare functions of program from which we get required output.

Then, executable statements are placed for execution.Function definition section : Used to define functions which are to be called from main().

DECLARATION

A declaration associates a group of variables with a specific data type. All variables must be declared before they can appear in executable statementsIt consists of data type, followed by one or more variable names, ending with a semicolon.

EXPRESSIONAn expression represents a single data item, such as a number or a character. It consists of a single entity, such as a constant, a variable an array element or a reference to a function.It can also represent logical conditions that are either true or false.

STATEMENTSA statement causes the computer to carry out some action. There are three different classes of statements in C. They are expression statement, compound statement and control statement.

Expression Statement:

It consists of an expression followed by a semicolon. The execution of an expression statement causes the expression to be evaluated.

Compound Statement:It consists of several individual statements enclosed within a pair of braces { }. The individual statements themselves be expression statements, compound statements or control statements.

Control Statements:

They are used to create special program feature such as logical tests, loops and branches. It require that other statements be embedded within them.

Symbolic constants:

It is a name that substitutes for a sequence of characters. The characters may be numeric, characters or string constant. It is define at the beginning of the program.

Syntax:# define name

text

Name represents a symbolic name

Text represents the sequence of characters which is associated with the symbolic name.Data Types in C Language

A program contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C language is rich of data types. A C programmer has to employ proper data type as per his requirement.

C has different data types for different types of data and can be broadly classified as :

1. Primary data types

2. Secondary data types

Data Types in C

Primary data types consist following data types.

Integer types:

Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number.

To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.

Syntax: int ; like

int num1;

short int num2;

long int num3;

Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits of 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 and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.

Syntax: float ; like

float num1;

double num2;

long double num3;

Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:

Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from 128 to 127.

Syntax: char ; like

char ch = a;

Example: a, b, g, S, j.

Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float.

The void data type is usually used with function to specify its type. Like in our first C program we declared main() as void type because it does not return any value. The concept of returning values will be discussed in detail in the C function hub.

Secondary Data Types

* ArrayAn array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int.

* Pointers In this tutorial I am going to discuss what pointer is and how to use them in our C program. Many C programming learner thinks that pointer is one of the difficult topic in C language but its not...

* Structure

We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare...

User defined type declarationC language supports a feature where user can define an identifier that characterizes an existing data type. This user defined data type identifier can later be used to declare variables. In short its purpose is to redefine the name of an existing data type.

Syntax: typedef ; like

typedef int number;

C PROGRAMMING - OPERATORS

C programming language provides several operators to perform different kind to operations. There are operators for assignment, arithmetic functions, logical functions and many more. These operators generally work on many types of variables or constants, though some are restricted to work on certain types. Most operators are binary, meaning they take two operands. A few are unary and only take one operand.

Operators can be classified based on the type of operations they perform.

1. ARITHMETIC OPERATORS

Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and division (/) operations. In addition there is the modulus operator (%) which gives the remainder left over from a division operation.

Example:

#include

void main()

{

int a = 100;

int b = 3;

int c;

c = a + b;

printf( "a + b = %dn", c );

c = a - b;

printf( "a - b = %dn", c );

/* multiplication performed before call to printf() */

printf( "a * b = %dn", a * b );

c = a / b;

printf( "a / b = %dn", c );

c = 100 % 3;

printf( "a % b = %dn", c );

}

Output:

a + b = 103

a - b = 97

a * b = 300

a / b = 33

a % b = 1

When you use an operator on mixed types they will be implicitly converted into a common type before the operation is performed. The result of the operation will also be in the common type. The common type is derived using a few rules, but generally, a smaller operand is converted to the larger operand's type. If the result of the operation is assigned to another variable, the result is converted from the common type to the type of that variable.

2. RELATIONAL OPERATORS

Relational operators compare operands and return 1 for true or 0 for false. The following relational operators are available:

Symbol Meaning

< Less than

> Greater than

= Greater than or equal to

== Equal to

!= Not equal to

Example:

#include

#include

#include

void main()

{

int mynum;

int guess = -1;

char buffer[64];

srand( time(0) );

mynum = rand() % 100 + 1;

printf( "I have picked a number between 1-100.n" );

while( guess != mynum )

{

printf("Enter your guess: ");

if ( fgets( buffer, 64, stdin ) == NULL )

break;

guess = atoi( buffer );

if ( guess >= 101 || guess guess )

printf("Your guess is too low.n");

else if ( mynum < guess )

printf("Your guess is too high.n");

}

if ( guess == mynum )

printf( "You guessed correctly.n" );

}

Output:

I have picked a number between 1-100.

Enter your guess: 300

Your guess is out of bounds.

Enter your guess: 50

Your guess is too high.

Enter your guess: 25

Your guess is too low.

Enter your guess: 37

Your guess is too high.

Enter your guess: 31

Your guess is too high.

Enter your guess: 28

Your guess is too high.

Enter your guess: 26

You guessed correctly.

LOGICAL OPERATORS

The logical operators are || for a logical OR and && for a logical AND and ! for logical NOT. The AND and OR operate on two boolean values of true or false. In C, an expression that evaluates to 0 is false and an expression that evaluates to non-zero is true. These operators return 1 for true or 0 for false.

An AND operation is true only when both its operands are true. An OR operation is true if either one of its operands is true.

3. Assignment Operators

C has several assignment operators available - one simple assignment operator and several convenience assignment operators that combine arithmetic operations with assignment. The operators are as follows:

Symbol

Meaning

=

Assignment

*=

Multiply and assign

/=

Divide and assign

%=

Modulo and assign

+=

Add and assign

-=

Subtract and assign

The variable to be assigned to is the left operand. The right side is evaluated and its type converted to the type of the variable on the left and stored in the variable. The assignment operators return the value that was stored in the variable, making it possible to assign multiple variables on a single line.Syntax: identifier = expression;Example:

#include

void main()

{

int a = 8.3;

float b = 1.343f;

int c;

printf( "a = %d, b = %fn", a, b );

a += 2;

b *= a;

printf( "a = %d, b = %fn", a, b );

a %= 4;

b -= 0.43;

printf( "a = %d, b = %fn", a, b );

a = c = 5;

printf( "a = %dn", a );

a