Unit 2-Notes
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 as 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?”
NEnter “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- o r i e n t e d language, it divides the problem
intosmaller 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 results into an erroneous condition.
Extensible:
C is extensible language that is it allows new features and modifications to
be made to the existing programs written in C.
Supports pointers:
C supports the use of pointers that allows the programmers to manipulate
the memory directly.
Journey of C Language
• 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.
• The result was the C programming language.
• Version 4 of Unix Kernel major portions were coded in C
• First languages used for writing an OS rather than a assembly language
• Language became popular
• 1978 K&R released the first specification via book The C programming language
• To address standardization 1983 ANSI committee formed
• ANSI released standard document in1989
• Adopted by ISO in 1990
• C89 or C90 refer to same standard
• ISO C99 inline functions, one line comments, variable length arrays
• C11 and C18
The only way to learn a programming language is by writing programs in it.
Comments in C Code
// C hello world example
/*
Graphic Era University
B.Tech 1stsem
*/
#include <stdio.h>
int main()
{
printf("Welcome to C Programming\n");
return 0;
}
#include <C_HeaderFile.H>
Example
#include <stdio.h>
OR
#include “U_HeaderFile.H”
Example
#include “projects.h”
• “U_HeaderFile.H” Searches in the location where your source file exists followed
bythe 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
sourcefile. 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
preprocessingbecomes 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.
Life cycle of a C program
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.
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).
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.
• For ex. // this is an example for single line comment
/* this is an example for multiple line comment */
Preprocessor Directives
• 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.
• Forex:
#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.
Example: Program to display a message on the screen.
#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.
• Forex:
scanf(), getchar(), getch(), getche(), gets()
scanf()
Reads values into built-in data types
Syntax: scanf(“Format specifier”,&var_name);
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:
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
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)
• Forex:
Average,_Percent, total100
i) Fractional Form
• A floating point number represented using fractional form has an
integerpart followed by a dot and a fractional part.
• Forex:
0.5, -0.99
• Forex:
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
Data Types in C
• The data type defines the type of data stored in a variable and hence inthe
memory-location.
Three basic data types in C:
int , float and char
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.
• The keywords long and short are 2 size qualifiers.For example:
long int i; //The size of int is 2 bytes but, when long
//keyword is used, variable will be of 4 bytes
short int i; //The size of int is 2 bytes but, when short
//keyword is used, that variable will be of 1
//byte
Sign Qualifiers
• Whether a variable can hold positive value, negative value or both values
isspecified by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An identifier declared by using a const keyword cannot be modified.
Variable Declarations:
//Showing some variable declarations
#include <stdio.h> #define LOWER 0 int main ()
{
int lower = 234;
char c = ‘a’, d, f;
short age ;
float fahr = 123.45;
int start = LOWER;
const double e = 2.7049658030;
}
/*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.
• 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
• The syntax is shown below:
data_type variable1, variable2, variable3;
where variable1, variable2, variable3 are variable-names of
data_type that could be int, float or char type.
• Forex:
int a, b, c;
float x, y, z;
Initialization of Variable
• The variables are not initialized when they are declared. Hence, variables
normallycontain garbage values and hence they have to be initialized with valid data.
data_type variable_name
// INSTANTIATE OBJECT
enum WEEK_DAY DAY ;
// DAY is variable of type ENUM
Int main()
{
enum WEEK_DAY DAY;
DAY= THU;
printf("Value of Thursday is %d", DAY);
return 0;
} // OUTPUT 4
if (test==TRUE)
printf(“PASS\n”);
if (test==FALSE)
printf(“FAIL\n”);
#include <stdio.h>
#include <stdbool.h>
//boolasanaliasto _Bool intmain()
{
Booltest;
test=true ;
if (test)
printf(“TRUE \n”);
else
printf(“FALSE \n”);
}
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()
{
inti=101 ;
floatj=1234.123f; char
name[20]="Arjun";
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);
printf("[%s][%15s][%-15s][%15.2s]\n", name,name,name,name);
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 Left-to-right
^
(exclusive or)
- (Unary) 1 R-L
*,%,/ 2 L-R
+,- 3 L-R
= 4 R-L
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);
return1;
}
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, nextare*,/,%,operators and last are
binary+,
-operators and the associativity of allarithmetic 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
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
• Forex:
If x=10,
Then z=x--; // z becomes 10,
but z = --x; // z becomes9
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 ofanother type.
• Type conversion is of 2 types as shown in belowfigure:
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.
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.
• Forex:
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);
return1;
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 ”, 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 ”, big); return1;
}
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
Operator Example Same as
= 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:
Let us suppose the bitwise AND operation of two integers 12 and 25.
00001100
& 00011001
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output
00001100
| 00011001
Output = 29
Output
00001100
^ 00011001
Output = 21
~ 00100011
The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36.
Hence, the output is -36 instead of 220.
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output
Output = -36
Output = 11
212>>8 = 00000000
#include <stdio.h>
int main()
{
int num=212, i=1;
printf("\n");
return 0;
}
Int main()
{
int x= 2, y=3, z=-8;
x=x<< y;
printf("%d\n",x); //16
x=x>> 2;
printf("%d\n",x); // 4
z=z>> 2;
printf("%d\n",z); //-2 (?)
}
int main()
{
short i= 2 ,j=3;
printf("%d\n", i & j); // 2
printf("%d\n", i ^ j); // 1
printf("%d\n", i | j); // 3
}
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
#include <stdio.h>
int main()
{
int a;
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;
}
Output
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