2Introduction_to_C
2Introduction_to_C
Introduction to C Language
Introduction to C
C is a general purpose programming language developed by Dennis Ritchie at A T & T Bell
laboratories in 1972.
C is closely related to UNIX system and many of the important ideas are taken from “BCPL”
(Basic Combined Programming Language) developed by Martin Richards and “B” language.
C provides variety of data types, derived data types like pointers, arrays, structures and unions.
It also provides control flow constructions like conditional and looping constructs etc..,
Why C?
Generally computer understands only binary data i.e., 0’s and 1’s.
Writing and understanding programs in binary was very difficult and time consuming.
To overcome this middle level language was introduced; the user feels comfortable in writing the
program.
Many middle levels languages are available like C, C++ etc..
Even though the program is written in middle level language, the code has to be converted to
machine language so that computer can execute it for which we make use of compiler.
Advantages/Features of C Language
There are many features which attracted programmers for the usage of C. They are
1. Simple and Portable: it gives programmer access to all functions of the machine and can
work on different kinds of computers.
2. Powerful and Flexible: most of the functionalities like UNIX is written in C. The compiler
and interpreter is also written in C language.
3. Modularity: C is a structured programming language which mainly deals with the
procedures. It is also termed as procedure oriented language.
4. Efficient: C is more efficient which increases the speed of execution and management of
memory compared to low level languages.
5. Programmer oriented: It has many data types and flexible control structure which gives
access to hardware.
6. Other features include
Machine independent
No need to worry about machine details.
Versions of C:
The main is ANSI C (accepted by American National Standards Institute) under which we have
Lattice C Turbo C Tiny C
Microsoft C Borland C Etc….
Quick C Small C
Developing Programs in C:
1. Creating the Program :
The source program can be written or modified using editor and can be saved with
the extension of .C
2. Compiling the program.
Where the program is checked for the Syntax and Semantics of the language and
reports the errors to the user. These errors have to be corrected by the users in the source
program.
3. Executing the Program.
Once the error free code is generated after the compilation process, the program
can be executed with valid inputs by linking to the required header files.
For the successful execution of the C Program some of the software components are
required they are:
Operating System. Assembler.
Text Editors. Loader.
Compilers. Linker.
On the successful execution of the C Program the following files are created:
1. Pgm.C: Contains source code of the program saved in .C extension.
2. Pgm.txt: Contains text format of the source code stored in .txt a notepad file.
3. Pgm.obj: Contains the object code of source program in terms of 0’s & 1’s.
4. Pgm.exe: An Executable file generated after successful compilation.
5. Pgm.bak: An backup file for the Pgm.C
2 Mr.Sukruth Gowda M A, Assistant Professor
Introduction to C 2019
Typical steps for Entering, Compiling and Executing C programs
C Source Code
Preprocessed Code
Assembly Code
Libraries and
other object
modules Object Code
Executable Code
Such as Hard disk as an
Executable image.
Syntax Error: errors due to the fact that the syntax of the language is not respected.
Example: int a=20 // Error: Statement missing (;)
Semantic Error: errors due to the improper use of program statements.
Example 1.int i; // Error: Static semantic error @ compile time.
i++; // Error: Variable “i” is not initialized.
Note:
Debugging: The process of identifying the errors and correcting it.
Source Code: The text of a program that a user can read, modify and given as a input for the
C compiler.
Object Code: Translated code generated by the compiler by taking source code as the input
and computer can executes it directly.
Compile Time: The time during which your program is being compiled.
Run Time: The time during which your program is executing.
Short Cut keys:
Menu: F10.
Saving: Alt + F2.
Opening the Existed program: F3.
Compilation: F9.
Execution: Ctrl + F9.
To see the previously Executed screen: Alt + F5.
Single Tab View: F5.
To Maximize the Screen: Alt + Enter.
Concepts of C Programming
Structure of C Program
Comments/Documentation Section
Preprocessor Directives
Global Declaration Section
void main( ) [Program Header]
{
Local Declaration part
Execution part
Statement 1
------------
------------
Statement n
}
User Defined Functions
Comments/Documentation Section
Describes the program, which helps in understanding the program easily.
The comments are not mandatory.
The comment are may be of:
Single line Comment:
Description is written in single line with the delimiter //.
Example: //Program to multiply two numbers.
Multi line Comment:
It is written in more than one line.
Begins with /* and ends with */. The symbols /* and */ are called comment line
delimiters
Example :
/*Program to find the roots of the Quadratic equation on checking for value of a not
equal to 0 and condition for roots are real and equal, real and distinct & Imaginary*/
Note: Comments are ignored by C compiler, i.e. everything within comment delimiters
C Programming Concepts
A program is a group of instructions given by the programmer to perform a specific task.
To achieve programming there are many basic components of programming that has to be
learnt.
Character set of C language
The C language includes the characters.
Alphabets(lowercase a-z, Uppercase A-Z)
Digits (0-9)
Special Symbols( ~ ‘ ! @ # % & * () - + / $ = \ { } [ ] : ; “ “ ? etc)
C- Tokens
Tokens are the smallest individual units of C program.
A token is collection of characters.
Some of the C- Tokens available in C are:
Keywords
Words which have predefined / fixed meanings are called keywords.
These are basic building blocks of C program statements.
The meaning of keywords will be known to computer no new name or meaning can be defined
for it.
There are totally 32 keywords supported in C they are:
Auto double if Static
break else int Struct
case enum long Switch
char extern near Typedef
const float register Union
continue for return Unsigned
default while short Void
Do goto signed While
Identifiers or Variables
Identifiers are the name given to the program element.
The program element may be identified as variables, functions and arrays etc..,
These are user defined names and do not have fixed meaning.
It is name given to computer memory location.
Variables – Variables are the identifiers, the named memory location whose value changes on
program execution.
Rules for identifiers/variables
First character must be an alphabet or an underscore(_)
First character is followed by any number of letters or digits.
Only first 31 characters are significant
Keywords cannot be used as identifier / variable.
Must not contain blank space/white space
Must contain only alphabets, digits and one special symbol underscore ( _ )
Two successive underscore is not permitted
Ex:-
india Valid
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid
_ _india not valid as it contains successive underscore
06india not valid as it starts from digits
Int not valid since int is a keyword
india 06 not valid since there is space between india and 06
india@06 not valid since @ is not allowed
String Constant
A character string, a string constant consists of a sequence of characters enclosed in double
quotes.
A string constant may consist of any combination of digits, letters, escaped sequences and
spaces.
Note that a character constant ۥA’ and the corresponding single character string constant "A"
are not equivalent.
The string constant "A" consists of character A and \0. However, a single character string
constant does not have an equivalent integer value. It occupies two bytes, one for the ASCII
code of A and another for the NULL character with a value 0, which is used to terminate all
strings.
Valid String Constants: -
"W"
"100"
"24, Kaja Street"
Invalid String Constants: -
"W the closing double quotes missing
Raja" the beginning double quotes missing
Rules for Constructing String constants
A string constant may consist of any combination of digits, letters, escaped sequences
and spaces enclosed in double quotes.
Every string constant ends up with a NULL character which is automatically assigned
(before the closing double quotation mark) by the compiler.
Data types
The data type defines the type of data stored in memory location or the type of data the
variable can hold.
Data Types classification:
Primary data types – are the fundamental data types which are readily available in C.
Secondary data types – are the derived types with the help of primary data types.
Sizes in
Sl. No Data Type Range
Bits Bytes
1 char 8 1 -128 to 127
2 unsigned char 8 1 0 to 255
3 signed char 8 1 -128 to 127
4 int 16 2 -32,768 to 32,767
5 unsigned int 16 2 0 to 65,535
6 signed int 16 2 -32,768 to 32,767
7 short int 16 2 -32,768 to 32,767
8 unsigned short int 16 2 0 to 65,535
9 signed short int 16 2 -32,768 to 32,767
10 long int 32 4 -2,147,483,648 to 2,147,483,647
11 long longint 64 8 -(263 -1) to (263 -1) (Added by C99)
12 signed long int 32 4 -2,147,483,648 to 2,147,483,647
13 unsigned long int 32 4 0 to 4,294,967,295
14 unsigned long longint 64 8 264 – 1 (Added by C99)
15 float 32 4 -3.4E38 to +3.4E38 with six digits of precision
16 double 64 8 1.7e308 to +1.7 e308 with ten digits of precision
Format Specifiers
Format specifiers are the character string with % sign followed with a character. It specifies
the type of data that is being processed. It is also called conversion specifier. When data is
being output or input it must be specified with identifier (variable) and their format specifier.
There are many format specifiers defined in C. Take a look at the following list:
Symbols Meaning
%i or %d integer number
%f float point number
%c Character
%o octal number
%x hexadecimal integer(Lower case letter x)
%X hexadecimal integer(Upper case letter X)
%e floating point value with exponent(Lower case letter e)
%E floating point value with exponent (Upper case letter E)
%g floating point value with or without exponent
%ld long integer
%s String
%lf double
Addition + a+b = 10 + 5 15 2
Subtraction - a-b = 10 – 5 5 2
Multiplication * a* b = 10 * 5 50 1
Modulus(Reminder) % a % b = 10 % 5 0 1
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is arithmetic operators
have a higher priority over relational operators.
The logical operators && and | | are used when we want to test more than one condition and
make decisions.
Example: a>b && x==10
The above logical expression is true only if a>b is true and x==10 is true. If either (or both) of
them are false, the expression is false.
Assignment Operators
Assignment operators are used to assign the result of an expression to a variable or the RHS
value to the LHS variable. We have seen the usual assignment operator,‟=‟.
In addition, C has a set of “shorthand‟ assignment operators of the form. (+=,-=,/=,*=,etc..)
Syntax: v op = exp;
Where: v is a variable,
exp is an expression
op is a C library arithmetic operator
op= is known as the shorthand assignment operator.
The assignment statement:
v op= exp;
is equivalent to v= v op (exp).
with v evaluated only once.
Consider an example
x + = y+1;
This is same as the statement
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Bitwise Negate
Example:
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then:
Operator Description Example
& Operator copies a bit to the result if it exists in both (A&B) = 12
operands i.e., 0000 1100
| Operator copies a bit if it exists in either operand (A | B) = 61
i.e., 0011 1101
^ Operator copies the bit if it is set in one operand but (A ^ B) = 49
not both i.e., 0011 0001
~ Operator is unary and has the effect of 'flipping' bits (~A ) = 61
i.e., 1100 0011
in 2's complement form
<< The left operands value is moved left by the A << 2 = 240
number of bits i.e., 1111 0000
specified by the right operand.
>> The left operands value is moved right by the A >> 2 = 15
number of bits specified by the right operand i.e., 0000 1111
Special Operators
C supports some special operators of interest such as comma operator, sizeof operator.
The Comma Operator
The comma operator can be used to link the related expressions together. A comma-
linked list of expressions are evaluated from left to right and the value of right-most
expression is the value of the combined expression.
Example, the statement: value = (x=10,y=5,x+y)
First assigns the value 10 to x, then assigns 5 to y , and finally assigns 15
to value. Since comma operator has the lowest precedence of all operators,
the parentheses are necessary.
The sizeof() Operator
The sizeof() is a compile time operator and, when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, or a constant or
a data type qualifier.
Examples: m=sizeof(sum);
n= sizeof(5);
1. Primary Expressions
2. Unary Expressions
3. Binary Expressions
4. Ternary Expressions
5. Assignment Expressions
6. Comma Expressions
1. Primary Expressions
An expression with only one operand but without any operator is called primary expression.
The various types of primary expressions are:
(i) Names Ex: int a
(ii) Constants Ex: 5, 10.5
(iii) Parenthesized expressions Ex: (2+3*(4-2))
2. Unary Expressions
An expression with only one operand and one operator is called unary expression. The unary
expression act on a single operand to produce a value. The various types of unary expressions
are:
(i) Unary minus expression Ex: -5
(ii) Unary plus expression Ex: +5
(iii) Prefix expression Ex: ++i
(iv) Postfix expression Ex: i++
3. Binary Expressions
An expression containing two operands and an operator is called binary expression. A binary
operator acts on two operands to produce a value. The various types of binary expressions are:
(i) Multiplicative expressions Ex: 2*3 , 6/2
(ii) Additive expressions Ex: a-b, a + b etc
(iii) Relational expressions Ex: a>b, a<b etc
(iv) Logical expressions Ex: a && b, a || b
(v) Bitwise expressions Ex: a &b , a | b
4. Ternary Expressions
An expression containing three operands and two operators is called ternary expression. Here,
the two operators act on three operands.
Example:a ?b:c // a,b and c are operands and ? and:are operators
5. Assignment Expressions
A statement with assignment operator is called assignment statement. The assignment
statements are often referred to as assignment expressions
Example1: a=10 Example 2:a = b + c
6. Comma Expressions
Program Statement
Statement is a syntactic construction that performs an action when a program is executed. All
C program statements are terminated with a semi-colon ( ; )
Declaration is a program statement that communicates with the compiler about the name and
types of the data needed for program execution.
Example:inta, b;
Compound statements are the sequence of statements that may be treated as a single
statement in the constructions larger statements. Always compound statements will be
enclosed with in { and }.
Labeled statements can be used to mark any statement so that control may be transferred to
that statement.
Control statement is a statement whose execution results is a choice being made on condition
or path of execution. It can also be defined as the statement determines the flow of control of
the program.
Selection statements allow the programmer to select a particular execution path from a set of
one or more alternatives.
Iteration statements are used to execute a group of one or more statements repeatedly.
Jump statements cause an unconditional jump to some other place in the program.