MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey

2,070 views 84 slides Dec 17, 2022
Slide 1
Slide 1 of 84
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84

About This Presentation

���MCA 101�Programming in C with Data Structure�UNIT I��Prof. Rohit Dubey


Slide Content

MCA 101
Programming in C with Data Structure
UNIT I
Prof. Rohit Dubey

MCA 101
Programming in with Data Structure
UNIT I
Fundamentals of C Programming :
Structure of a C Program, Data types, Identifiers and keywords,
Operators & expressions, Preprocessor directive, Input output,
Casting, Precedence, Scope of variables Control Constructs and
Iteration Constructs Functions: Defining and accessing: passing
arguments, Function prototypes, Recursion, Storage classes

Structure of a C Program
Tofindthesumoftwonumbersgivenbytheuser
Itisgivenby:
/*Sumoftwonumbers*/
#include<stdio.h>
intmain()
{
inta,b,sum;
printf("Entertwonumberstobeadded");
scanf("%d%d",&a,&b);
//calculatingsum
sum=a+b;
printf("%d+%d=%d",a,b,sum);
return0;//returntheintegervalueinthesum
}
*conio.hisaCheaderfileusedmostlybyMS-DOS
compilerstoprovideconsoleinput/output.Itisnotpart
oftheCstandardlibraryorISOC,norisitdefinedby
POSIX.Thisheaderdeclaresseveralusefullibrary
functionsforperforming"istreaminputandoutput"from
aprogram.

Output

Data Types in C
•A data type specifies the type of data that a variable can store such as
integer, floating, character, etc.

Basic Data Types
•Thebasicdatatypesareinteger-basedandfloating-pointbased.C
languagesupportsbothsignedandunsignedliterals.
•Thememorysizeofthebasicdatatypesmaychangeaccordingto32
or64-bitoperatingsystem.
•Let'sseethebasicdatatypes.Itssizeisgivenaccordingto32-bit
architecture.

C Identifiers
•CidentifiersrepresentthenameintheCprogram,forexample,
variables,functions,arrays,structures,unions,labels,etc.An
identifiercanbecomposedofletterssuchasuppercase,lowercase
letters,underscore,digits,butthestartinglettershouldbeeitheran
alphabetoranunderscore.Iftheidentifierisnotusedintheexternal
linkage,thenitiscalledasaninternalidentifier.Iftheidentifieris
usedintheexternallinkage,thenitiscalledasanexternalidentifier.

•We can say that an identifier is a collection of alphanumeric
characters that begins either with an alphabetical character or an
underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions,
labels, etc. There are 52 alphabetical characters (uppercase and
lowercase), underscore character, and ten numerical digits (0-9) that
represent the identifiers. There is a total of 63 alphanumerical
characters that represent the identifiers.

Rules for constructing C identifiers
•Thefirstcharacterofanidentifiershouldbeeitheranalphabetoran
underscore,andthenitcanbefollowedbyanyofthecharacter,digit,or
underscore.
•Itshouldnotbeginwithanynumericaldigit.
•Inidentifiers,bothuppercaseandlowercaselettersaredistinct.Therefore,
wecansaythatidentifiersarecasesensitive.
•Commasorblankspacescannotbespecifiedwithinanidentifier.
•Keywordscannotberepresentedasanidentifier.
•Thelengthoftheidentifiersshouldnotbemorethan31characters.
•Identifiersshouldbewritteninsuchawaythatitismeaningful,short,and
easytoread.

Exampleofvalididentifiers
1.total,sum,average,_m_,sum_1,etc.
Exampleofinvalididentifiers
1.2sum(startswithanumericaldigit)
2.int(reservedword)
3.char(reservedword)
4.m+n(specialcharacter,i.e.,'+')

Types of identifiers
•InternalIdentifier
•Iftheidentifierisnotusedintheexternallinkage,thenitisknownas
aninternalidentifier.Theinternalidentifierscanbelocalvariables.
•ExternalIdentifier
•Iftheidentifierisusedintheexternallinkage,thenitisknownasan
externalidentifier.Theexternalidentifierscanbefunctionnames,
globalvariables.

Let's understand through an example.
intmain()
{
inta=10;
intA=20;
printf("Valueofais:%d",a);
printf("\nValueofAis:%d",A);
return0;
}

Output:
•Value of a is : 10
•Value of A is :20
•The above output shows that the values of both the variables, 'a' and
'A' are different. Therefore, we conclude that the identifiers are case
sensitive.

Keywords in C
•Akeywordisareservedword.Youcannotuseitasavariablename,
constantname,etc.Thereareonly32reservedwords(keywords)in
theClanguage.
•Alistof32keywordsintheclanguageisgivenbelow:

Keywords in C

// C program to demonstrate
// auto keyword
#include <stdio.h>
int printvalue()
{
auto int a = 10;
printf("%d", a);
}
// Driver code
int main()
{
printvalue();
return 0;
}

C Operators:
Anoperatorissimplyasymbolthatisusedtoperformoperations.There
canbemanytypesofoperationslikearithmetic,logical,bitwise,etc.
•Therearefollowingtypesofoperatorstoperformdifferenttypesof
operationsinClanguage.
•ArithmeticOperators
•RelationalOperators
•ShiftOperators

C Operators:
•LogicalOperators
•BitwiseOperators
•TernaryorConditionalOperators
•AssignmentOperator
•MiscOperator

Precedence of Operators in C
•Theprecedenceofoperatorspeciesthatwhichoperatorwillbe
evaluatedfirstandnext.Theassociativityspecifiestheoperator
directiontobeevaluated;itmaybelefttorightorrighttoleft.
•Let'sunderstandtheprecedencebytheexamplegivenbelow:
intvalue=10+20*10;
•Thevaluevariablewillcontain210because*(multiplicativeoperator)
isevaluatedbefore+(additiveoperator).
•TheprecedenceandassociativityofCoperatorsisgivenbelow:

C -Preprocessors
•The C Preprocessor is not a part of the compiler, but is a separate step
in the compilation process. In simple terms, a C Preprocessor is just a
text substitution tool and it instructs the compiler to do required pre-
processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.
•All preprocessor commands begin with a hash symbol (#). It
must be the first nonblank character, and for readability, a
preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor
directives −

C Input Output (I/O)
•In C programming, printf() is one of the main output function. The
function sends formatted output to the screen. For example,

How does this program work?
•All valid C programs must contain the main() function. The code
execution begins from the start of the main() function.
•The printf() is a library function to send formatted output to the
screen. The function prints the string inside quotations.
•To use printf() in our program, we need to include stdio.hheader file
using the #include <stdio.h> statement.
•The return 0; statement inside the main() function is the "Exit status"
of the program. It's optional.

C Input
•In C programming, scanf() is one of the commonly used function to
take input from the user. The scanf() function reads formatted input
from the standard input such as keyboards.

C -Type Casting
•Converting one datatype into another is known as type casting
or, type-conversion. For example, if you want to store a 'long'
value into a simple integer then you can type cast 'long' to 'int'.
You can convert the values from one type to another explicitly
using thecast operatoras follows −
WithoutTypeCasting:
intf=9/4;
printf("f:%d\n",f);//Output:2
WithTypeCasting:
floatf=(float)9/4;
printf("f:%f\n",f);//Output:2.250000

Type Casting example
Let's see a simple example to cast int value into the float.
#include<stdio.h>
int main(){
float f= (float)9/4;
printf("f : %f\n", f );
return 0;
}
Output:
f : 2.250000

Operator precedence
•Operatorprecedencedeterminesthegroupingoftermsinan
expressionanddecideshowanexpressionisevaluated.
Certainoperatorshavehigherprecedencethanothers;for
example,themultiplicationoperatorhasahigherprecedence
thantheadditionoperator.
•Forexample,x=7+3*2;here,xisassigned13,not20
becauseoperator*hasahigherprecedencethan+,soitfirst
getsmultipliedwith3*2andthenaddsinto7.

Operator precedence
•Forexample,x=7+3*2;here,xisassigned13,not20
becauseoperator*hasahigherprecedencethan+,soitfirst
getsmultipliedwith3*2andthenaddsinto7.
•Here,operatorswiththehighestprecedenceappearatthetop
ofthetable,thosewiththelowestappearatthebottom.
Withinanexpression,higherprecedenceoperatorswillbe
evaluatedfirst.

•When you compile and execute the above program, it produces the
following result −
•Value of (a + b) * c / d is : 90
•Value of ((a + b) * c) / d is : 90
•Value of (a + b) * (c / d) is : 90
•Value of a + (b * c) / d is : 50

C variable scope
•InCprogramming,everyvariableisdefinedinscope.Youcandefinescopeasthe
sectionorregionofaprogramwhereavariablehasitsexistence;moreover,that
variablecannotbeusedoraccessedbeyondthatregion.InCprogramming,a
variabledeclaredwithinafunctiondiffersfromavariabledeclaredoutsideofa
function.Thevariablecanbedeclaredinthreeplaces.Theseare:

Local Variables
•Variables that are declared within the function block and can be used
only within the function are called local variables.
•Alltheselocallyscopedstatementsarewrittenandenclosed
withintheleft({)andright(})curlybraces.Calsohasaprovision
fornestedblocks,whichmeansthatablockorfunctioncan
occurwithinanotherblockorfunction.Soitmeansthat
variablesdeclaredwithinablockcanbeaccessedwithinthat
specificblockandallotherinternalblocksofthatblockbut
cannotbeaccessedoutsidetheblock.

GlobalVariables
•In most cases, global variables are defined outside a function or any
specific block on top of the C program.These variables hold their
values all through the end of the program and are accessible within
any of the functions defined in your program. Any function can access
variables defined within the global scope, i.e., its availability stays for
the entire program after being declared.

Function prototype
•A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type. It doesn't
contain function body.
•A function prototype gives information to the compiler that the
function may later be used in the program.

Syntax of function prototype

Function definition

•Passing arguments to a function
•In programming, argument refers to the variable passed to the
function. In the above example, two variablesn1andn2are passed
during the function call.
•The parametersaandbaccepts the passed arguments in the function
definition. These arguments are called formal parameters of the
function.

Thetypeofargumentspassedtoa
functionandtheformalparameters
mustmatch,otherwise,thecompiler
willthrowanerror.
Ifn1isofchartype,aalsoshouldbe
ofchartype.Ifn2isoffloattype,
variablebalsoshouldbeoffloattype.
Afunctioncanalsobecalledwithout
passinganargument.

Return Statement
•Return Statement
•The return statement terminates the execution of a function and
returns a value to the calling function. The program control is
transferred to the calling function after the return statement.
•In the above example, the value of the result variable is returned to
the main function. The sum variable in the main() function is assigned
this value.

Parameter Passing Techniques in C/C++
•There are different ways in which parameter data can be passed into
and out of methods and functions. Let us assume that a function B()
is called from another function A(). In this case A is called the “caller
function” and B is called the “called function or callee function”. Also,
the arguments which A sends to B are called actual arguments and
the parameters of B are called formal arguments.

Terminology
•FormalParameter:Avariableanditstypeastheyappearintheprototype
ofthefunctionormethod.
•ActualParameter:Thevariableorexpressioncorrespondingtoaformal
parameterthatappearsinthefunctionormethodcallinthecalling
environment.
•Modes:
•IN:Passesinfofromcallertocallee.
•OUT:Calleewritesvaluesincaller.
•IN/OUT:Callertellscalleevalueofvariable,whichmaybeupdatedby
callee.

Important methods of Parameter Passing
•Pass By Value: This method uses in-mode semantics. Changes made
to formal parameter do not get transmitted back to the caller. Any
modifications to the formal parameter variable inside the called
function or method affect only the separate storage location and will
not be reflected in the actual parameter in the calling environment.
This method is also called as call by value.

•Pass by reference(aliasing): This technique uses in/out-mode
semantics. Changes made to formal parameter do get transmitted
back to the caller through parameter passing. Any changes to the
formal parameter are reflected in the actual parameter in the calling
environment as formal parameter receives a reference (or pointer) to
the actual data. This method is also called as call by reference. This
method is efficient in both time and space.

Recursion
•Recursionisthetechniqueofmakingafunctioncall
itself.Thistechniqueprovidesawaytobreak
complicatedproblemsdownintosimpleproblemswhich
areeasiertosolve.
•Recursionmaybeabitdifficulttounderstand.Thebest
waytofigureouthowitworksistoexperimentwithit.

o/p: 55

Example Explained
•When the sum() function is called, it adds parameter k to the sum of
all numbers smaller than k and returns the result. When k becomes 0,
the function just returns 0. When running, the program follows these
steps
•Since the function does not call itself whenkis 0, the program
stops there and returns the result.

C -Storage Classes
•Astorageclassdefinesthescope(visibility)andlife-timeof
variablesand/orfunctionswithinaCProgram.Theyprecede
thetypethattheymodify.Wehavefourdifferentstorage
classesinaCprogram−
•auto
•register
•static
•extern

The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage
class. 'auto' can only be used within functions, i.e., local variables.

The register Storage Class
The register storage class is used to define local variables that should
be stored in a register instead of RAM. This means that the variable has
a maximum size equal to the register size (usually one word) and can't
have the unary '&' operator applied to it (as it does not have a memory
location).
{
register int miles;
}

The static Storage Class
Thestaticstorageclassinstructsthecompilertokeepalocalvariableinexistenceduringthe
life-timeoftheprograminsteadofcreatinganddestroyingiteachtimeitcomesintoandgoes
outofscope.Therefore,makinglocalvariablesstaticallowsthemtomaintaintheirvalues
betweenfunctioncalls.
Thestaticmodifiermayalsobeappliedtoglobalvariables.Whenthisisdone,itcausesthat
variable'sscopetoberestrictedtothefileinwhichitisdeclared.
InCprogramming,whenstaticisusedonaglobalvariable,itcausesonlyonecopyofthat
membertobesharedbyalltheobjectsofitsclass.

The extern Storage Class
•Theexternstorageclassisusedtogiveareferenceofaglobal
variablethatisvisibletoALLtheprogramfiles.Whenyouuse
'extern',thevariablecannotbeinitializedhowever,itpointsthe
variablenameatastoragelocationthathasbeenpreviously
defined.
•Whenyouhavemultiplefilesandyoudefineaglobalvariable
orfunction,whichwillalsobeusedinotherfiles,
thenexternwillbeusedinanotherfiletoprovidethereference
ofdefinedvariableorfunction.Justforunderstanding,externis
usedtodeclareaglobalvariableorfunctioninanotherfile.

•The extern modifier is most commonly used when there are two or
more files sharing the same global variables or functions as
explained below.

MCA 101
Programming in C with Data Structure
UNIT I
Prof. Rohit Dubey
Thank You
Tags