MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
2,070 views
84 slides
Dec 17, 2022
Slide 1 of 84
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
About This Presentation
���MCA 101�Programming in C with Data Structure�UNIT I��Prof. Rohit Dubey
Size: 1.2 MB
Language: en
Added: Dec 17, 2022
Slides: 84 pages
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.
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
•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.
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.
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.
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.
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