0% found this document useful (0 votes)
24 views78 pages

Unit 3 1

This document provides an overview of the C programming language, including its structure, syntax, data types, and basic input/output operations. It covers essential concepts such as functions, variables, literals, keywords, and the usage of the printf and scanf functions for displaying and receiving data. Additionally, it explains the characteristics of different data types and how to declare and manipulate variables in C.

Uploaded by

21bcs008
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)
24 views78 pages

Unit 3 1

This document provides an overview of the C programming language, including its structure, syntax, data types, and basic input/output operations. It covers essential concepts such as functions, variables, literals, keywords, and the usage of the printf and scanf functions for displaying and receiving data. Additionally, it explains the characteristics of different data types and how to declare and manipulate variables in C.

Uploaded by

21bcs008
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

Unit - 3

C Language

By Yogendra Kumar
Universal starJng point
Header file includes functions
for input/output
#include <stdio.h> Main function is executed when
you run the program. (Later we will
int main() see how to pass its parameters)
{
printf (“Hello World\n”);
return 0;
}
Statement for
Curly braces within which Return value printing the sentence
statements are executed one to func7on within double quotes
after another. (“..”). ‘\n’ denotes end
of line.
Three steps to follow
1. Write a program and save it.
2. Compile the program using the correct compiler.
3. Execute the program
1. vi hello.c
#include <stdio.h>

int main()
{
prini("Hello World\n");
return 0;
}

2. $ cc hello.c
$

3. $ ./a.out
Hello World
Structure of a C program
• Every C program consists of one or more func7ons.
– One of the func7ons must be called main.

– The program will always begin by execu7ng the main func7on.

• Each func7on must contain:


– A func7on heading, which consists of the func@on name,
followed by an op7onal list of arguments enclosed in
parentheses.

– A list of argument declara@ons.

– A compound statement, which comprises the remainder of the


func7on.
Structure of a C program
• Each compound statement is enclosed within a pair
of braces: ‘{‘ and ‘}’
– The braces may contain combina7ons of elementary
statements and other compound statements.

• Comments may appear anywhere in a program,


enclosed within delimiters ‘/*’ and ‘*/’.
– Example:
a = b + c; /* ADD TWO NUMBERS */
In and Out only

Integers variables declared


before their usage.
#include <stdio.h>

int main()
Comments within /* .. */
{
int n,m;
scanf(“%d”,&n);/* Read the value of n */
m=n+n;
printf(“%d”,m); Input statement for reading
return 0; variable from the keyboard
}

Control character for printing


value of m in decimal digits.
The C Character Set
• The C language alphabet:
– Uppercase leWers ‘A’ to ‘Z’
– Lowercase leWers ‘a’ to ‘z’
– Digits ‘0’ to ‘9’
– Certain special characters:

! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank
Literals

Values such as numbers, characters or string of characters


whose values are self-evident are known as Literals.

There are four types of literals that exist in C programming:


◦ Integer literal
◦ Float literal
◦ Character literal
◦ String literal
Literals

Integer 500 3 10000


Floating point 6.14 800.798 0.883494

Character ‘A’ ‘a’ ‘2’

String “Agra” “3.14” “This is a String”


Keywords
• Keywords
– Reserved words that have standard, predefined meanings
in C.

– Cannot be used as iden7fiers.

– OK within comments.

– Standard C keywords:

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
IdenJfiers
• Iden7fiers
– Names given to various program elements (variables,
constants, func7ons, etc.)

– May consist of leIers, digits and the underscore (‘_’)


character, with no space between.

– First character must be a leWer.

– An iden7fier can be arbitrary long.


• Some C compilers recognize only the first few characters
of the name (16 or 31).

– Case sensi7ve
• ‘area’, ‘AREA’ and ‘Area’ are all different.
Valid and Invalid IdenJfiers
• Valid idenJfiers • Invalid idenJfiers
X 10abc
abc “hello”
simple_interest simple interest
a123 (area)
LIST %rate
stud_name
Empl_1
Empl_2
avg_empl_salary
Basic Data Types in C
int :: integer quan7ty
Typically occupies 4 bytes (32 bits) in memory.

char :: single character


Typically occupies 1 byte (8 bits) in memory.

float :: floa7ng-point number (a number with a decimal point)


Typically occupies 4 bytes (32 bits) in memory.

double :: double-precision floa7ng-point number


Precision refers to the number of significant digits a6er the decimal point.
Augmented Data Type
• Some of the basic data types can be augmented
by using certain data type qualifiers:
– short
– long
– signed
– unsigned
• Typical examples:
– short int
– long int
– unsigned int
Integer type
unsigned char è 1 byte è 8 bits
è 00000000 to 11111111 è 0 to 255

11111111 è 1×27+ 1×26+ 1×25+ 1×24+ 1×23+ 1×22+ 1×21+ 1×20

signed char è 1 byte è 8 bits


è 00000000 to 11111111 è -128 to 127

1111111 è 1×26+ 1×25+ 1×24+ 1×23+ 1×22+ 1×21+ 1×20


Integer type
Storage size
Type Value range
(in byte)
char 1 -128 to 127 or 0 to 255
unsigned char 1 0 to 255
signed char 1 -128 to 127
-32,768 to 32,767 or -2,147,483,648 to
int 2 or 4
2,147,483,647
unsigned int 2 or 4 0 to 65,535 or 0 to 4,294,967,295
short 2 -32,768 to 32,767
unsigned
2 0 to 65,535
short
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
FloaJng-point type
Storage size
Type Value range Precision
(in byte)
float 4 1.2E-38 to 3.4E+38 6 decimal places
double 8 2.3E-308 to 1.7E+308 15 decimal places
long double 10 3.4E-4932 to 1.1E+4932 19 decimal places

E or e means “10 to
the power of”
Some Examples of Data Types
• int
0, 25, -156, 12345, -99820
• char
‘a’, ‘A’, ‘*’, ‘/’, ‘ ’
• float
23.54, -0.00345, 25.0 E or e means “10 to
2.5E12, 1.234e-5 the power of”
The sizeof function
#include <stdio.h>
void main()
{
printf(“size of short int: %d\n”,sizeof(short
int));
printf(“size of int is %d\n”,sizeof(int));
printf(“size of long int is %d\n”,sizeof(long
int));
}
Constants
Constants

Numeric Character
Constants Constants

integer floating-point single string


character
Integer Constants
• Consists of a sequence of digits, with possibly
a plus or a minus sign before it.
– Embedded spaces, commas and non-digit characters are
not permiWed between digits.

• Maximum and minimum values (for 32-bit


representa7ons)
Maximum :: 2147483647
Minimum :: – 2147483648
FloaJng-point Constants
• Can contain frac7onal parts.

• Very large or very small numbers can be


represented.
23000000 can be represented as 2.3e7

• Two different nota7ons:


1. Decimal nota7on
25.0, 0.0034, .84, -2.234
2. Exponen7al (scien7fic) nota7on
3.45e23, 0.123e-12, 123E2 e means “10 to
the power of”
Single Character Constants
• Contains a single character enclosed within a pair
of single quote marks (‘ ’).
– Examples :: ‘2’, ‘+’, ‘Z’

• Some special backslash characters


‘\n’ new line
‘\t’ horizontal tab
‘\’’ single quote
‘\”’ double quote
‘\\’ backslash
‘\0’ null
String Constants

• Sequence of characters enclosed in double quotes


(“ “).
– The characters may be leWers, numbers, special
characters and blank spaces.

• Examples:
“nice”, “Good Morning”, “3+6”, “3”, “C”

• Differences from character constants:


– ‘C’ and “C” are not equivalent.
– ‘C’ has an equivalent integer value while “C” does not.
Variables
• It is a data name that can be used to store a
data value.

• Unlike constants, a variable may take different


values in memory during execu7on.

• Variable names follow the naming conven7on


for iden7fiers.
– Examples :: temp, speed, name2, current
Example
int a, b, c;
char x;
Variables
a = 3;
b = 50;
c = a – b;
x = ‘d’;
Constants
b = 20;
a = a + 1;
x = ‘G’;
DeclaraJon of Variables

• There are two purposes:


1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

• General syntax:
data-type variable-list;

• Examples:
int velocity, distance;
int a, b, c, d;
float temp;
char flag, op7on;
Address and Content
speed int speed;
speed=234;
1349

1350 11101010

1351 speed 234


1352 &speed 1350

Binary of 234

Every variable has an address (in memory), and its contents.


Address and Content
• In C terminology, in an expression
speed refers to the contents of the memory
loca7on.
&speed refers to the address of the memory
loca7on.

• Examples:
printf (“%f %f %f”, speed, time, distance);
scanf (“%f %f”, &speed, &time);
An Example
#include <stdio.h>
int main()
{
float speed, time, distance;
Address of speed
scanf (“%f %f”, &speed, &time);
distance = speed * time;
printf (“\n The distance traversed
is: \n”, distance);
return 0; Content of speed
}
Assignment Statement
• Used to assign values to variables, using the
assignment operator (=).

• General syntax:
variable_name = expression;

• Examples:
velocity = 20;
b = 15; temp = 12.5;
A = A + 10;
v = u + f * t;
s = u * t + 0.5 * f * t * t;
Advanced Assignment Statement
• Assignment during declara7on
int speed = 30;
char flag = ‘y’;

• Mul7ple variable assignment


a = b = c = 5;
flag1 = flag2 = ‘y’;
speed = flow = 20.0;
Input
scanf (“control string”,arg1,arg2, …, argn);

• Performs input from the standard input device, which is the keyboard by
default.
• It requires a control string refers to a string typically containing data types of
the arguments to be read in.
• And the (arguments) address or pointers of the list of variables into which
the value received from the input device will be stored.
• The address of the variables in memory are required to men1on (& before
the variable name) to store the data.
• The control string consists of individual groups of characters (one character
group for each input data item). Typically, a ‘%’ sign, followed by a
conversion character.

int size,a,b;
float length;
scanf ("%d", &size) ;
scanf ("%f", &length) ;
scanf (“%d %d”, &a, &b);
Input
Conversion Character Data Item meaning
c Single charcater
d Decimal integer
e Floa1ng point value
f Floa1ng point value
g Floa1ng point value
h Short int
i Decimal/hexadecimal/octal integer
o Octal integer
s String
u Unsigned decimal integer
X Hexadecimal integer

We can also specify the maximum field-width of a data item, by specifying a number indica1ng
the field width before the conversion character.
Example: scanf (“%3d %5d”, &a, &b);
Output
printf (“control string”,arg1,arg2, …, argn);

– Performs output to the standard output device (typically defined to be the


screen).
– Control string refers to a string containing formaqng informa1on and data
types of the arguments to be output;
– The arguments arg1, arg2, … represent the individual output data items.
– The conversion characters are the same as in scanf.

int size,a,b;
float length;
scanf ("%d", &size) ; printf(“%d”,size);
scanf ("%f", &length) ; printf(“%f”,length);
scanf (“%d %d”, &a, &b); printf(“%d %d”,a,b);
Forma@ed Output
float a=3.0, b=7.0;
printf(“%f %f %f %f”,a,b,a+b,sqrt(a+b));
3.000000 7.000000 10.000000 3.162278
Will be wrisen
Total Space exactly.
printf(“%4.2f %5.1f\na+b=%3.2f\tSquare
Root=%-6.3f”,a,b,a+b,sqrt(a+b));
3.00 7.0
a+b=10.00 Square Root=3.162
Lea Align
Aaer decimal Tab
place

For integer, character and string, no


decimal point.
Character I/O
char ch1;
scanf(“%c”,&ch1); /* Reads a character */
printf(“%c”,ch1); /* Prints a character */
ch1=getchar(); /* Reads a character */
putchar(ch1); /* Prints a character */

char name[20];
scanf(“%s”,name); /* Reads a string */
printf(“%s”,name); /* Prints a string */
gets(name); /* Reads a string */
puts(name); /* Prints a string */

Help for any command:


$ man gets
Operators in Expressions

Operators

Arithmetic Relational Logical


Operators Operators Operators
ArithmeJc Operators

X= 25; Y=23;

• Addi7on :: + X+Y 48

• Subtrac7on :: – X–Y 2
• Division :: / X*Y 575
• Mul7plica7on :: * X/Y ?
• Modulus :: % X%Y ??
RelaJonal Operators
• Used to compare two quan11es.
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
RelaJonal Operators
int x = 20;
int y = 3;
float a=20.3;

if ( x > y ) /* 20 > 3 è True */


printf (“%d is larger\n”, x);

if ( x + x > y * 6 ) /* 20+20 > 3*6 è (20+20)>(3*6) è True


*/
printf(“Double of %d is larger than 6 times %d”,x,y);

if ( x > a ) /* Type cast??? */


printf(“%d is larger than %f”,x, a);
else
printf(“%d is smaller than %f”,x, a);
Logical Operators
• Unary and Binary Operators
! è Logical NOT, logical nega1on (True if the operand is False.)
&& è Logical AND (True if both the operands are True.)
|| è Logical OR (True if either one of the operands is True.)
int x = 20; int y=3;float
a=20.3;
X !X
FALSE TRUE if((x>y) && (x>a)) /* FALSE */
TRUE FALSE printf(“X is largest.”);

if((x>y) || (x>a)) /* TRUE */


X Y X && Y X || Y printf(“X is not smallest.”);
FALSE FALSE FALSE FALSE
if(!(x==y)) /* TRUE */
FALSE TRUE FALSE TRUE printf(“X is not same as Y.”);

TRUE FALSE FALSE TRUE if(x!=y) /* TRUE */


printf(“X is not same as Y.”);
TRUE TRUE TRUE TRUE
Bitwise operators
Operator Meaning Example
a = 237 1 1 1 0 1 1 0 1
& AND b = 174 1 0 1 0 1 1 1 0
a & b is 172 1 0 1 0 1 1 0 0
a = 237 1 1 1 0 1 1 0 1
| OR b = 174 1 0 1 0 1 1 1 0
a | b is 239 1 1 1 0 1 1 1 1
a = 237 1 1 1 0 1 1 0 1
^ EXOR b = 174 1 0 1 0 1 1 1 0
a ^ b is 67 0 1 0 0 0 0 1 1
a = 237 1 1 1 0 1 1 0 1
~ Complement
~a is 18 0 0 0 1 0 0 1 0
a = 237 1 1 1 0 1 1 0 1
>> Right-shift
a >> 2 is 59 0 1 1 1 0 1 1 0
b = 174 1 0 1 0 1 1 1 0
<< Left-shift
b << 1 is 92 0 1 0 1 1 1 0 0
operations in an arithmetic statement are performed is called the

Operator Precedence
hierarchy of operations. The hierarchy of commonly used operators is
shown in Figure 2.3.

Operator Precedence
• In decreasing order of priority
Priority Operators Description
1. Parentheses :: ( )

st 2.
In decreasing
Unary minus :: –5 order of priority
1 1. * / %
Parentheses :: ( ) Multiplication, Division, Modular division
nd 3. Mul7plica7on, Division, and Modulus
2 + - minus :: –5Addition, Subtraction
2. Unary
rd 4. Addi7on and Subtrac7on
3 3. Mul7plica7on,
= Division, and Modulus
Assignment
4. Addi7on and Subtrac7on
• For
Figure 2.3 operators of the same priority,
• For operators of the same
evalua7on is from leY to right as they priority,
Now a few evalua7on is from
tips about usage leY to right
of operators as they
in general.
appear.appear.
(a) Within parentheses the same hierarchy as mentioned in Figure 2.3
is operative. Also, if there are more than one set of parentheses,
• Parenthesis
the Parenthesis
• operations may may
within bebeused
the used to change
to change
innermost the would be
the
parentheses
precedence of operator
precedence of operator evalua7on.
performed first, followed by the evalua7on.
operations within the second
innermost pair and so on.
inside it.

Operator Precedence
A few examples would clarify the issue further.
Example 2.1: Determine the hierarchy of operations and evaluate the
Example: Determine the hierarchy of operations and evaluate the following
• In decreasing order of priority
followingassuming
expression, expression,
that iassuming that
is an integer i is an integer variable:
variable:

i = 21.* 3 Parentheses
/ 4 + 4 / 4 + 8:: - (2) + 5 / 8
2. Unary minus :: –5
3. Mul7plica7on,
Stepwise evaluation of Division, and Modulus
this expression is shown below:
4. Addi7on and Subtrac7on
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
• i For
= 1 + 4operators
/ 4 + 8 - 2 + 5 / of 8 the same priority,
operation: /
i evalua7on
= 1 + 1+ 8 - 2 + 5 /is8 from leY tooperation: right as
/ they
i=1+1+8-2+0 operation: /
i appear.
=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
• i Parenthesis
=8 may be usedoperation: to change
+ the
precedence of operator evalua7on.
Consider the expression a = 3 / 2 * 5 ;
Operator Precedence
Here there is a tie between operators of same priority, that is between /
and *. This tie is settled using the associativity of / and *. Both enjoy Left
In decreasing
•to Right orderfirstly
associativity. Therefore of priority
/ operation is done followed by *.
1. one
Consider Parentheses :: ( )
more expression.
2. Unary minus :: –5
a = b = 3.
3 ; Mul7plica7on, Division, and Modulus
4. Addi7on and Subtrac7on
Here both assignment operators have the same priority. So order of
operations is decided using associativity of = operator. = associates from
•RightFor operators of the same priority,
to Left. Therefore, second = is performed earlier than first =.
evalua7on is from leY to right as they
Consider yet another expression.
appear.
z=a*b+c/d;

•HereParenthesis maypriority
* and / enjoys same be used to change
and same associativitythe
(Left to Right).
Compiler is free to perform * or / operation as per its convenience, since
precedence of operator evalua7on.
no matter which is performed earlier, the result would be same.
Operator Precedence
• In decreasing order of priority
1. Parentheses :: ( )
2. Unary minus :: –5
3. Mul7plica7on, Division, and Modulus
4. Addi7on and Subtrac7on

• For operators of the same priority,


evalua7on is from leY to right as they
appear.

• Parenthesis may be used to change the


precedence of operator evalua7on.
Examples: ArithmeJc expressions

v = u + f * t; è

X = x * y / z è

A = a + b – c * d / e è

A = -b * c + d % e è
Examples: ArithmeJc expressions

v = u + f * t; è v = u+(f*t);

X = x * y / z è X = (x*y)/z

A = a + b – c * d / e è A = ((a+b)-((c*d)/e))

A = -b * c + d % e è A = (((-b)*c)+(d%e))
ArithmeJc – integer /real

• An expression contains only integer operands


è Integer arithme7c will be performed.

• An expression contains only real operands è


Real arithme7c will be performed.

• An expression contains integer and real both


the operands è Real arithme7c will be
performed.
Type casJng
• A faulty reciprocal finder

#include <stdio.h>
The division 1/n is of integers (quo7ent).
int main () The format %d is for prin7ng integers.
{
int n;
scanf("%d",&n);
printf("%d\n",1/n);
return 0;
}
Type casting
Type casJng
#include <stdio.h> #include <stdio.h>
int main () int main ()
{ {
int n; int n;
scanf("%d",&n); float x;
printf("%f\n",1.0/n); scanf("%d",&n);
return 0; x=(float)1/n;
} printf("%f\n",x);
return 0;
}
Type casJng

Integer to real Real to real


int a=10; float b;
float b; double c=3.14;
b=(float)a; b=(float)c;

Real to integer Real to real


int a; float b;
float b=3.14; double c;
a=(int)b; c=22.0/7.0;
b=(float)c;
Mixed Mode Arithmetics

If operands in an expression contains both INTEGER and REAL constants or


variables, this is a mixed mode arithmetic expression.

In mixed mode arithmetic expressions, INTEGER operands are always converted


to REAL before carrying out any computations. As a result, the result of a mixed
mode expression is of REAL type. The following is a table showing this fact.

Operator INTEGER REAL

INTEGER INTEGER REAL

REAL REAL REAL


Mixed Mode Arithmetics
• Locate an operator for evaluation and do the following:
◦ if the operands of this operator are of the same type, compute the
result of this operator.
◦ otherwise, one of the operand is an integer while the other is a
real number. In this case, convert the integer to a real (i.e.,
adding .0 at the end of the integer operand) and compute the
result. Note that since both operands are real numbers, the result is
a real number.

Simple Examples:
• 1 + 2.5 is 3.5
• 1/2.0 is 0.5
• 2.0/8 is 0.25
Control Statements

Control Statements

Branching Looping

Statement takes more than one Some set of statements are


branches based upon a being executed iteraJvely un1l
condiJon test comprising of a condiJon test comprising of
rela1onal and/or logical (may be rela1onal and/or logical (may
arithme1c) operators. be arithme1c) operators are
not being sa1sfied.
CondiJons
• Using rela1onal operators.
– Four rela1on operators: <, <=, >, >=
– Two equality opera1ons: ==, !=

• Using logical operators / connec1ves.


– Two logical connec1ves: &&, | |
– Unary nega1on operator: !
CondiJon Tests
if(count <= 100) /* Relational */
if((math+phys+chem)/3 >= 60) /* Arithmetic, Relational */
if((sex==‘M’) && (age>=21)) /* Relational, Logical */
if((marks>=80) && (marks<90) ) /* Relational, Logical */
if((balance>5000) | | (no_of_trans>25)) /* Relational,
Logical */
if(! (grade==‘A’)) /* Relational, Logical */

CondiJon EvaluaJon

True False
(Non-zero, preferably 1) (Zero)
Operator confusion
Equality (==) and Assignment (=) Operators

• What is expected in condi1on?


– Nonzero values are true, zero values are false
– Any expression that produces a value can be used in control structures

int age=20;
if ( age > 18 ) /* Logical Operator; Evaluated as TRUE */
printf( "You are not a minor!\n" );

if ( age >= 18 ) /* Logical Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );

if ( age == 20 ) /* Logical Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );

if ( age = 18 ) /* Arithmetic Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );

if ( age = 17 ) /* Arithmetic Operator; Evaluated as TRUE */


printf( "You are a minor!\n" );
Operator confusion
Equality (==) and Assignment (=) Operators
Be@er is avoid.
int age=20;
if ( age > 18 ) /* Logical Operator; Evaluated as TRUE */
printf( "You are not a minor!\n" );

if ( age >= 18 ) /* Logical Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );

if ( age == 20 ) /* Logical Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );

if ( age = 18 ) /* Arithmetic Operator; Evaluated as TRUE */


printf( "You are not a minor!\n" );
Value of age will be 18
if ( age = 17 ) /* Arithmetic Operator; Evaluated as TRUE */
printf( "You are a minor!\n" );

Value of age will be 17


There will be no
These statements are not syntax error.
logically correct!!!
Operator confusion
Equality (==) and Assignment (=) Operators

#include <stdio.h>
int main()
{
int x,y;
scanf(“%d”,&x);
y=x%2; /* y will be 1 or zero based on value entered
and stored as x */
if(y=1) { /* y will be assigned with 1, condition will be
evaluated as TRUE */
printf(“Entered number is odd.”);
} else {
printf(“Entered number is even.”);
}

return 0;
}
Unary Operator
• Increment (++) Opera1on means i = i + 1;
– Prefix opera1on (++i) or Pos`ix opera1on (i++)
• Decrement (--) Opera1on means i = i - 1;
– Prefix opera1on (--i) or Pos`ix opera1on (i--)
• Precedence
– Prefix opera1on : First increment / decrement and then used in
evalua1on
– Pos`ix opera1on : Increment / decrement opera1on aaer being used
in evalua1on
• Example

int t, m=1; int t,m=1;


t=++m; t=m++;
m=2 m=2
t=2 t=1
Shortcuts in Assignment Statements
• A+=C à A=A+C
• A-=B à A=A-B
• A*=D à A=A*D
• A/=E à A=A/E
Labels
• A label in ‘C’ programming language is a sequence of characters
that identi es a location/statement within source code.

• In ‘C’ programming language labels consist of an identi er and


followed by a punctuation character (e.g., a colon).

• A single statement can have multiple labels.


fi
fi
Goto Label

The jumping label can be anywhere in the code. Either before goto
statement or after the goto statement. It does not matter where the
label exists.

This kind of jump is unconditional. Usually we use goto statement to


handle errors. But this will reduce the readability of the code and
create confusion to the one looking at the code. Hence it always
advisable to reduce the use of goto statements in the code.
Goto Label
Switch Labels
• Two types of labels can be put in a switch statement.

• A case label consists of the keyword case, followed by an


expression that evaluates to integer constant.

• A default label consists of the keyword default.

• Case labels are used to associate an integer value with a statement


in the code.

• When a switch statement is reached, program execution continues


with the statement after the case label with value that matches
the value in the parentheses of the switch.
Switch Labels
break
Break statement is used to discontinue the normal execution of the code
without any condition and it will jumps out from the current executing loop.
continue
It is similar to break statement, but it will not jump out of the loop instead
stop executing the set instructions inside loop body for current iteration
and jumps to execute the body of loop for next iterations.
Desirable Programming Style
• Clarity
– The program should be clearly wrisen.
– It should be easy to follow the program logic.

• Meaningful variable names


– Make variable/constant names meaningful to enhance program clarity.
• ‘area’ instead of ‘a’
• ‘radius’ instead of ‘r’

• Program documenta1on
– Insert comments in the program to make it easy to understand.
– Never use too many comments.

• Program indenta1on
– Use proper indenta1on.
– Structure of the program should be immediately visible.
IndentaJon Example :: Good Style
/* A program to check the age based quota in Indian Railway 1cke1ng system */

#include <stdio.h>
#define SENIOR 60 /* Declare the age of Senior Ci1zen */

int main()
{
int age;
scanf(“%d”,&age);
if(age< SENIOR) {
if(age<5) {
prin`(“Kid Quota”);
} else if (age<10) {
prin`(“Child Quota”);
} else {
prin`(“General Quota”);
}
} else {
prin`(“Senior Ci1zen”);
}
return 0;
}
IndentaJon Example :: Bad Style
#include <stdio.h> #include <stdio.h>
#define SENIOR 60 #define SENIOR 60
int main() int main()
{ {
int age; int age;
scanf(“%d”,&age); scanf(“%d”,&age);
if(age< SENIOR) { if(age< SENIOR) {
if(age<5) { if(age<5) { prin`(“Kid Quota”); }
prin`(“Kid Quota”); else if (age<10) { prin`(“Child Quota”);
} else if (age<10) { } else { prin`(“General Quota”); }
prin`(“Child Quota”); } else { prin`(“Senior Ci1zen”); }
} else { return 0;
prin`(“General Quota”); }
}
} else {
prin`(“Senior Ci1zen”);
}
return 0;
}

You might also like