0% found this document useful (0 votes)
6 views11 pages

C Part 2 Notes

The document discusses various control structures in C programming, including conditional control (if, if-else, switch-case) and iteration (for, while, do-while loops). It explains the syntax and usage of these structures to manage the flow of execution based on conditions. Additionally, it covers function definitions, parameters, and the importance of reusability in programming.

Uploaded by

garaisubhajit343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

C Part 2 Notes

The document discusses various control structures in C programming, including conditional control (if, if-else, switch-case) and iteration (for, while, do-while loops). It explains the syntax and usage of these structures to manage the flow of execution based on conditions. Additionally, it covers function definitions, parameters, and the importance of reusability in programming.

Uploaded by

garaisubhajit343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

scanf("%d%d,&x, &ey):

sum=x+y;
printf("the sumof the twO numbers is =% d".sum);
getch();

1.6.2 Conditional Control


Control):
(Selection Control or Decision
In conditional control,the
the condition-test. If the execution statements depends upon
of
condition evaluates to
statements is executed otherwise another set true, then a set of
of statements is
followed. This control is also called Decision
helps in making decision about which set of Control because it
executed. statements is to be
Decision control structure in Ccan be
implemented by using:
i If statement
ii. If-else statement
iii. Nested if else statement
iv. else-if ladder
V. case control structure/ Switch case statements
vi.
vii.
conditional
If
operator
statement The if statement controls
conditional
branching. The body of an if statement is executed if the
value of the expression is nonzero. The syntax for
the if statement has two forms. Example:
if (i> 0)
y=x/i;
else

X= i;
y=f(x );

. lI-else statement: This is a bi-directional control statement. This


slatement is used to test a condition and take one of the two possible
4cons. If the condition evaluates to true then one statement (or block
19
20
21
largese"c); printf("%d
the is CODE CODE CODE CODE
c>b){ &&
c>a &&
if(c>d }else
largest",b); printf("%d
the is
b>d)! &&
b>a && if(b>c }else
largest"
a); printf(%d
the is eELSE Nested,Block EES Block IF
Hested
a>d){ && a>c &&
if(a>b
&d); &b,&c, &a, d%d" Scanf("%d
%d% False True J False True J
a,b,c,d:
"): values
ofprintf("Enter
the
a,b,c,d; int CONDITION-3 CONDITION-2
(){ main void
#include<stdio.h>
ladder. elifse called nesting
is type
of Block Block
This part. else last the except part else every statement in else
ifanthere
is which nesting False True
in type
of s
a isThiladder:- Else
if ix.
CONDITION-1
}
return
0;
} statement. else if of
year"); printf("Not
leap a known
as this
1s then else, and if
both body
of the in or
}else{ statenestmenting else body the either
statement
within body
of.if-else thstatement
ehave or statement:
weIf if an ofelse Nested
if Vii.
year"):
printf("Leap
el{se J return
0;
year"); printf("Not
leap a printf("%d
number",number); odd is
else } else
year");
printf("Leap
0)
{ 400= (year
% if printt("%dis
even
400 divisible
by number",number): if(number%2=-0){
year
is check
if condition
to else /nested
if &number); scant("d",
{ 0)=100 (year% if number:"); rintt("entera
100 by umlber-0; int
divisible is
year check
if condition
to else//nested
if main(0! int
0) (year #includestdio.h>
4
&year); %d", scanf("if
year; int evecuted. statements)
is
main(){ int of
block (or statetents) of
<stdio,h #include eNCuted is
statement otherotherwise
main)
voi<conio.h>
d#includeexample lcode value2: case
int
default: //optional
break;//code//optional
casebreak:
//codevaluel:
Modulus\n");
Subtraction\n");
Exit\n");Division\
printf("4.
printf("6.
Multiplication\n");
scanf("%d",
&choice);
printf("Enter
choice:"); n");printf("2.
Addition\n");
printf("3.
yourprintf("5. printf("1. choice;#include<stdio.h>
printf("Select switchlexpression)generalThesubstandituteSwitch printf("%dJelsel
to to to a
be be be clearer is
executed syntax case the
an executed; executed; for
option
format long
stofatements: largest",d);
if switch than if
22 from all statements
cases follows:-case
statement else-if Switch
the
are
list laddermoreand
not case
below:\n"):
matched: has
is
statements
as

flexiblity
are

Iterations
controlled or 1.6.3similar
perform vi.
block Conditional
Iteration default: case 6: case 5: case 4: case 3: case 2: 1:
scanf("%d
case(choice)
switch
printf("Enter b;
// int a,
to break; printf("%d
printf("Exiting...\n");
printf("Invalid break; printf("%d break;
break; printf("%d break; break;
printf("
of or simple printf("
%d-%d read
with if-else
statementsloops two
Control
the conditional
operator:-
statement.( %d %d",numbers
help are / * + two
% %d %d %d=
used % &a,
of
several Loops ( choice\n"); %d= = %d\n", a,
= numbers:
= &b);
a when It %d\n", %d\n", %d\n",
23 test operations.
discussed
already
earlier) is %d\n",
): a
condition.
times.The we ternary a,
");
a, a,
want a, b, b, b, b,
It b, a a a a
/ * - +
to
is
operator a b); b); b); b);
repetition
The used %
execute b);
statements to
doand
of a
statement operations is
lops used
in
the to
is
i. iii. i. i. There
becomesfalselo.op
num++;
i. while(num<=5)
return0;d\n",num);
printf("% num=l;int mainint ) Example (condition)
statements;while Syntax:
{
condition While
Do-While
#include<stdio.h>
#include<conio.h> known. are keep
Thicondition
remainstrue.while
s when isloop
Do-whi
loopFor loeopWhilolope
the
on
loop the loop being :
In following executing
loop condition is
is satisfied a
: used a while
simple three
is the we
whenfalse, typesrepetitively
of
24 loop
theloop loop, have
this
wil a loops:-
number it
the condition
executes,keep until
terminated.
gets running. the
of
and test
iteration as
long as condition
long
1s as
not that

initialization
for(initial Syntax: (after For Syntax:
loop loop:Foriii.
the return0; num+t;
("%d\n",2*num);
while(num<=5); #include<stdio.h>
num=1;
printf #include<conio.h> statements do
do}while(expression):
int main)int Example { condition
Do 2nd being Do

value; loop is while time while


like This In in
runs) (if C do
isand
is loop
condition; any) a looploops,
while also
onwards. notwhile
each ,the is knownsatisfied is
loop very for exactiy
separated loop
condition/s loop
incrementation but easy
as the
is exit and like
25 and
in mostly loop
by for a control it
gets checks willwhile
aand
semicolon. loop define used.
or the loop. run loop
ecrementation) the
increment/decrements we
tell in condition the the
a once only
the single
loop even
difference
statement. from
the if
new the the
parameters and When
passed 1.7.1Formal A 1.7
main(). is AsFunction: The
function C. h a. d\n",number);
return0;printf("% number;int main)int Example: statements;
alwe
l #incl#iunde<coni
clude<sto.dhi>o.h>
the sometimes GotoContinue
constructs. Break three
lconstructs.
oop for(number-1;number<-5;number++)
variables we
function call know, is
types
to
Parameters :The :The
it a a
block also :The of
yXfunction
and while there is loop
we goto Break
of referred continue
created
calling and statements statement
control
to in always statement
obtain main()
Actual to
statement
the as statements
26
needs at
the
function. or unconditional
Parameters:
least
one that is is
sum anywhere a used
parameters, can is
jump are
not
of In perform to
andy. xthe function used
else jump
statement exit
example we in a to from
particular
in statement. exit
woula the C,
which from the
above,progran, and
that task. the Ioon
we
Pa is

1.7.3 There 1.7.2 andthe


AdvantagesAccording
A. B. A.
Different Types
<stdio.h>
#include This
void Functions code.
User-defined
reduces by
floor)
etc.Library are program.
Reusability
functions.
multiple We again
We By
printf("x-y
%d",res);
x=10,y=7;
=int int int main() C However, from actualparameters
res the header two can using
sub(int,int);// function of can of to
any and
= types
Functions: the
sub(x,y); Aspectsprogrammer, the C Functions: track call a
placefunctions,
with files Function is again function: example
C
has comnplexity of the functions a
functions:
of such functions large in in
arguments
arguments main a a are
function Function are program. above,
calling program.
C we
so as x
the achievementprogram any and
of
that scanf(),
are in can
27
with and
and Calling: a functions C number avoid y.the
big
he/she the programming: is
formal
return returnsreturn functionsprintf), always easily
program rewriting
which of of
can Cwhen times parameters
value values:
a functions.a
value: use gets(),
and which are overhead
and it it in same
many declared is a
optimizes puts(), dividedprogram
arguments are logic/code are
times.
created in a
ceil), in and
the a into and
the b,
It C
C. value void return
value
#include<stdio.h>
sum();int main()int This
Functions main)#include
<stdio.
int h> Functions
This wiB.th
float sum(float
x=10.56,y=7.22; int
printf("Sum nt
=ic=
int %d",c):sum); function printf("x
%f"z);
ty= sum(x,y); float void
m()//function z
function return(a-b);argumentssubint
=
without atb; a,float sum(float,float):
has has
no // a,int
arguments b) argumentargument
s, withoutsand return
arguments, //tunction b)
with //function value/7/tunction
28
but
no and it
arguments D but with does
it with
has not with
return arguments with
a values:
return return
return return
value
and
and arguments
values: na
return value: and value:
no and
data rt
type. no

the locations
collection has number
A1.8.1 lot number We
variable Array:1.8 This D.
array's
group int //functionsum)
void main()
#include<stdio.h>int Functions
function
memory Important a of require printf("x= int void
sum);sum);
similar
concept sum return(sum);
printf("x=%d;y=%d;z=%d\n'x,y,z);
int int
components names
of of printf("Sum x=15,y-35,z=5;
%d"sum); =
of with sumn
x=10,y=20,z=5;
of
variables. =
Thevariables data data a
variety x*y+z;
has
without
similar
single called =
Information when %d no x+y+Z;
array's values entries. ;y=
are arguments
There the of arguments
of name. "Array"data various
size all the is
%d;z=%d\n"x,y,z);
program's
Programmers with
kept on items necessary. may
must same to and
variables, no
29 in Arrays simplify be arguments and
be
close data no
stored instances
complexity
an The returnwithout
in
proximity type
integral C: this beçome while
in C and
make continuousprogramming
process. where working
value: return

constant.An rises return


perplexed
to up workingalong values:
one An data
an with
anotherarray array
memorylanguage with
with by a type
array's huge
The is the the
in a a
pointers,wehe A 1.Therefore, 9 move Asarray advance.In
known inruntime. Any corting.
TheduringStatic 1.8.3 elements. eacharray. must
pointer isa an Algorithms Using same Less 1.8.2 lasistngleiteimsnteger name
Definition an
c other cannotarray, number Limitations data element elenments
element Bythedeclare data codeBenefits line, of and
programming array's and
adding
elements structures using array pe is
tyN wrapped
you
an a
contain only of of
determining that one A
canvariable of the required of are array. subscript/
can
Pointer:
components objects elements or are by adistinct into Arrays
loop name located in
directly or array
Drawbacks one. a access
removing
one comnponents include simple randomsquare
language. used toand
variables. singlesince, in at index
place of can iterate C:
the that include
the to index any
accessthe to are arrays. be index, data we
store forward an same implement access
elementbracketvaris,able.
will of maximum
accessed from structure may and -0
30 By element kept of Arrays the we data
the different data be The index 0 of cansuch
using can combine (size
or in stored in structure an
regionaddress
in array's in and be
orderly
back,takes type accesS arrays. usingby array
C
O(1) size-1, to
of used as
the data employeeSalary|5],
array
can in : minimum .An
size time. N array's
variable of as
time those any variables is to
memory kinds. be the
memory another appropriate. cannot 1), access
an
since stored. element
we
array for respectively. array.
num may If firstspecific
identifier we be searching, not, with
variable locations. A must alkoro access of
have and In
wite single wethe a an
to he
or

characters:
message|20]; 20 String
Strings
charDeclaration:
following C:
1.10.1
sequence
terminated In 1.10addressHere, of
A. Example: Variable's
derived
message[20];
printf("Enter char stringStrings String Initialization:
fileInput: Strings
literal.
char with String int int For
String
C *ptr A
usingmessage]= the Some
programming ptr isa =
from can For can in 100;
= data
text of &A; value
the code C character handling
the be example, can characters
common type.
"Hello be pointer
a "fgets" is
message: user: read initialized declares be
stored.
For
"Hello
World": the declared in
function. from operations language,
arrays.
that to defining
c: a
following
World"; a tundamental From
"); the string is variabie
at
user as terminated A pointer
For the arrays string
named null-terminated
that
31 example,using code time of
can typeint variables,
of handling
the initializes of "message'" characters. with
be
declaration data
"scanf"
the performed a
null and is
following character is we
types,
the that character done utilise
function For initialized
with
"message" carn a
using example, on pointer
code using
array (*).
hold strings
or a (\O').
reads from stringstring up nuil
is is
the in a
to a
a a
struct_name
struct The ortype
variables 1.11
Indestination[20]: :
char"destcharinatstiorin'ng: For strcmp: strcat: strcpy: strlen: such asC.
membern; memberl;
typenmember2;
type2 typel a C,
strcpy(destinatsoiourn,ce); ManiStpriulngsStatrinogn: the filSte ringsStOutrinpgutOv: ertlony
syntax class that Structure
a sourcel] example, printf("Mesmeage%ss: a\|gne"); scant("%19s",
structure Returns
Copies can
incanunder Compar
Concates enates "mes age" using the can
for other = be bè
in
declaring contain a is c: "Hello"; the one the string"fputspr" inted mes age):
programming single a following two two string length manipulated
composite
variables to
a name. strings.strings. to of functhtoetion. the //
structure a using console: console reads
of Itdata code another. string. For
32 languages. allows various up
different example, using to
in type copies
C 19
is you thàt
thtehe string
as types, the the characters
to
grOus "source" "printf"
follows: handling following
define
similar function to
togethera avoid
custom string functions code
to
a or buffer
record related to prints to
data in a

variable_name.member2=
1.12 addition, Structures
related
be as variable_name;
membersHere,value2; notation, struct_name
like You struct typeOnce membern and(tynel Here,
structure: The similar that Infunctions. variable this:
union_name
member1; union C,
member2;
type2typel passed linked
can Union can using you each struct_name
syntax a valuel through
to union data
hold of
name.member1 then member are
a in
structures lists,
are the the have
structure, as
for c: together often and the
data is arguments access followingdefined typen).
a trees,structure.
declaring special value2 can names is
of can used the
different
but and the beYou
befor are = a of name of
data valuel; members structure,
syntax:
all to graphs. to
usedeasier acan the
members a the different
type functions represent members,
define of
union types, to values the
33
that processing
define They you structure,
but of data as
inshare allows complex that the can
or can many each
C only custom type.
is the returned you structure declare
one you members with and
similar same and also data
want
data be its
type to manipulation. variables member1
memory define as structures,
used to using own
at types as
to values assign
a you data
that time. a to the through
that of
space.variable to need, type
of from can group such dot that
It the
a is In
open
arguments: permanent
lo data data keepusing union Unions
In 1.13 depending ofmembersHere, variable
variable_name.member2
value2; = notation,
this:
like You union type Oncemember. largest(typel
membern Here, membern;
C, different typen
open from File track valuel can using you
the storage file unions, to union union_name
are through
Handling represent of then are
a e handling of on often thname.member1 the have
file. the file thbasis. types e the
which and name
file, that because the union. access following
Thename in used value2 defined typen).names
writing variable_name; is
mode
C, Fileinvolves can member-
in context.value a in
the
ofyou handling c: they a in
th e
be
compact are =
the data situations
that valuel; syntax:union, a The theof name
can use used can
However,
is the members siz e
file working
the to in currently use.in
leacd could way. values members, of
34
be to the C to you of the
open,
"r" fopen involves to where the
file, store with unexpected you beFor
that of can union,
for an union iseach
and example, you th e
and
function, integer,
need you declare
reading, andfiles,
closing
opening need union with and
the want
retrieve which to variables determinedmember1 its
mode results be ayou to
float,
"w" which the to using own
a careful represent assign
for in file. file, data are if might or data
which takes a you a Hhe that of through
writng reading type string. use to by
on don't when data fhe 3. thetype
two of a
to a

andfscanf(fp,
This "%d", int x; like
&x); example: pointer.
hefp
To tfprintf(fp,
world!"):
This"Hello, printf,
anlike To
but pointer to
This *fp; Here'
fpFILE s or
(overwriting
editors be This fcloseWhen
Filefclose(fp): "r+"
read example: write a =
used
handling storescode scanf, code FILE code
fopen("myfile.
code function,
you're to an for
to data data
complex to closes it
reads but writes read opens
structure examplereading
build in from the
in done the reads output
writesthe to or
C the like an the a the file
variable a file, write bxt", of and
databases. a is file working integer input file, "myfile.txt"
that filefor
wide a this: string
you data "w");
howwriting. if it
powerful
represented you represents already
x.
from from can to
variety witha can "Hello, to open
the
the ause touse exists),
35 tool file a file. a
of file, file world!" file the file
by instead the the
applications, for the represented fprintf
instead writing, for
you fscanf file. "a"
working fp to writing: for
pointer. should of You
function,
the the function, appending
console.theof and
with console. file can
from close by returns
the represented then
data, which which
simple it fp to
using Here's use a
and pointer, works Here'sworks pointer the
text can this file,
the an by
This
cOmpiler.#pragma: #endif DEBUG
#ifdef #ifndef:
includedirectives
These
#ifdefand#define PI Forvalues#define:
defined, whethera 3.14159, This <stdio.h>
#include
following
directive: Hoader
function,obiects
#include:
directives
beginning PREPROCESSER
header DIRECTIVES:
In 1.14
// Preprocessorrequired
preprocessor C
directive Code example,directive
you a that that files preprocessor
For to specificmacro 3.14159 you you This in of before files,
execute would your
contain Ca
example, is
would if do is
not directives
has are you used would codedirectiveinclude: line. thdefine
e before
used section use change code
if use been used want to declarations Some directtheives
you to DEBUG the the define includeuses. is are
constants,
is
defined
of to used of code
can
provide following
conditionally throughout
following to For compiled.
indicated
code defineconstants the is are
36 use
is examnple,
the to instructions
and
compiled.
defined or include
header
most
used
for commonly
only
the
additional not. directive: a stdio.h
funcions,
directive: byperform
#pragma ifFor
compile
constant the n T
a execution your you a They that
certain
example, header hash
want
variables, other usedare are
instructions
directive code PI Code. files symbol
macro with of file to processed
tasks
if Constants in
use preprocessor
depending
you the your
a usi the and to
to has program.
value the at that
#) include
disaDle want by
to been
print code.o
are the
the to on of are

argumentsArgument Argument
hello
2:
In Argument
./a.out would
program Forconsole,theargv.
1: 0: to This <stdio.h>
#include s array which To allow
int Here'represents to the ie In memory. 1,15 specific
return 0; for int i;
this main(int read modify executed. C,
program
example, printf("Argument
code
It (i of
fromthe Command
example, see an takes vou you
then = compiler
with defines 0; examplestrings command its to can
(including the i<argc, the
world following loops two source code.Command
cus pass
the ifalong argc; number
that ine
argc you a char arguments: tomize
command through of line command warningsS,
with main it+) contains argument
e is compile %d: *argv) how
thequal
argumentsof the
operating line
name output: function
its {
%s\n", command
to behavior
line index. the argunents line or
to this {
read the argC in
37 of 3, argv actual arguments c: to
thesince arguments that i, command system's
code argv[il); and in specify
arraytakes line of
program arguments. argv. C, yOur are
there and you
arguments,
and two command
program values to the
are "hello' line argc use
then your alignment
itseli). prints
arguments, arguments
three the that
and run is program
The each and an main without line, are
command "world", the integer
argv of
argv function, passed
and
resulting argument argc in having when data
array C: is they
line you and an that
to it in
contains three strings, with argv[0] containing the name of the
"hello", and argv[2]] containing
program, argv(1]
containing
feature
of C
"world".
are a powerful
Command
and line arguments
programming,
they can be used to make your programs more flexible and
situations.
adaptable to different

38

You might also like