Unit 2-Notes
Unit 2-Notes
Terminology
• Integrated development environment (IDE) seethe program output in one placewith an
IDE . Example:Code::blocks, Eclipse, Visual Studio
• Editor
• Compilation
• Debugging: Removing them called debugging.
• Errors in code called Bugs.
Introduction
We all program our lives in some way. Computer Program is a list of Instructions
Example Program: ISBT (Inter State Bus Terminus) to Graphic Era Univesity, Dehradun
• Head west on NH 7 toward ISBT Circle
• At ISBT Circle, take the 1st exit ontoNH307 2 Kms
• Turn left onto Post Office Rd 1 Kms
• Turn right onto Bell Road 200 Metres
• Make a left towards Graphic Era University
Let us say your parents give you one thousand rupees per month towards your expenses. Assume you
hobby is listening to music and you purchase them from a website selling songs. Let us say the cost of
a song is 12 rupees. Now you want to write a simple program to tell you the total cost for say N
number of songs you download from the site. If you had to write the steps they would be…
Enter “Number of songs you would like to download today?”
N Enter “the cost per song:” 12
Multiply the Number of songs with cost per song: N x 12Show
the final cost: Rs.
// C Program
#include <stdio.h>
int main ()
{
int N_Songs ;
float Song_Cost = 12, Final_Price;
printf(“Enter Number of Songs \n”);
scanf(“%d”, &N_Songs);
Final_Price = N_Songs * Song_Cost;
printf(“Cost of Songs is %0.2f \n”,Final_Price);
return 0;
}
Features of C language:
• Structured
• High Level/Middle Level
• Robust
• Portable
• Extensible
• Supports pointers
Structured:
C is structured procedure- oriented language, it divides the problem into smaller modules called functions or
procedures.
Robust:
C is robust language that is programs written in C do not crash so easily. It recovers quickly whenever
programs result into an erroneous condition.
Extensible:
C is extensible language that allows new features and modifications to be made to the existing programs
written in C.
Supports pointers:
C supports the use of pointers that allow the programmers to manipulate the memory directly.
Journey of C Language
1. In 1972 Dennis Ritchie worked on improvement of a language called B by Ken Thompson which in
turn was derived from BCPL by Martin Richards.
2. The result was the C programming language.
3. Version 4 of Unix Kernel major portions were coded in C
4. First language is used for writing an OS rather than a assembly language
5. Language became popular
6. In 1978, K&R released the first specification via book The C programming language
7. To address standardization 1983 ANSI committee formed
8. ANSI released standard document in1989
9. Adopted by ISO in 1990
10. C89 or C90 refer to same standard
11. ISO C99 inline functions, one-line comments, variable length arrays
12. C11 and C18
13. The only way to learn a programming language is by writing programs in it.
14. Comments in C Code
// C hello world example //Single line comment
/*
Graphic Era University B.Tech 1st sem //multi line comment
*/
#include <stdio.h>
int main()
{
printf("Welcome to C Programming\n");
return 0;
}
#include <stdio.h>
int main()
{
printf("Welcome to C Programming\n");
return 0;
}
Library:
#include <C_HeaderFile.H>
Example
#include <stdio.h> OR
#include “U_HeaderFile.H”
Example
#include “projects.h”
• <C_HeaderFile.H> Search for header file in the standard system directories (Can show a
snapshot of standard system directories on Windows with Code::Blocks compiler)
• “U_HeaderFile.H” Searches in the location where your source file exists followed by the
standard directories
C|D:\Code Blocks\MinGW\include
Eg: stdio.h, math.h
• Contents of the header file are included at that point in the source code. Think of itas a copy
paste into the source file
• Step is prior to compilation. Not apart of the C Compiler. That is why no ;
• Files shared across programs
• One header file Per Line
• Function prototype declarations (No code is present), Global variables, Constants
• No Code after # line
• Software Program as the name indicates does pre-processing prior to the actualcompilation
of the program in a high level language.
• Includes header file <stdio.h>
• Removes any comments in the source program
Macros Substitution
They are abbreviations of C code. They are substituted for all occurrences in your source file.
Example : #define PI 3.142
Ex:
#include <stdio.h>
#define STRING "Hello World"
int main(void)
{
/* Using a macro to print “HelloWorld” */
printf(STRING); return
0;
}
• Create a file in code:blocks IDE and save the file with an extension .c For example: hello.c
• File is passed onto a software program called pre-processor. File after
preprocessing becomes hello.i
• The file is taken in by the compiler and converted to a assembly file called hello.s
• The assembler converts the file into hello.o (object code)
• Some calls like say printf code not yet part of the program. These references need tobe resolved.
Library object code is stored in .a or .lib files.
• A software program called the linker resolves these references (linking the code)
• Output of the linker is .exe on windows and a.out on Linux platforms. The
executableimage is stored on the secondary storage device.
• Loader takes the image and loads into RAM. Intimates to the CPU starting address of
the code.
Source Pre-
Executable
Object Linking
Program Compile File
process file
(P1.c) (P1.o) (P1.exe)
Library files
Source Program:
Any C file say P1.C program is edited and given to a C compiler. Figure above shows the different phases of execution
of C program.
Pre-Processing:
This is the first phase through which source code is passed. In this phase any statements defined in this section (before
the main() function) are processed, if used in the program.
This phase includes:
Removal of Comments
Expansion of Macros
Expansion of the included files.
Conditional compilation
For ex. printf and scanf statements, if used in the program, will have been checked with their definitions stored in the
header file <stdio.h>.
Compile:
The next step is to compile and produce an; intermediate file that contains assembly level instructions P1.s.
During this phase the compiler checks for the syntax errors such as declaration of variables, initialization if any, the
correct syntax of the C program etc. If any errors are encountered then they get displayed with corresponding line
numbers.
The assembler converts the P1.s file after correction and successful compilation of the program to an object file P1.o.
Linking:
This is the final phase in which all the linking of function calls with their definitions are done. Linker knows where all
these functions are implemented. Linker does some extra work also, it adds some extra code to our program which is
required when the program starts and ends.
Linking produces the executable file P1.exe (a.out by default on Linux/Unix machines), which is the machine code
(binary code) which will be actually executed by the processor.
Loader:
Loader takes the image (P1.exe) generated and loads it into RAM and informs the CPU the starting address of the code
for execution (running of the program).
int main()
{
declaration section;
Documentation Section
This section allows to document by adding Comments to the program. Comments are portions of the code
ignored by the compiler. The comments allow the user to make simple notes in the source code.
• The preprocessor accepts the source program and prepare the source program for
compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the specified file-
contents in the beginning of the program.
• For ex:
#include<stdio.h>
main()
Global declaration section
• If user wishes to declare any variable outside the main program which needs to be accessed by any
part of the program then he may declare it in this section just before main function.
• Every C program should have a function called as main() and is an entry point to the program (a
gateway to the program) that is always executed.
• The statements enclosed within left and right curly brace is called body of the function. The
main() function is divided into 2parts:
Declaration Section
• The variables that are used within the function main() should be declared in the declaration-
section only.
• The variables declared inside a function are called local variables. The compiler allocates the
memory for these variables based on their types for ex. if the variable is an integer, then it
allocates 4 Bytes, if it’s of char type then 1-Byte and so on. Ex: int p, t,r;
Executable Section
• This contains the instructions given to the computer to perform a specific task.
• The task may be to:
→ display a message
→ read data or
→ do some task ex. add two numbers etc.
User Defined Function-definition(s):
If user has any user defined functions, then those definitions are written outside the main function.
#include<stdio.h>
int main()
{
printf(“Welcome to C”);
return 1;
}
Output:
Welcome to C
Input Function
• The input functions are used to read the data from the keyboard and storein memory-location.
• For ex:
scanf(), getchar(), getch(), getche(), gets()
scanf()
Output Functions
The output functions are used to receive the data from memory- locations through the variables and display on
the monitor.
Forex:
printf(), putchar(), putch(), puts() Types of I/O Functions:
• format strings i n f o r m C how the values are to be interpreted. It contains conversion specifiers and
text
• Conversion specifiers begin with %
• Expressions may contain constants, variables or a combination evaluating to a built- indata type
• At the point of conversion specifiers values are substituted during printing
• Conversion specifiers specify the format of display
• For example %d indicates decimal integer
• Ordinary characters enclosed within “”are printed as is.
• No checking of number of format specifiers and expressions
• C does not perform any type checks in the printf( ) function call
• Programmer job to make sure that the data type of the variables MATCH and
CORRESPOND to formatting character
• Programmers responsibility to specify correct specifier and data type
• Otherwise garbage results are printed
ILLUSTRATION
printf(“Value of i = %f and j = %d \n”, i,j);// Garbage Output
printf(“Value of i = %d and j = %f \n”, i);// i = 100, meaningless output
These are unprintable, which means they are not displayed on the screen or printer. Those characters
perform other functions. Examples are backspacing, moving to a newline, or ringing a bell. Each one of
character constants represents one character, although they consist of two characters. These character
combinations are called escape sequence.
• An escape sequence character begins with a backslash and is followed byone character.
• A backslash (\) along with some characters give rise to special print effectsby
changing (escaping) the meaning of some characters.
• The complete set of escape sequences are:
Identifier
• Identifier is used to represent various part of a program such as variables,
constants, functions etc.
• An identifier is a word consisting of sequence of
→ Letters
→ Digits or"_"(underscore)
• For ex:
Average, Percent, total100
i) Fractional Form
• A floating-point number represented using fractional form has an integer part
followed by a dot and a fractional part.
• Forex:
0.5, -0.99
• For ex:
9.86E3 imply 9.86*103
3. Character Constant
• A symbol enclosed within a pair of single quotes (') is called a
character constant.
• Each character is associated with a unique value called an ASCII (American
Standard Code for Information Interchange) code.
Forex: '9', 'a','\n'
4. String Constant
•A sequence of characters enclosed within a pair of double quotes (“) is called a string
constant.
• The string always ends with NULL character (denoted by \0) character.
• Forex:
"9" "a" "sri" "\n"
Data in Programming
• The data type defines the type of data stored in a variable and hence in the memory-
location.
Three basic data types in C:
int, float and char
Range and Size of data types for 32-bit and 64-bit processor
Qualifiers
• Qualifiers alter the meaning of primary data types to yield a new data type.
Size Qualifiers
• Size qualifiers alter the size of primary datatype.
long int i; //The size of int is 4 bytes in 32- and 64-bit processors but, when long
//keyword is used, variable will be of 8 bytes
short int i; //The size of int is 2 bytes.
To get to know about the size of the datatype, use sizeof operator.
#include <stdio.h>
int main() {
printf("The size of int data type: %d bytes\n", sizeof(int));
printf("The size of char data type: %d bytes\n", sizeof(char));
printf("The size of float data type: %d bytes\n", sizeof(float));
printf("The size of double data type: %d bytes\n", sizeof(double));
printf("The size of long double data type: %d bytes\n", sizeof(long double));
return 0;
}
Sign Qualifiers
• Whether a variable can hold positive value, negative value or both values is specified
by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
unsigned int a; //unsigned variable can hold zero &
// positive values only
Signed int b; //signed variable can hold zero, positive
//and negative values
Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An identifier declared by using a const keyword cannot be modified.
const int p=20; //the value of p cannot be changed in the
//program.
Variables
•A variable is an identifier whose value can be changed during execution of the program.
Variable is a name given to a memory-location where the data(value) can be stored.
Variable Declarations:
//Showing some variable declarations
#include<stdio.h>
#define LOWER 0
int main ()
{
int a;
float b;
char c;
}
/*Ritchie’s advice: Declare each variable type on a separate line */
• Choose variable names that are related to the purpose of the variable, and that are unlikely to get
mixed up typographically.
• Use short names for local variables, especially loop indices, and longer names for external variables.
Rules for defining a variable
1) The first character in the variable should be a letter or an underscore.
2) The first character can be followed by letters or digits or underscore.
3) No special symbols are allowed (other than letters, digits and
underscore).
4) Length of a variable can be up to a maximum of 31characters.
5) Keywords should not be used as variable-names.
• Valid variables:
area, rate_of_interest, _temperature_, celcius25
• Invalid variables:
3fact, ?sum, sum-of-digits, length62$, for, int, if
Declaration of Variable
The declaration tells the complier:
• what is the name of the variable used
• what type of data is held by the variable
• For ex:
int a, b, c;
float x, y, z;
Initialization of Variable
• The variables are not initialized when they are declared. Hence, variables normally contain
garbage values and hence they have to be initialized with valid data.
data_type variable_name
float pi=3.1416;
char c='z';
Common Conversion Specifiers
Decimal integer:
%d Octal integer:
%o Hexadecimal:
%x float: %f
double:%lf
char: %c
string: %s
unsigned int : %u
% W.P[Conversion_Specifier]
• Width specification is ignored if number of letters is more than the width specified
#include<stdlib.h> int
main()
{
Int i=101 ;
float j=1234.123f;
printf("[%d][%6d][%-6d][%6.4d]\n",i,i, i, i);
printf("[%f][%12f][%-12f][%12.2f][%12.2e]\n", j,j,j,j,j);
return 0;
}
OPERATOR
• An operator can be any symbol like + - * / that specifies what operation need tobe performed
on the data.
• Forex:
+ indicates add operation
* indicates multiplication operation Operand
-- Postfix decrement
[] Array subscripting
Element selection by
. reference
++ Prefix increment
2 Right-to-left
-- Prefix decrement
Unary plus
+
Unary minus
-
Logical NOT
!
Bitwise NOT (One's
Complement)
~
Type cast
(type)
Indirection (dereference)
*
Address-of
&
sizeof
sizeof
Multiplication
3 * Left-to-right
Division
/
Modulo (remainder)
%
Addition
4 + Left-to-right
Subtraction
-
Bitwise left shift Left-to-right
5 <<
Bitwise right shift
>>
Less than
<
6 Less than or equal to Left-to-right
<=
Greater than
>
Greater than or equal to
>=
Equal to
7 == Left-to-right
Not equal to
!=
8 Bitwise AND Left-to-
& right
Bitwise XOR
9 L
^
e
(exclusive or) f
t
-
t
o
-
r
i
g
h
t
Bitwise OR (inclusive or)
10 | Left-to-
right
11 Logical AND Left-to-right
&&
12 Logical OR Left-to-right
||
Ternary conditional
13 ?: Right-to-left
Direct assignment
=
Assignment by sum
14 += Right-to-left
Assignment by difference
-=
Assignment by product
*=
Assignment by quotient
/=
Assignment by remainder
%=
Assignment by bitwise left
<<= shift
Assignment by bitwise right
>>= shift
Assignment by bitwise AND
&=
Assignment by bitwise XOR
^=
Assignment by bitwise OR
|=
15 Comma
, Left-to-right
Lowest
CLASSIFICATION OF OPERATORS
Operator Name For Example
Arithmetic operators +-* / %
Increment/decrement operators ++ --
Assignment operators =
Relational operators <>== Logical
operators && ||~
Conditional operator ?:
Bitwise operators & |^
Comma operator ,
Special operators [], sizeof,
ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations such
asaddition, subtraction, division, multiplication, modulus.
There are 5 arithmetic operators:
Operator Meaning of Operator
+ addition
- subtraction
* multiplication
/ division
% modulos
• Division symbol(/)
→ divides the first operand by second operand and
→ returns the quotient.
Quotient is the result obtained after division operation.
• Modulus symbol (%)
→ divides the first operand by second operand and
→ returns the remainder.
Remainder is the result obtained after modulus operation.
• To perform modulus operation, both operands must be integers.
• Program to demonstrate the working of arithmetic operators.
#include<stdio.h> int
main()
{
int a=11,b=4,c;
c=a+b;
printf("a+b=%d \n", c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c); c=a/b;
printf("a/b=%d \n", c); c=a%b;
printf("Remainder when a is divided by b=%d ", c);
return 1;
}
Output:
a+b=15
a-b=7
a*b=44
a/b=2
a%b=3 Remainder when a is divided by b= 3
int a=20,b=6,result;
result = a / b ; //3
result = a % b ; //2
Float result;
result=10/3; // 3.333333
NOTE:
a) Unary+, -have highest precedence, next are*,/,%,operators and last
are binary+,
-operators and the associativity of all arithmetic operators is left to right.
b) Mod works only on Integer type data
INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is used toincrease the
value of a variable by1.
• For example:
If b=5
then b++ or ++b; // b becomes 6
• The increment operator is classified into 2categories:
1) Post increment Ex:b++
2) Pre increment Ex:++b
• As the name indicates, post-increment means first uses the value of variableand
then increases the value of variable by1.
• As the name indicates, pre-increment means first increases the value of variableby 1
and then uses the updated value of the variable.
• Forex:
If x= 10,
then z= x++; assigns the value 10 to z & then increments value of x but z = ++x; assigns the
value 11 to z
Example: Program to illustrate the use of increment operators.
#include<stdio.h>
int main()
{
int x=10,y = 10, z ;
z= x++;
printf(“ z=%d x= %d\n”, z, x);
z = ++y+x;
printf(“ z=%d y= %d”, z, y++);
return 1;
}
Output:
z=10 x=11
z=22 y=11
DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used todecrease the
value of a variable by1.
• For example:
If b=5
then b-- or --b; // b becomes 4
• Similar to increment operator, the decrement operator is classified into two categories:
i) Post decrement Ex:b--
ii) Pre decrement Ex:--b
• Forex:
If x=10,
Then z=x--; // z becomes 10, but
z = --x; // z becomes 9
int main()
{
int x=10,y = 10, z ;
z= x--;
printf(“ z=%d x= %d\n”, z, x);
z = --y;
printf(“ z=%d y= %d”, z, y);
}
Output:
z=10 x=9
z=9 y=9
TYPE CONVERSION
• Type conversion is used to convert data of one type to data of another type.
• Type conversion is of 2 types as shown in below figure:
Implicit Type Conversion
• If a compiler converts one type of data into another type of data automatically, it is
known as implicit conversion.
• There may be data loss whenever in implicit conversion takes place i.e while converting from
float to int the fractional part will be truncated, double to float causes rounding of digit and long to
int causes dropping of excess higher order bits.
• The conversion always takes place from lower rank to higher rank.
int main()// Implicit Conversion
{
intage=2;
char gender ='A'; //ASCII65
age=age*gender;
printf("%d\n", age); //130
} //Lower to a WIDER Type
Any implicit type conversions are made by converting the lower type to higher type as shown below:
#include<stdio.h> int
main()
{
inti=10,j= 20;
float result;
result=i/j;
printf("%0.2f\n",result);// 0.00
result =(float)i/j;
printf("%0.2f\n", result);// 0.5
}
RELATIONAL OPERATORS
• Relational operators are used to find the relationship between
two operands.
• The output of relational expression is either true(1) or false(0).
• For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
• The 2 operands may be constants, variables or expressions.
There are 6 relational operators:
Operator Meaning of Operator Example
> Greaterthan7>4 returns true (1)
< Lessthan7<4 returns false(0)
>= Greater than or equal
to 7>=4 returns true (1)
<= Less than or equal to7<=4
return false(0)
== Equal to 7==4 returns false(0)
!= Not equal to 7!=4 returns true(1)
• For ex:
Condition Return values
8> 7 1 (or true)
8<7 0 (or false)
8+7<15 0 (or false)
• Example: Program to illustrate the use of all relational operators. #include<stdio.h>
int main ()
{
printf(“7>4 : %d \n”, 7>4);
printf(“7>=4 : %d \n”, 7>=4);
printf(“7<4 : %d \n”, 7<4);
printf(“7<=4 : %d \n”, 7<=4);
printf(“7==4 : %d \n”, 7==4);
printf(“7!=4 : %d ”, 7!=4);
return 1;
Output:
7>4 : 1
7>=4 : 1
7<4 : 0
7<=4 :0
7==4 :0
7!=4 : 1
LOGICAL OPERATORS
}
Output:
5 &&0 : 0
5 || 0 : 1
!0 : 1
#include<stdio.h>
int main()
{
printf(“7>5 && 5< 8 : %d \n”, 7>5 &&5<8);
printf(“ 7<5 || 5!=5 : % d \n”, 7<5 || 5!=5);
printf(“!(3 ==3) : %d ”, !(3==3));
return 1;
}
Output:
7>5 && 5<8 :1
7<5 || 5!=5 :0
!(3 ==3) : 0
Equality Operators ( == != )
int main ()
{
int a=20,b=10;
int result ;
if (a== 20)
printf("Yes a is 20\n”);
if (b!=20)
printf("Yes b is not 20\n”);
}
#include<stdio.h>
int main()
{
int a,b, big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d”, &a, &b);
big=(a>b)? a :b;
printf(“ Biggest number is % d ”, big);
return 1;
}
Output:
Enter two different numbers: 88 79 Biggest
number is 88
#include<stdio.h>
int main()
{
int a,b,c big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d%d”, &a, &b, &c);
big=(a>b)?((a>c)?:a:c) : (b>c)? b:c;
printf(“ Biggest of three number is %d”, big);
return 1;
}
Output:
Enter two different numbers: 88 99 Biggest
number is 99
ASSIGNMENT OPERATOR
• The most common assignment operator is=.
• This operator assigns the value in right side to the left side.
• The syntax is shown below:
variable=expression;
• Forex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to b 5=c; // Error! 5
is a constant.
• The operators such as +=, *= are called shorthand assignment operators.
• Forex,
a=a+10: can be written as a+=10;
Compact Assignments
= Direct assignment
+= Assignment by sum
-= Assignment by difference
*= Assignment by product
/= Assignment by quotient
%= Assignment by remainder
<<= Assignment by bitwise left shift
>>= Assignment by bitwise right shift &= Assignment by bitwise AND
^= Assignment by bitwise XOR
|= Assignment by bitwise OR
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
BITWISE OPERATORS
• These operators are used to perform logical operation (and, or, not) on individual bits of a binary number.
• There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
• The operator that is used to shift the data by a specified number of bit positions towards left or right is called
shift operator.
• The syntax is shown below for <<
b=a << num, where a is value to be shifted and num is number of bits to be shifted.
• The syntax is shown below for >>
b=a >> num, where a is value to be shifted and num is number of bits to be shifted.
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte \n",sizeof(d));
printf("Size of char in bits=%d\n",sizeof(d)*8);
return 0;
}
Size of int = 4 bytes
Size of float = 4
bytes Size of double
= 8 bytes Size of char
= 1 byte Size of char
in bits= 8
Comma Operator:
The comma operator (represented by the token ,) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns the value (and type).
The comma operator has the lowest precedence of any C operator.
intx, y;
x=(10,20,30);
printf(“x=%d”,x);
x=33, y=22;
printf(“\nValue: %d\n”,(x,(y+10)));
Output: x=30
Value: 22