Sie sind auf Seite 1von 21

Introduction to C

The root of the modern programming language is ALGOL (Algorithmic language),


introduced in the early 1960.ALGOL was the first computer language to use a block
structure.
In 1967 Martin Richard developed a language BCPL (Basic Combined Programming
Language), primarily for writing system program.
In 1970 Ken Thompson created a language using BCPL called B, at Bell laboratory.
The language B was modified by Dennis Ritchie and was implemented at Bell
Laboratories of USA in 1972 and the new language was named C.
In 1983, the American National Standard Institute established a standard specification of
C.
C is a simple and structure oriented programming language.

Why use C ?
C is often called a "Middle Level" programming language. This is not a reflection on its
lack of programming power but more a reflection on its capability to access the system's
low level functions. Most high-level languages (e.g. Fortran) provides everything the
programmer might want to do already built into the language. A low level language (e.g.
assembler) provides nothing other than access to the machines basic instruction set. A
middle level language, such as C, probably doesn't supply all the constructs found in
high-languages - but it provides you with all the building blocks that you will need to
produce the results you want!

C was initially used for system development work, in particular the programs that make-
up the operating system. Why use C? Mainly because it produces code that runs nearly as
fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems , Language Compilers, Assemblers ,Text Editors ,Print Spoolers
,Network Drivers ,Modern Programs ,Data Bases ,Language Interpreters ,Utilities

Features of C
a. Simple
b. Portability
c. Powerful
d. Platform dependent
e. Structure oriented
f. Case sensitive
g. Compiler based
h. Modularity
i. Middle level language
j. Syntax based language
k. Use of Pointers
a. Simple
Every c program can be written in simple English language so that it is very easy to understand
and developed by programmer.
b. Platform dependent
A language is said to be platform dependent whenever the program is execute in the same
operating system where that was developed and compiled but not run and execute on other
operating system. C is platform dependent programming language.
Note: .obj file of C program is platform dependent

c. Portability
C is highly portable this means that programs once written can be run on another machines with
little or no modification.
d. Powerful
C is a very powerful programming language, it have a wide variety of data types, functions,
control statements, decision making statements, etc.
e. Structure oriented
C is a Structure oriented programming language. Structure oriented programming language
aimed on clarity of program, reduce the complexity of code, using this approach code is divided
into parts using functions. So, it is easy to understand and modify
f. Modularity
In C programming we can break our code in subprogram.
g. Case sensitive
It is a case sensitive programming language. In C programming 'break and BREAK' both are
different.
h. Middle level language
C programming language can supports two level programming instructions with the combination
of low level and high level language that's why it is called middle level programming language.
i. Compiler based
C is a compiler based programming language that means without compilation no C program can
be executed. First we need compiler to compile our program and then execute.
j. Syntax based language
C is a strongly tight syntax based programming language. If any language follow rules and
regulation very strictly known as strongly tight syntax based language.
k. Pointers
Pointers is a variable which hold the address of another variable. C provides the feature of
pointers.
Structure of C Program
Document Section
The document section contains a set of comment lines, giving the name of the program, the
author details etc.
Pre-processor
Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor.
#include is the first word of any C program.
The main work of pre-processor is to initialize the environment of program, i.e to link the
program with the header file.
Commands used in preprocessor are called preprocessor directives and they begin with
# symbol.
Header file
Header file is a collection of built-in functions that help us to code easily in our program.
Header files contain definitions of functions and variables which can be incorporated into
any C program by pre-processor #include statement.
stdio.h is a header file in C used for input & output purpose.
It contains the predefined input function like scanf() and output function printf() etc.
main() function
The program starts execution from here.
When C program executes, the operating system will send resource and that resource is
picked by the main function. So without main function we cannot execute a C program.
Opening Curly Brace
The opening curly brace { states the beginning of the main function or starting of the
program.
The closing curly brace } states the end of the main function or end of the program.
All the statements between the two braces forms the function body. The function body
contains set of instructions to perform the given task.
Each expression statement must end with a semicolon (;)
First C Program
/* Name : Ram
Date : 22/08/2017
Description : Write a program to print Hello World
*/
#include<stdio.h> // preprocessor directive
int main() // main function
{
printf(Hello, World! \n"); // Printing here
return 0;
}

C Basic commands Explanation

#include <stdio.h> This is a preprocessor command that includes standard input output header
file(stdio.h) from the C library before compiling a C program
int main() This is the main function from where execution of any C program begins
{ This indicates the beginning of the main function.
/*_some comments_*/ whatever is given inside the command /* */ or // in any C program,
wont be considered for compilation and execution.
// some comment
printf(Hello,World! ); printf command prints the output onto the screen.
return 0; This command terminates C program (main function) and returns 0.
} This indicates the end of the main function.
Flow of C Program

fig Flowchart Of C Program Execution


C - Environment Setup
Local Environment Setup
If you want to set up your environment for C programming language, you need the following
two software tools available on your computer
1. Text Editor
2. The C Compiler.
1. Text Editor
This will be used to type your program.
Examples : Windows Notepad, gedit, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For
example, Notepad will be used on Windows, and vim or vi or gedit can be used on Linux
or UNIX.
The files you create with your editor are called the source files and they contain the
program source codes.
The source files for C programs are typically named with the extension ".c".
2. The C Compiler
The compiler compiles the source codes into final executable programs
Example : GCC C compiler

Compile and Execute C Program


Open a text editor and write the code.
Save the file as hello.c
Open a command prompt and go to the directory where you have saved the file.
Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next line
and would generate a.out executable file.
Now, type ./a.out to execute your program.
You will see the output Hello, World ! printed on the screen.

Writing style of C program


Lowercase letters are used for statements.
It Uses beginning and ending curly braces for functions.
Each C statement should end with a semicolon.
User defined functions are generally placed immediately after the main(), although
they may appear in any order.
The message to be displayed is enclosed within a pair of double quotes.
Use of more than one main() is illegal.
Data types cant be used as variable name.

Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant,
a string literal, or a symbol.
In C Programming punctuation,individual words,characters etc are called tokens.
For example, the following C statement consists of five tokens
Elements of C
Every language has some basic elements and grammatical rules.
The basic elements include:

1. Character Set
Character sets affect the fundamental part of the program code, the storage and transmission of
data and the logic with which you manipulate text. A C compiler may use any character set that
includes at least following character sets.
1. 52 alphabetic characters (A-Z and a-z)
2. 10 decimal digits (0-9)
3. 29 special characters (! # % ^ & * ( ) - _ + = ~ [ ] , . : / ?).
4. 5 formatting characters (backspace, horizontal tab, vertical tab, form feed and carriage
return). These are treated as spaces.
5. Dollar ($) and at @ are also used but required by the standard.
White Space
It includes blanks (space character, horizontal tab, vertical tab, end of line, form feed and carriage
return and comments. White spaces are ignored by compiler except when required to separate
tokens or when used in a character or string constant. These are used freely by the programmer to
make the program easy for a person to read.
The characters that are used in C programs are given below:
Alphabets
A,B,C,.,Z
a,b,c,.,z
Digits
0,1,2,3,4,5,6,7,8,9
Special characters

2. Escape sequence
Some characters such as newline, tab and backspace cant be printed like other normal
characters.
C supports the combination of backslash(\) and some characters from the C character
set to print these characters.
These character combinations are known as escape sequences and are represented by two
characters.

Escape Meaning Explanation


Sequence

\n newline moves the cursor to beginning of the current line


\t horizontal tab moves the cursor to the next horizontal tab position
\v vertical tab moves the cursor to the next vertical tab position
\\ backslash presents a character with backslash(\)
\0 null Null
\ Single quote Printing a Single quotation mark
\ Double quote Printing a Double quotation mark

\b backspace moves the cursor to the previous position


2.1. Tab : \t Character
It is Horizontal Tab
Takes Control 8 spaces ahead in Borland CC++ 3.0
Compiler
After Execution of Printf :
Hello World

2.2. New Line Character : \n Character


It is New Line Character
Takes Control to new Line
Cursor Position After Execution of Printf :
Hello
World

2.3. Backslash : \b Character


It is Backslash Character
Takes Control one position back
After Execution of Printf :
HellWorld
Note : on o character from Word Hello

2.4. Carriage Return : \r Character


It is Carriage Return Character
Takes Control to First Position in the Line

After Execution of Printf :


World
Note : on Hello character from Word HelloWorld

2.5. Double quote: \ Character


It is a double quote character
Double quote is printed
After Execution of Printf :
HelloWorld
Note : on character from Word HelloWorld
3. Delimiters
Delimiters are used for syntactic meaning in C.
These are as given below:

Symbol Name Description

: Colon Used for labels


; Semicolon End of statement
# Hash Pre Processor Directive
, Comma Variable Separator
{} Curly Braces Scope of statement
[] Square Bracket Used for array declaration

4. Keywords
These are certain reserved words called keywords, that have standard,
Predefined meaning in C.
These keywords can be used only for their intended purpose.
The keyword have fixed meaning and there meaning cannot be changed.
They are written in lowercase letter.
Total 32 keywords are there.

ANSI C keywords:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
5. Identifiers
Identifiers are names given to various programs elements, such as variables, functions and arrays.
Identifier consists of letters and digits, in any order, except that the first character must be letter.
Rules for Identifier
The first character of an identifier must be an alphabet (or underscore).
It must not start with a digit.
Must consist of only letters, digits or underscore.
Cannot use a keyword.
Must not contain whitespace.
Both upper case & lower case letters are permitted not interchangeable.
Example:
valid
X, y12, sum_1, _temp, name
Invalid
4th, -x, -sum, -temp, order-no, order no , rec#

6. Data type
Defines a domain of allowed values and the operations that can be performed on those
values.
Data type is a keyword used to identify type of data.
Data types are used for representing the input of the user in the main memory (RAM) of
the computer.
What is common between a suitcase and a bottle ?
They all are containers.
They store specific type of thing.
The program stores the values being supplied by the user, so
we need containers, which can store values in them.
These containers are referred to technically as variables.
Similarly, every variable is created to store specific type of data, which is called
data type of variable.
Basic /Fundamental data types

There are 5 basic data types in C such as:


1. int 2. float 3. double 4. char 5. Void
There are a number of modifiers/qualifiers that can be applied to these data types such as:
a. Size qualifier :- Short and long
b. Sign qualifier :- signed and unsigned
NOTE : When the qualifier is unsigned is used the number is always positive.

Integer data type:


Integer data type allows a variable to store numeric values.
int keyword is used to refer integer data type.
The storage size of int data type is 2 or 4 or 8 byte.
It varies depend upon the processor in the CPU that we use.
If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for int data
type. Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int datatype.
int (2 byte) can store values from -32,768 to +32,767
int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
If you want to use the integer value that crosses the above limit, you can go for long int
and long long int for which the limits are very high
Note:
We cant store decimal values using int data type.
If we use int data type to store decimal values, decimal values will be truncated and we will
get only whole number.
In this case, float data type can be used to store decimal values in a variable.

Float data type:


Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the CPU
as int data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type
Double data type:
Double data type is also same as float data type which allows up-to 10 digits after
decimal.
The range for double datatype is from 1E37 to 1E+37.

Char data type:


Character data type allows a variable to store only one character.
Storage size of character data type is 1. We can store only one character using character
data type.
char keyword is used to refer character data type.
For example, A can be stored using char datatype. You cant store more than one
character using char data type.
void data type:
void type means no value. This is usually used to specify the type of functions.
void data type is used when one doesnt want to return any value from the function

Example of Basic Data Type

#include <stdio.h>
NOTE : %.2f means that the variable to be
int main() printed will be of type float and '.2' means that
{ the number rounded to only two decimal places
int sum = 100; will be printed. We can use any number to
char letter = 'Z'; which we have to round our decimal value.
float set1 = 23.567;
double num2 = 11e+23;

printf("Integer variable is %d \n", sum);


printf("Character is %c \n", letter);
printf("Float variable is %.2f \n", set1);
printf("Double variable is %e \n", num2);
return 0;
}

Data type modifiers in C


In C language Data Type Modifiers are keywords used to change the properties of current
properties of data type.

Data type modifiers are classified into following types.


1. long
2. short
3. unsigned
4. Signed

Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.

For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte

Size qualifier long


This can be used to increased size of the current data type to 2 more bytes, which can be applied
on int or double data types.
For example int occupy 2 byte of memory if we use long with integer variable then it occupy 4
byte of memory
SYNTAX : long int a; ----------------> by default which represent long int.

Size qualifier short


In general int data type occupies different memory spaces for a different operating system; to
allocate fixed memory space short keyword can be used
SYNTAX : short int a; -----------> occupies 2 byte of memory space in every operating
system

Sign qualifier unsigned


This keyword can be used to make the accepting values of a data type is positive data type

Sign qualifier Signed


This keyword accepts both negative or positive value and this is default properties or data type
modifiers for every data type.

Note: in real time no need to write signed keyword explicitly for any data type
Size and range of Datatypes
Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

Derived data types


These data type are derived from fundamental data type.
Variables of derived data type allow us to store multiple values of same type in one
variable but never allows to store multiple values of different types.
These are the data type whose variable can hold more than one value of similar type.
In C language it can be achieve by array.

User defined data types


User defined data types related variables allows us to store multiple values either of same
type or different type or both.
This is a data type whose variable can hold more than one value of dissimilar type, in C
language it is achieved by structure
7. Constants
A data item which does not change it value during the execution of a program is known as
constants. In C, constants can be defined in any of the various basic data types. C provides
several types of constants.

Numeric constants
Numeric constants of numeric digits, they may or may not have decimal point (.).
These are rules for defining numeric constants
Numeric constant should have at least one digit.
No comma or space is allowed within the numeric constants.
Numeric constants can either be positive or negative but default sign is always positive.
There are two types of numeric constants
Integer Constant
Integer constants are whole numbers, which have no decimal point (.). There are three types of
integer constants based on different number systems. These constants are
a) Decimal constants 0,1,2,3,4,5,6,7,8,9 (base 10)
b) Octal constants 0,1,2,3,4,5,6,7 (base 8)
c) Hex decimal constants 0,1,2,3,4,5,6,7,8,9 A,B,C,D,F (base 16)
Valid integer constant: 123, 3705, 0, -25
Invalid integer constant: 2.5, 3#5, 98 5
Real Constants
The numbers are containing fractional parts like 12.45 are called real (or floating point) constant.
The real constants can be written in two forms
a) Fractional form: In this form, the numbers has a decimal point.
Example: +325.35, 42.0,-21.5
b) Exponential form: The real number can be expressed by exponential notation. The general
form
mantisa@exponent
Constructing real constant in exponential form:
The mantissa part and the exponential part should be separated by a letter e or E.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
Example: 0.65e4, 22e-3, 2.11E3
Single Character Constants
A single character constant (or simply) character constant contains a single character enclosed with
a pain of single quote marks. Every character constant has a unique integer value associated with
it. This integer is the numeric value of the character in the machines character code. If the machine
is using ASCII (American Standard Code for Information Interchange), then the character A
represents integer value 65. Each character constant represents an integer value. So, it is possible
to perform arithmetic operations on character constant. Examples of character constants are
a Y *
Some ASCII values are
A-Z ASCII value (65-90)
a-z ASCII value(97-122)
0-9 ASCII value (48-57)
; ASCII value (59)
String Constants
A string constant has zero, one or more than one characters. The characters may be letters,
numbers, special characters and blank space. A string constant is enclosed within double quotes (
). At the end of string, \0 is automatically places b the compiler. Some examples of string
constants are
imedia 463 5 X

Constant Syntax and Example

SYNTAX : const datatype variable = value;


EXAMPLE : const int height = 100

#include<stdio.h>
int main()
{
const int a=10;
printf("%d",a);
a=20; // gives error you can't modify const
return 0;
}
Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The character may
represent a numeric constant, a character or named constant.
Note: A symbolic constant is required if we want to use a constant several times.
For example: If we have to use the constant 3.14159265 at many places in our program, than we can give
it a name PI and use this name instead of writing the constant value everywhere.
These constants are generally defined at the beginning of the program as
#define name value
name: is the symbolic name for the constant , and is generally written in uppercase letters
Value: can be numeric, character and string constant.
#define statement is a preprocessor compiler directive.

Rules for writing Symbolic Constant


1. Symbolic names have same form as variable name.
2. No blank spaces between # (pound sign) and the word define is permitted.
3. # must be the first character in the line.
4. A blank space in required between #define and symbolic name and between the symbolic
name and the constant.
5. #define statement ends with semicolon(;) .
6. Symbolic value should not be assigned any other value within the program.
7. Its data type depends on the type of constant.
8. It may appear anywhere in the program before it is referenced. But good practice, to place
them beginning of the program.

Some examples of symbolic constants are

# define MAX 75
# define P1 3.14159625
# define Ch Y
# define NAME tapan

8. Variable
Variable is an identifier which holds data or another one variable.
It is an identifier whose value can be changed at the execution time of program.
It is used to identify input data in a program.
The variables need to be declared before their use.

Why declare a variable?


We declare a variable so that the compiler can be able to know what are the names of the
variables and what type of variables they are i.e., what type of values can they contain.
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Syntax : Datatype variable_name;
Example : int a;

If no input values are assigned by the user than system will gives a default value called
garbage value.

Garbage value
Garbage value can be any value given by system.
This is a disadvantage of C programming language and in C programming it can overcome
using variable initialization

Initialization of Variables
When a variable is declared it contains undefined value commonly known as garbage
value.
If we want we can assign some initial value to the variable during the declaration itself.
This is called initialization of the variable.
It is the process of allocating sufficient memory space with user defined values.
Syntax : Datatype variable_name = value;
Example : int b = 20;

Variable assignment
Syntax : variable_name = value;
Example : b = 20;

Example :
int a = 20;
int b;
b = 25; // directly assign variable
b = a; //assigned variable in term of variable 35

b = a + 15; //assigned variable in term of expression

Scope of the variable


In C language, a variable can be either of global or local scope.
Global variable
Global variables are defined outside of all the functions, generally on top of the program. The
global variables will hold their value throughout the life-time of your program.
Local variable
A local variable is declared within the body of a function or a block. Local variable only use
within the function or block where it is declare.
EXAMPLE
#include<stdio.h>
int a; // global variable
int main()
{
int b; // local variable
a=10, b=20;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
return 0;
}

9. Expressions
An expression is a combination of operators, constants, variables and function calls. The
expression can be arithmetic, logical or relational .
Example:
x+y
a=b+c
a>b
a==b
Func(a,b)

10. Statements
In a C program instructions are written in the form of statements.
Statements can be categorized as :
i. Expression statements
ii. Compound statements
iii. Selection statements ( if, if.. .else, switch)
iv. Iterative statements (for, while, dowhile)
v. Jump Statements (goto, continue, break, return)
vi. Label statements (case, default, label statement used in goto)

11.Comments
Comments are used for increasing readability of the program.
They explain the purpose of the program and are helpful in understanding the program.
In 'C' language two types of comments are possible
Single line comments
Multiple line comments
Single line comments
Single line comments can be provided by using
//....................
Multiple line comments
Multiple line comments can be provided by using /*......................*/

Error
Error is a abnormal condition whenever it occurs execution of the program is stopped these are mainly
classified into following types.
Compile time error
Run time error
Compile time error
If any error is generated at the time of compilation it is known as compile time error, in general these
are raised while break down the rules and regulation of programming language.
Example:
Missing semicolon, writing keyword in upper case, writing variable declaration, initialization after calling
clrscr() function. Compile time errors also known as syntax errors.

Compile time error a


is not defined but
used in the program.

Run time error


If any error is generated at run time is known as runtime error, in general these are raised because of
writing wrong logics in the program.
Example
Calling function without existence, divide by zero.
int a=10,b;
b = a / 0 ; ------> infinite
Here out of range of int data type. In general it is very difficult to identify logical error in C language, to
overcome this problem exception handling was introduced in object oriented programming language.

Warning
Warning is also an abnormal condition but whenever it occurred execution of program will never be
stopped.

Note: In C language warning can be neglected but error cannot be neglected.

Das könnte Ihnen auch gefallen