C Language-Class Notes

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 17

Trainer:M.

PAVAN
PH: 7013088104
=========================================================================
First online session - c programming language

Q) did u understand .... the instruction i shared with all of u????


ans) yes

very very complex task ----->


Q) factorial of 5???
ans) 120

Q) factorial of 120???
silent mode....

Q) in our universe......how many human understandable languages are there???


ans) so many

Q) how many computer languages we r having???


ans) so many

why we need computer language:


to communicate with computer
how to do u communicate: by writing some set of instructions
program: is a collection of instructions
to write instruction .... what ever language u will choose: programming language

ex: programming languages: ABC,B,BCPL,FORTRAN,COBOL,ALGOL,C ,CPP,JAVA,PYTHON, etc

software field --> softwares


software: is a collection of programs
program: is a collection of instructions

one person wants to communicates/talk to another person --------------


ans) language: telugu, english, hindi, bengali, tamil etc

Factorial of 5 : 120

Factorial 120: silent?????

computer/machine: task is given to computer: can solve 1 nano sec

computer cant take any decisions on its own

user/developer/programmer: has to provide some set of / group of instructionsto


the computer then computer
can run those instructions & produce the result

myself/pavan sir/user/programmer/developer ========> computer

communication channel: language: computer language

computer can understand only 0s 1s

in the market ... how many computer languages are availables?

ans) so many
All those computer languages are classified into 2 types

1) Low level Langauges: the language in which writing a program / developing an


instruction is bit difficult for a user
programs written in Low level languages are not portable

machine language/binary language: this language purely consisting 0s 1s


addition of two numbers: 101000 0100001 11111000

Assembly langugage: english words: mnemonic words


mll===> 11111000
all =====> add
sub
mul
div
mov

2) High Level Languages : language where programmer can feel very easy to write
programs
ex: C,C++, JAVA, PYTHON etc
a) program written in H.L.L are portable
+

elements of natural language: english

tamil movie : playing:audience(telugu)

1) telugu dubbed movie::::::::::: compiler


2) tamil movie: every dialogue:subtitle: telugu:::::: interpreter

PRIME MINISER(HINDI) =====> CHIRALA =====> OUR PEOPLE


( TELUGU)
APPOINT: TRANSLATOR

TRANSLATION CAN BE DONE IN 2 WAYS:

1) after 10 mins: translator: can translate : total speech:


telugu
2) after completion one line: translate: telugu

H.L.L(elements of natural langu: english, mathematical


symbols):====>computer/machine language(0s 1s)
Translator: is a program / software which will convert programs
developed in one computer language into another computer language
1) Assembler: to convert instruction written in A.L.L into
machine understandable code

2) compiler:
i wrote one c program- 12 lines of instructions
12 lines of program - source code (human
understandable) ===> compiler
3) interpreter

All High level languages are classified into :


a) compiled languages: C, C++
b) interpreted languages: ruby, python

what is compilation?
ans: the process of converting program(source code) into machine understandable
code by the compiler

During compilation ... compiler will find out ---------------- type of erros
ans: syntax

Errors are of 3 types


1) syntax 2) Logical 3) Runtime

What is syntax?
rules framed by any programming language

what is debugging?
the process of identifying the bug & removing the bug from the program

what is a bug?
error in your program

Interpreter: will convert the total program in to machine understandable code line
by line

compiler
interpreter
1) total - all at a time
1) total - line by line

2) intermediate code - saved 2) no


intermediate code generated

3) it required more memory 3) no


memory problem

4) execution is faster
4) execution is slow

5) ex: c, C++
5) python, ruby etc

Note: java is both compiled & interpreted

C : is a mother of all programming languaes

PYTHON: INTERPRETER MACHINE

HISTORY OF "C" LANGUAGE:


=========================
Father: Dennis Ritchie in 1972
D.T & KEN THOMPSON - AT & T BELL LABORATORIES, USA

TELEPHONE, TRANSISTOR,LASER, COMMUNICATION SATELLITES, SOLAR CELLS ETC


1961 - MIT,GE,BELL LABORATORY - PROJECT - MULTICS (MULTIPLEX INFORMATION &
COMPUTING SERVICES)-MULTITASKING OS

1969- BELL LAB - TEAM - KEN THOMPSON, DENNIS RITCHIE & TEAM - UNICS(UNIPLEX
INFORMATION & COMPUTING SERVICES)- SINGLE TASKING OS
UNICS - MULTI TASKING OS
ASSEMBLY LANGUAGE: LOT OF PROBLEMS
FAMOUR PROG LANGUAGE: BCPL
KEN THOMPSON: B
DENNIS RITCHIE: NB - 1972 ===> C

UNICS - MULTITASKING OS - RE WRITTEN - UNIX

OPERATING SYSTEM:

DRIVE A VEHICLE: 1 CR: DRIVER

COMPUTER: DRIVER: OPERATING SYSTEM: SOFTWARE: COLLECTION OF PROGRAMS

C LANGUAGE
K & R C
ANSI C
C99
C11

SYSTEM SOFTWARE: ANY S/W DEVELOPED TO MEET THE NEEDS OF COMPUTER


EX: OS, DEVICE DRIVER, TRANSLATOR
APPLICATION SOFTWARE: ANY S/W DEVELOPED TO MEET THE NEEDS OF USER: MUSIC, VIDEO,
BROWER, TEXT EDITOR, POWER PNT

IN OLDEN DAYS: PEOPLE CAN USE LOW LEVEL LANGUAGES: SYSTEM S/W: UNIX: C - LOW LEVEL

C LANGUAGE: TEXT EDITOR, GAMES, ETC ===> HIGH LEVEL LANGUAGE

C LANGAUGE - MIDDLE LEVEL LANGUAGE

C LANGUAGE IS WIDELY USED IN - EMBEDDED DEVICE


EX: any device that consists of programmable component called microprocessor
washing machine, microwave oven

father - D.R - 1972


SUCCESSOR - B - KEN THOMPMSON
SUCCESSOR - BCPL

============================================================
ENGLISH:
ALPHABETS ==> WORDS ==> GRAMMAR ==> SENTENCE ===> PARAGRAPH

C LANGUAGE:
character set==> keywords/identifier/constants
etc=>syntax==>instructions===>Program

character set of "C" language:


-----------------------------------------
alphabets: a-z / A-Z
digits: 0 to 9
white space characters: space, newline , tab etc
special symbols: & ^ % $ # @ ! ~ ( ) * + -

Q:Why do we write a program???


ans: to process the data ( accno, rno, employee info, book info etc)

Q:Generally where do we store the data???


ANS: memory

Q: what is an identifier?
ans: named elements in the program
Ex: Variable, functions, arrays, structures etc

Rules for naming:


-------------------------
1) name must start with an alphabet only(lower case/uppercase) or underscore
Note: a) c is a case sensitive language b) highly recommended not to start
with underscrore
case sensitive langauge: lower & upper case letters are treated differently

2) from 2nd letter onwards it may be alphanumeric

3) no spaces,special symbols are allowed(except one spl symbol: underscrore)

4) keywords cant be used for naming purpose

names answer (v/i)


--------------------------------------------
1) pavan v
2) a1b2c3 v
3) AaaAaa v
4)007jamesbond Inv(started with digit)
5) student marks Inv(space)
6) amountin$ Inv(spl symbol)
7) x_y_7final valid
8) volatile Invalid(keyword)
9) Void valid
10) inT valid

keywords: reserved words


============
at the time of developing "c" langu- dennis ritchie & team, they reserved
some words for some
specific purpose.. those words are nothing but keywords:
frequently used keywords: 32

1) void 2) char 3) int 4) float

5) double 6) signed 7) unsigned 8) short

9) long 10) const 11) volatile 12) sizeof

13) typedef 14) if 15) else 16) switch

17) case 18) default 19) break 20) continue


21) goto 22) while 23) do 24) for

25) auto 26) static 27) extern 28) register

29) return 30) structu 31) union 32) enum

Note: always keywords must be represented in lower case only

Q: What is a constant?
Ans: fixed values in the program & these are also known as Literals

Types of constants:
Number constant:
a) integer constant:
1) it must have atleast one digit
2) it must not contains decimal point
3) either + ve or -ve
4) if no sign symbol: default: +ve
5) no special symbols,spaces are allowed

ex: 3 45 899 -98765


invalid ex: $456 9,000 9 87 654

in our mathematics also: number: decimal number system


1) decimal integers: in this number system digits: 0 to 9 Total: 10
ex: 123 741 2 89
2) octal integers: in this number system: digits: 0 to 7: Total : 8
ex: 0o725
3) hexadecimal integers: in this number system:
digits: 0 to 9
a: 10
b: 11
c: 12
d: 13
e: 14
f: 15

total: 16
ex: 0xFACE

Real constant:
1) is a number must contain one decimal point
2) u should not contain more than one decimal point
3) it may be either +ve or -ve
4) if no sign is specified default: +ve
5) real constant also known as: float point constant
6) represented in 2 ways: decimal form, exponential form
ex for decimal form: 0.21 1.258 99999.99
exponential form: 2.3e+7 9e-12

single character constant:


=========================
character set of C language: alphabets & digits & white space characters &
special symbols
1) in C language : single character constant must be represented within
single quotes
ex: '5'
2) with in a single quotes at max one character is allowed
'abc' ---> invalid
in C there are certain characters... even though they contains 2 letters
still they will be treated
as single character constants only..... backslash characters also known as
escape characters
'\n'
'\t'
'\r'
'\a'
'\f'
'\v'
'\"'
'\''
'\\' etc
for every student - unique number- for identification - roll no
for every character : unique number: ASCII : American standard Codes for
Information interchange

a : 97 A : 65

b : 98 B : 66

digits:
0 : 48

etc
white space character : 32

Total ASCII CODES: 256 ( 0 TO 255)

String constant: string is nothing but collection of characters enclosed


within double quotes " "
valid examples:
"abc" "y" "c language"

8 '8'
"8"
integer constant single character constant
String constant

desktop/ laptop: install

IDE : INTEGRATED DEVELOPMENT ENVIRONMENT


MARKET: SAMSUNG, SONY, THOMSON, MI , VU , aiwa ETC
PRACTICE C PROGRAMS: IDE:

1) visual studio code - MICROSOFT


2) code blocks
3) dev c++
4) Turbo c++
5) elicpse
6) atom
7) netbeans
steps involved from writing "c" program to execute the program
-----------------------------------------------------------------------------------
--------
1) creating / editing a program: in this step we will develop/create a program &
save that to
a file with any name but extension must be ".c"
file names: PRI_NAME.EXTENSION
Ex: add.c factorial.c
prime.c
in this step whatever c program written & saved to a file: is known as source file

to edit/develop your c program : text editor


ex: first.c ( user can understand)

2) compiling the program:


compilation: the process of converting source code into machine understandable code
software: compiler
the process of compilation will be done if our program is error free program
software: is a collection of programs
compilers: pre processor + compiler
Generally most commonly/repetedly perfomed task - for that in c language - built in
features - standard library
first source is handed over to pre processor.
preprocessor is a part of our compiler
jobs done by pre processor:
1) unwanted lines - removed
2) unwanted spaces - removed
3) comment lines - removed
4) adding content of standard library(in the form of header file)
once preprocessor job is over....source code is handed over to compiler , then
compiler checks for syntax errors
if your program is error free then compiler generates object code(machine
understandable code) & this object
will be saved to another file
software: compiler
ex: first.obj ( neither human understandable nor computer understandable)

3) Linking the program: all necessary files are linked in this step to the file
generated in step 2
first.obj + required files ===> first.exe ( machine understandable)

sofware: Linker

4) Loading/executing the program: in this step .exe file will be loaded from hard
disk to
RAM. because when cpu wants to execute your program, instructions must be available
in RAM itself

software: Loader

Q: from developing the application to until execution total how many steps??
ans: 4 steps
Q: in which step object code is generated??
ans: step 2

Q: cpu fetch the instructions from hard disk??? is it true/false


ans: false

Q: Loader will transfer the content of .exe file from RAM TO HD??
ans: false

Q: comment lines will be continued in .obj file also??


ans: no

Q: commet lines will be removed from our source file by preprocessor??


ans: yes

Q: who is responsible to link all necessary files & to add some extra code which is
required to run our program?
ans: Linker

Q: if a file contains machine understandable code such file we can call it as a


source file??
ans: no

Q: which of the following extension is allowed for C program


a) .x b) .xyz c) .c d) all the above
ans: d=> all the above

1) EDITING THE PROGRAM:


EDITOR
SOURCE CODE
SOURCE FILE
NAME: PRINAME.C

2) COMPILING : SYNTAX ( FREE FROM)


COMPILER: OBJECT CODE
FILE: PRINAME.OBJ

3) LINKING THE PROGRAM:


LINKER
FILE: PRINAME.EXE

4) LOADING THE PROGRAM:


loader

editor,compiler,linker,loader: Intrgrated Development Environment(IDE)


A) DEV C++
B) CODE BLOCKS
C) TURBO C++
D) VISUAL STUDIO CODE
E) ELICPSE
F) ATOM
g) onlinegdb.com (without installation)
etc

First Program in "C":


================
Q) What is a program?
ans: is a collection of functions

Q) What is a function?
ans: is a collection of instructions

syntax to create a function:

R.T fun_name(inputs)
{
GROUP OF INSTRUCTIONS
}

Note: here inputs is optional


() pair of parenthesis - is used for representing functions
{} pair of curly braces - to create block of instruction/statements
Functions are not executed on their own... they must be called by someone
In c language: our main functions is called by "operating system"
from main function we r supposed to return either 0 or 1 to the OS USING return
keyword
0 - NORMAL TERMINATION
1 - ABNORMAL TERMINATION

it is very good programming practice to include comment lines to your program it


improves the readability
& also understandability

syntax to write comment lines:


if your comment line is a single line comment it must be started with // (forward
slash)
if our comment line is multiple comment lines ... those lines must be
/*
line-1
line-2
etc
*/
Note: comment lines are ignored by the compiler

AS PER THE SYNTAX OF C LANGUAGE.... EXECUTABLE STATEMENTS MUST BE TERMINATED WITH ;

builtin function: readymade function: predefined function


to print anything to the console in "c" language we have the following built in
function

printf("pavan")
printf("welcome to c programming language")

Note: at the time of calling a function inputs supplied to the function call known
as "arguments"
All the builin function's information (known as function prototype) is available in
header files
for ex: printf -> this function prototype is available in stdio.h ( standard input
output header file)
( function prototype: name of function + how many inputs + what type of inputs +
order + return type)
any statement that starts with # symbols is a preprocessor directive statement

for main function eventhough return type mentioned is "int" type... if u forgot to
write
return statement.... nothing will happen

1) dev c++
2) codeblocks
3) turbo c++
4) onlinegdb.com
5) from command line

preprocessor directive statements:

1) #include
2) #define ==> create a constant
create a macro

Q: Why do we write a program?


ans: To process the data
Q: in computer, where do we store the data?
ans: in memory blocks

Variable:
is named memory block which holds the data
name elements: identifier

Note: Every variable must be declared before it is used in the program.

syntax to declare a variable:

datatype var_name;
ex:
int x;
char ch;
float avg;

datatype represents following information about a variable:


a) what type of data u r going to store
b) how much memory to be allocated

Data types provided by C language:


=========================================
a) primitive/primary/fundamental data types
b) derived data types:
c) userdefined data types
=========================================
C supports the following fundamental/primitive/basic data types
1) char
2) int
3) float
4) double

character data type:


-----------------------------
1) To represent character data type in "c" we use the following keyword: char
char ch;
char result;
char gender;
2) Memory : 1 byte ( 8 bits)
3) Range: -128 to +127

integer data type:


-----------------------------
1) To represent integer data type in "c" we use the following keyword: int
ex: int rno1,rno2,rno3;
2) Memory : 4 byte (Note: size of the variable varies from compiler to compiler)
3) Range: -2147483648 to +2147483647
int x;
4) in a integer variable we store either + ve or -ve value

4 bytes: 32 bits

float data type:


---------------------
1) To represent float data type in "c" we use the following keyword: float
ex: float avg,wt,ht;
2) Memory : 4 bytes
3) Range:
4) precision: upto 6 digits ( no.of digits allowed in decimal part)

double data type: is same as float except accuracy of storing number with decimal
part having precision more than
6 digits
Memory: 8 bytes
Range:
ex: double x,longitude;

What is a declaration statement?


it is used to declare the variable at the beginning of the program

which operator to be used to assign value to a variable?


assignment operator
Symbol: =

syntax:
variable=value;

What is initialization?
at the time of creating a variable, if the value is assigned to a variable then we
can call it as a initialization

printf is a predefined function which is used to print the given string as it is or


it is used to print formatted string also

formatted string: string which contains format specifiers

format specifier: in "c" language format specifiers starts with % followed a


character

datatype formatspecifier
========= ============
char %c

int(decimal) %d or %i

float %f

double(long float) %lf

unsigned int %u

long long int %lld

unsigned long long int %llu

short int %hd (or) %hi

variable1 = variable2
ex:
result = a

when variable is used on right side of assignment expression, means


that we are referring the data
when variable is used on left isde of assignment expression, means that
we are referring the memory block

variable is hard coded means: when we are assigning some value to a variable with
in a program like the below is nothing but hard coding
ex: int x=34;
float avg=9.8;
char gender='m';

Best approach: take the input for a variable during runtime/ program execution
given by the user

to meet above requirement... C language provides u predefined/readymade/built in


function: scanf
scanf is used to read the data given by the user during program execution time

syntax:

scanf("formatted string",listofvariables)

note: every variable must be preceded by a symbol & (ampersand)


& - address of operator

scanf is a built in "input" function whose prototype (return


type+name+arguments info) is available in
"stdio.h"

delimiter: is the character to be used to seperate multiple inputs


default delimiter for scanf: either white space character (or) newline character

Q) can we use user specified delimiter?


ans: Yes u can

Qualifiers in "C": is a keyword applicable to data type . When qualifier is


applied to a data type then it is going to modify the behaviour(size or sign) of a
variable
==============
3 types of qualifiers
a) size: short , long
b) sign: signed, unsigned: is applicable to char,int type only but not to float &
double D.T
c) type: const, volatile

range of integer data type: -2147483648 to 2147483647


int x;
x can take either + ve or -ve

int phno; govt imposed one rule: 50 admissions: 40 boys + 10 girls


in that rural are no scope for girls: 50 boys

unsigned int phno; 4 bytes : 32


(or)
unsigned phno;
the above two declaration are same
range: 0 to 4,29,49,67,295
when unsigned qualifier is applied to a variable of type "int" then variable can
accept only +ve values
Q: suppose if u try to assign a -ve value what happens?
ans: no

int a; signed int a; signed a; (all are same)

signed int b;

Every variable of "int" type is by default "signed" type


for an integer: 4 bytes: 32 bits: so a total of 4,29,49,67,296 values we can store
( it inclues both +ve & -ve)

- ve range: -1 to -2,14,74,83,648
+ve range: 0 to 2,14,74,83,647

char: 1 byte: 8 bits: total values: 256 values ( both +ve and -ve)
range for -ve: -1 to -128
range for +ve: 0 to 127

range of char: -128 to + 127

RANGE OF unsigned char D.T: 0 TO 255

sometimes to meet our requirements (for ex: to store our mobile no : variable must
capable to hold 10 digit number
that should start with either 6/7/8/9) we have to increase the size of the
variables then we have to use size qualifier
on the data type
a) short
b) long
long int phno;
(or)
long phno;

size: 4 bytes : 32 bits

there is no difference between int & long int type under gcc compiler
However to meet our requirement... we can apply qualifier "long" one more time
ex: long long int phno;
(or)
long long phno;
Memory: 8 bytes: 64 bits

Total values: 1,84,46,74,40,73,70,95,51,616


range: -92,23,37,20,36,85,47,75,808 to 92,23,37,20,36,85,47,75,807

unsigned long long x;


Memory: 8 bytes: 64 bits
range: 0 to 1,84,46,74,40,73,70,95,51,615

to decrease size of int data type we must apply qualifier " short "
ex: short int mks;
(or)
short mks;

Memory: 2 bytes: 16 bits


out of 16 bits Total values: 65536
range: -32768 to 32767

Q: Can i use size (short,long) qualifiers on float data type?


ans: on float type: size qualifiers not applicable
on double type: only size qualifier applicable is : long

datatype formatspecifier range


size(in bytes)

==============================================================================
char %c -128 to +127
1

unsigned char % 0 to 255

int %d or %i -2147483648 to
2147483647 4

unsigned int %u 0 to
4,29,49,67,295

short int %hd (or) %hi -32768 to


32767 2

unsigned short int %hu 0 to 65535

long int ******** same as int type only


under gcc compiler ************

long long int %lld -


92,23,37,20,36,85,47,75,808 to 92,23,37,20,36,85,47,75,807 8

unsigned long long int %llu 0 to


1,84,46,74,40,73,70,95,51,615

float %f
4

double %lf
8

long double %Lf


10

const qualifier:
ex: const float pi=3.14; //literally this variable is locked(read only
variable)

int main()
{
int p=-8;
const float pi=3.14;
-------
-------
-------
-------
-------
p=-1;
-------
-------
-------
-------
-------

if u declare a variable with "const" qualifier....it means that we are declaring it


as a constant so that
you are not allowed to make any changes to that variable. if u try to make any
changes to that variable
syntax error will be generated

Q: what is another to create a constant in "c"?


ans: using #define statement

ex: #define PI 3.14

Operators in "c":
1) Arithemtic operators
2) Relational operators
3) Logical operators
4) Bitwise operators
5) increment & decrement operators
6) Conditional (or) ternary operators
7) other operators: . -> sizeof comma operator etc

Operand: is the data on which operation(addition/multiplication/comparision) is


carried out
Operator: to perform the above operation the symbol which we use is nothing but an
operator
ex: + - * / % < >

Based on no.of operands that operator can take.... operators are classified into
a) Unary operator: if an operator take only one operand to perform operation...
then it is unary operator
ex: unary minus,unary plus, increment,decrement operator etc
b) Binary operator: if an operator takes two operands to perform the operation...
then it is binary operator
Note: All arithmetic operators are binary operators
c) Ternary operator: if an operator takes three operands to perform the
operation... then it is binary operator
Ex: conditional operator (Symbol: ? : )

Arimetic Operators:
================
+ - * / %

/ division operator: returns quotient as a result


% modulo division operator: returns remainder as a result

You might also like