Porcedraul Programming Unit-1B_Intro to C Programming
Porcedraul Programming Unit-1B_Intro to C Programming
INTRODUCTION TO C PROGRAMMING
‘C’ is high level language and is the upgraded version of another language (Basic Combined
Program Language). C language was designed at Bell laboratories in the early 1970’s by Dennis Ritchie.
C being popular in the modern computer world can be used in Mathematical Scientific, Engineering
andCommercial applications
The most popular Operating system UNIX is written in C language. This language also has the
features of low level languages and hence called as “SystemProgramming Language”
Features of C language
• Highly Portable: C programs are machine-independent which means that the fraction of a
code created in C program can run on various machines with none or some machine-specific
changes. Hence, it provides the functionality of using a single code on multiple systems
depending on the requirement.
• Robust: C provides a lot of inbuilt functions and operators that can be used to write any
complex program.
• Structured programming language: C is a structured programming language because a
program in c language can be divided into small logical functions, modules or structures. So, it
is easy to understand and modify. Functions also provide code reusability. Proper collection of
these functions or modules would make a complete program. Modular structure makes program
to debug, test and maintain easily.
• Efficient and Fast: C is a compiler-based program that makes the compilation and execution
of codes faster.
• Procedural Language: C is a procedural programming language, which means it follows a
procedure of steps written in it called functions.
• Simple: C is a simple programming language, since it provides structured approach, rich set of
library functions, data types etc.
• Flexibility: C is a versatile language that can be used for a wide range of applications, from
system programming and embedded systems to desktop applications and game development.
• Ability to extend itself: If a program is already written in it then some more features and
operations can be added to it.
• General purpose programming language: C can be used to implement any kind of
applications such as math’s, graphics and business oriented applications.
DOCUMENTATION SECTION:
Document the use of logic or reasons in your program. It can be used to write the program's
objective, developer and logic details. The documentation is done in C language with comments.
Comments: The lines beginning with /* and ending with */ are known as comment lines.
• Single line comment (//)
• Multi-line comment (/* */)
o Comments are used to enhance readability and understanding of a program.
o Comment lines are not executable statements.
o Comments can be written anywhere beginning, middle or end of a line but never in middle of a
word.
Example:
// description, name of the program, programmer name, date, time etc.
//To find sum of two numbers
or
/*
* Description, name of the program, programmer name, date, time etc.
*/
Declaration part: It is part of C program where all the variables, arrays, functions etc., used in the
C program are declared and may be initialized with their basic data types.
Executable Part / Statements: These are instructions to the specific operations. They may be
input-output statements, arithmetic statements, control statements and any other statements.
Comments are also included in statements.
Example:
Output:
All programs written in C uses library functions. These library functions are pre-compiled
pre
and the object code of these library files is stored in .lib extension.
Compiler:: compiler is a program that converts high level language instructions into low level
language instructions on one go.. It performs:
• Verifies the program errors, if errors are found, it re
returns
turns a list of errors otherwise.
• It converts the complete code into the low level language.
Compiled programs run faster as there is no translation during runtime. A compiler displays every
error and warning while compiling. So program cannot run until all errors are fixed.
• Example:: gcc (GNU C Compiler)
Interpreter:
Reads High Level Language programs line by line and executes their equivalent operational
codes. The process of interpretation makes the program execution slower
slower.. It generates errors in
every single line one by one. An interpreter reads every statement, then display the errors if any.
User must resolve these errors in order to interpret the next line.
• Example:
– Java Virtual Machine: Works on object code generated by Java compiler.
compiler
Linking the program
Linking is the process of putting together other program files and functions that are required
by the program. Linking is done by linker. The linker is a proc
process
ess that accepts object files and
library files as input to produce the final executable program.
Errors
Errors are the problems or the faults that occur in the program.
Programming errors are also known as the bugs or faults.
The process of removing these bugs is known as debugging.
These errors are detected
ed either during the time of compilation or execution.
Thus, the errors must be removed from the program for the successful execution of the
program.
There are mainly five types of errors exist in C programming:
o Syntax error
o Linker error
o Run-time error
o Logical error
o Semantic error
Runtime Error
Errors that occur during the execution (or running) of a program are called Run time Errors.
These errors occur after the program has been compiled successfully.
When a program is running, and it is not able to perform any particular operation, it means
that we have encountered a run time error.
Runtime errors are difficult to identify because the compiler cannot detect these errors.
Some of the most common run time errors are:
o All mathematically incorrect operations
number not divisible by zero
calculating the square root of -1
o Memory related issues
Array index out of bounds
string index out of bounds
o Infinite loop
o Wrong input by the user
Logical Error
The logical error is an error that leads to an undesired output.
These errors produce the incorrect output, but they are error-free.
The output generated is different from the expected one after the compilation and execution
of a program.
Some of the most common Logical errors are:
o Semicolon after a loop.
o Incorrect use of relational and logical operators
o Misunderstanding the order of precedence
Semantic Error
Errors that occur because the compiler is unable to understand the written code are called
Semantic Errors.
A semantic error will be generated if the code makes no sense to the compiler, even though
it is syntactically correct.
Linker Error
Linker is a program that takes the object files generated by the compiler and combines them
into a single executable file.
Linker errors are mainly generated when the executable file of the program is not created
even though the code gets compiled successfully.
We can run into a linked error if we have
o Imported an incorrect header file in the code.
o Wrong function declaration. Ex: main() is written as Main()
Conclusion
Errors are the problems or the faults that occur in the program.
There are 5 different types of errors in C programming language: Syntax error, Runtime
error, Logical error, Semantic error, and Linker error.
Syntax errors, linker errors, and semantic errors can be identified by the compiler during
compilation. Logical errors and run time errors are encountered after the program is
compiled and executed.
Syntax errors, linker errors, and semantic errors are relatively easy to identify and rectify
compared to the logical and run time errors. This is so because the compiler generates these
3 (syntax, linker, semantic) errors during compilation itself, while the other 2 (Logical and
run time) errors are generated during or after the execution.
Character set
• Alphabets
Lower case letters – a to z
Upper case letters – A to Z
• Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
• Special characters
~ % | @ + < _ - > ^ # = & $ / ( * \ ) ′ : [ “ ; ] ! , { ? . }
C Tokens
• C tokens : the smallest individual units
Operators – + - * % …
Special Symbols – [ ] { }…
Integer constants
An integer constant refers to a sequence of digits. There are three types of integers
Decimal Integer: Consists a set of digits 0 to 9
Octal Integer :Combination of digits 0 to 7
Hexadecimal Integer: Combination of digits 0 to 15 where A to F represents the numbers 10
to 15 respectively.
Real constant:
The numbers containing fractional part are called real or floating point constants.
Example: To represent quantities that vary continuously such as distance, height, prices etc. like
17.45, -.72, 12.
A single character constant contains a single character enclosed within a pair of single quote
marks. Every character constant has an equivalent integer value know as ASCII Value.
String constant:
A string constant is a sequence of character enclosed in double quotes. The character may
be letters, numbers, special characters and blank space
Example: “Hello”, “1997”, “welcome all’, “5+3”.
• When encountering a backslash in a string, the compiler looks ahead at the next character
and combines it with \ to form escape sequence
Variables
These are the names of the objects, whose values can be changed during the program
execution. Variables are named with description that transmits the value it holds.
A variable is a data name that may be used to store a data value.
A variable may take different values at different times during execution.
The variable name can be chosen by the programmer in a meaningful way.
Rules to name a variable
Should start with a letter or underscore.
Can be any length. Standard length is 31 characters.
Lowercase and uppercase are significant.
It should not be a C keyword.
White space is not allowed.
Declaration of variables
Syntax type Variable list
int i, j i, j are declared as integers
float salary salary is declared ad floating point variable
Char sex sex is declared as character variable
Range Format
Data Type Size (bits) Size (bytes)
Specifier
unsigned short 0 to 28
8 1 %hu
int
unsigned long 64
8 0 to 264 %llu
long int
unsigned char 8 1 0 to 28 %c
float 32 3.4E-38 to %f
4
3.4E+38
Character
Any character of the ASCII character set can be considered as a character data types and its
maximum size can be 1 byte or 8 bits long. ‘Char’ is the keyword used to represent character data
type in C. Char - a single byte size, capable of holding one character.
Syntax:
char var_name;
Integer data
The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits.
The integer data type can again be classified as
o Long int - long integer with more digits
o Int- an Integer with the natural size of the host machine
o Short int - short integer with fewer digits.
o Unsigned int - Unsigned integer
o Unsigned short int – Unsigned short integer
o Unsigned long int – Unsigned long integer
Syntax:
int var_name;
Double data: - Double is a keyword in C to represent double precision floating point numbers. It
can easily accommodate about 16 to 17 digits after or before a decimal point.
double - Double – precision floating point number value.
Syntax:
double var_name;
Void
The void data type always represents an empty set of values. It is used to specify the type of
a function. The type of function is said to be void when it doesn’t return any value to the calling
function.
Syntax:
void main()
Operator
An Operator is a symbol that operates on a certain data type. The data items that operators
act upon are called operands. Some operators require two operands, some operators act upon only
one operand. In C, operators can be classified into various categories based on their utility and
action.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operator
4. Assignment Operator
5. Increment & Decrement Operator
6. Conditional Operator
7. Special Operator
1. Arithmetic Operators
The Arithmetic operators perform arithmetic operations. The Arithmetic operators can operate on
any built in data type. Some of arithmetic operators are
2. Relational Operators
Relational Operators are used to compare arithmetic, logical and character expressions. The
Relational Operators compare their left hand side expression with their right hand side expression.
That results to an integer value. If the Expression is false it evaluate to “zero”(0) if the expression is
true it evaluate to “one”
Operator Meaning
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to
3. Logical Operators
A logical operator is used to evaluate logical and relational expressions. The logical operators act
upon operands that are themselves logical expressions. There are three logical operators.
Operators Expression
&& Logical AND
|| Logical OR
! Logical NOT
Logical And (&&): A compound Expression is true when two expression when two expressions
are true. The && is used in the following manner:
Exp1 && Exp2
The result of a logical AND operation will be true only if both operands are true.
The results of logical operators are:
Exp1 Operator Exp2 Result
True && True True
Logical OR: A compound expression is false when all expressions are false otherwise the
compound expression is true. It evaluates to true if either Exp1 Or Exp2 is true. The operator “||” is
used in following manner:
The truth table of “OR” is Exp1 || Exp2
Exp1 Operator Exp2 Result
True || True True
True || False True
False || True True
False || False False
Example: a = 5; b = 10; c = 15;
Exp1 Op. Exp2 Result
1. ( a< b ) || ( b < c ) => True
2. ( a> b ) || ( b < c ) => True
3. ( a< b ) || ( b > c ) => True
4. ( a> b ) || ( b > c ) => False
Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to true(1) if the
expression is false (0) or it evaluates to false (0) if expression is true (1). The general form of the
expression is: !( Relational Expression )
The truth table of NOT :
Operator. Exp1 Result
! True False
! False True
The increment/decrement operator act upon a Single operand and produce a new value is
also called as “unary operator”. The increment operator ++ adds 1 to the operand and the
Decrement operator – subtracts 1 from the operand.
Syntax: < operator > < variable name > ;
The ++ or – operator can be used in the two ways.
Example:
Pre-increment ++ A; (or) Post increment A++
Pre-Decrement —A; (or) Post decrement A—
Pre-increment ++ A: Immediately increments the value of A by 1.
Post increment A ++: The value of the A will be increment by 1 after it is utilized.
Example 1: Suppose A = 5 ;
Statements Output
printf ( “A value is %d”, A ); a value is 5
printf ( “A value is %d”, ++ A ); a value is 6
printf ( “A value is %d “, A) ; a value is 6
Example 2: Suppose : A = 5 ;
Statements Output
printf (“A value is %d “, A); A value is 5
7. Special Operators
i. Comma Operator:
A set of expressions separated by using commas is a valid construction in c language.
Example: Consider int i, j;
i= ( j = 3, j + 2 ) ;
The first expression is j = 3 and second is j + 2. These expressions are evaluated from left
to right. From the above example I = 5.
ii. Size of operator: The operator size operator gives the size of the data type or variable in
terms of bytes occupied in the memory. This operator allows a determination of the no of
bytes allocated to various Data items
Example : int i; float x; double d; char c;
printf (“integer : %d\n”, sizeof(i)); OUTPUT integer : 2
printf (“float : %d\n”, sizeof(i)); OUTPUT float : 4
printf (“double : %d\n”, sizeof(i)); OUTPUT double : 8
printf (“char : %d\n”,sizeof(i)); OUTPUT character : 1
Expressions
* Dereference right-to-left
12 || Logical OR left-to-right
= Assignment right-to-left
Type Conversion
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination data type can’t be smaller than the
source data type. Type conversion is done at compile time and it is also called widening conversion
because the destination data type can’t be smaller than the source data type.
There are two types of Conversion
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit conversion is done automatically by the compiler, without any external trigger from
the user.
Generally takes place when in an expression more than one data type is present. In such
conditions type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with the largest
data type.
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly converted to
float).
Example: Implicit type conversion
The compiler automatically converts the int value 9 to a float value of 9.000000.
Explicit Type Conversion is also called type casting and it is user-defined. Explicit
conversion is done manually by placing the type in parentheses () in front of the value.
Consider the following example
The result is 2.00000 but the expected output is 2.5. This is because 5 and 2 are still integers
in the division so result is 2.00000. In this case, integer values need to be manually converted to
floating-point values. This is known as Explicit Type Conversion.