Bca C Language 1
Bca C Language 1
spread beyond Bell Labs. In the late 70's C began to replace widespread well-
known languages of that time like PL/I, ALGOL, etc'
because its predecessor was called B. The B language was developed by Ken
Thompson of Bell Labs.
are efficient, fast and highly portable, i.e., C programs written on one
computer can be riin op another with little or no modification. C functions are
the building blocks in which all programming activities are incorporated.
1.1.2. Properties of C
fo. structured
programming.
Weak Typing like for instance, characters can be used as integers.
l-ow-level access to computer memory via machine addresses and typed pointers.
Function pointers allow for a basic form of run-time polymorphism.
A standardized C prep(rcessor for macro definition, source code files
inclusion, conditional compilation, etc.
e.g., {...}.
meaningless operations.
1..L.3. Advantages of C
l) Flexibility: To give access to any level of the computer down to raw machine
language, however, C was designed and because of this, it is perhaps the most
fl exible high-level language.
In this example <stdio.h> file is included, i.e., all the definitions and
prototypes of function defined in this file are available in the current
program. This file is also compiled with original program.
2) Global Declaration: This section declares some variables that are used in
more than one function. These variables are known as global variables. These
variables must be declared outside of all tho functions.
4) Declaration Part: The declaration part declares the entire variables that are
used in executable part. The initializations of variables are also done in this
section. The initialization means providing initial value to the variables.
s) Executable Part: This part contains the moments following the declaration
of the variables. This part contains a set of statements or a single statement.
These statements are enclosed between the braces.*.*1,::
6) user-Defined Function: The functions defined by the user are called user-defined
functions. These functions are generally defined after the main0 function. They
can also be defined before main0 function. This portion is not compulsory.
7) Comments: Comments are not necessary in the program. However, to understand
the flow of programs, the programmer can include comments in the program.
comments are to be inserted by the progarrmer. It is useful for documentation.
The clarity of the program can be followed if it is properly documented.
Comments are nothing but some kind of statements which are placed between
the delimiters /* and */. The compiler does not execute comments..Thus, we
can say that comments are not the part of executable programs.
The user can frequently use any number of comments that can be placed
anywhere in the program.
Note: comments and statements can be nested. The user should select the oprloN
MENU of the editor and selecr the (COMPILER-SOURCE - NESTED
COMMENTS ON/OFF). The comments can be inserted with a single starement or in
nested statements.
Program Code
-*T-l
Source Program
Syntax Errors?
Logic Error
Logic and Data
Errors?
No Errors
C
Compiler To compile F2.C, click Debug and then
Run
F2.exe
Figure 1.3
Figure 1.4
Step 2) Select Run from the menu, as shown in figure 1'5'
Theprogramiscompiledandimmediatelybeginstoexecute'Anew
program
windowlshowing the lnput/output dialog, appears containing_the
listing. This is ,ho*, in ngure 1.5 for the values numl as 50 and
num2
as 2i. These values have been entered by the user, in response
to the
input promPts.
Figure 1.5
Step 3) once the input has been entered the program resumes execution as shown
in the figure 1.6:
Figure 1.6
'
Step 4) As the last input has been entered the' program resumes execution,
see that a value
resulting in the finpl output shown iir'figure 1'7' Thus' we
of sum is 75 is bbtained for the given input quantities:
Figure 1.7
declared as, say, integer or floating point. c is not, howevei, strongry typed,
in that the values in variables can change type atthe will of the prograflrmer.
parampdtfrs- to functions and when dealings with arrays, strings, and dynamii
memfr allocation.
The keywords are also identifiers but cannot be user defined since they are
reserved words.
Basically c has six types of tokens as shown below. All the c programs are
written using these tokens and syntax of the language'
Types of C Token
1.2.4. Identifiers
An identifier is a sequence of characiers that represents an entity such as a
Syntax
identifier nondigit
identifier digit
identifier dollar-sign
Where,
1) nondigit: any character from the set:
-abcdefghijklmnoP
qrstuvwxYzABCDEFG
HIJKLMNOPQRSTUVWX
YZ
2) digit: any character from the set:
0123456789
3) dollar-sign: $ character
For example, Thakur-publisher.
l-.2.5. Variables
variable is a named location in memory, i.e., used to hold a value that can be
modified by the progftlm. These variables can take different values but one at a
time. The values of variables can be changed during execution. All the variables
should be declared before they can be used.
Declaration of Variqble
It is must to declare the variable before it is used in the program. We declare the
variable with data type;.means the variable name can store ihe value of this data
type. c compiler distinguiihes all these variable names, which are declared.
Types of Variable
variables they are
it ,yp"r of variables are defined by the location of the its
"
declared. The place of declaration of the var-iable affects storage and its
of and which has to be
memory storage. Hence declaration is prime concerns
started Lven before the actual coding is started:
are called
1) Local variables: variables that are declared lside a lrnctioq thit are inside
local variables. Local variables can be uied oniy by statements
local variables
the block in which the variables are declared. In other words,
is upon
are not known outside their own code block. A local variable
created
within one
entry into its block and destroyed upon exit. A variable declared
code block has no bearing on or relationship to another variable
with the
same name declared within a different code block'
program and
z) Global variables: variables that are .known throughout the
Also, they will hold their value throughout
may be used by any piece of code.
the program," Global variables are created uv g*gle}l.g_!u:!1-
"*""irtior.
ou1.':$g.'"qf gay*fuap.tronl'Any expression may access
them, regardless of what
tioCii # it is in. Storage for global variables is in a fixed
. "oa" " "*pr"ssion
region of memory sei aside for this purpose by the compiler. Global variables
same data. Use of
aII t"tpfut when many functions in the program use the,
u,n""",,ury global variables, however, because they take-up memory thea
are needed. If
entire time the progruln is executing, not just when they
to that
global variable uoa i to"ut variable have the same name, all references
is declared
variable name inside the code bl0ck in which the l0cal variable
will refer to that local variable and have no effect on the global variable.
- --
Numeric Character
Constants Constants
ii) Real (Floating Point) constant Floating point constanrs are rhe
numbers, which hold the decimal point. Some valid floating point
constants are:
0.5
5.3
4000.0
0.0073
Every character constant has a unique integer value associated with it. These
are-r{S-Cl (American standard code for Information I,lte-rchange) value for
each character of the character set. For exCmpte:
A-Z ASCII value (65-90)
a-z ASCII value (97-t2Z)
0-9 ASCII value (48-57)
ASCII value (59)
Types of Character Constant
i) String Constant: A string constant has a zero, one or more than one
character. A string constant is enclosed within double quotes (""). Atthe
end of string \0 is automatically placed. For example:
Forrnally, data type is definbd as a finite set Qi values alongwith well-defined set
of rules for operations that cah be performed bn these values'
C supports different types oi data. Storage representations of these data types are
also different in memory.
To control the range of numbers and storage space, c has three classes of
integer storage namely short int, int and long int. All three data types have
signed and unsigned forms. A short int requires half the amount of storage
than normal integer. unlike signed integer, unsigned integers are always
positive and use all the bits for the magnitude of the number. Therefore the
range of an unsigned integer will be from 0 to 65535. The long integers are
used to declare a longer range of values and it occupies 4 bytes of storage
space.
2) Type: char
Size: I byte.
Description: A (positive or negative) integer. Usually represents a character
according to a character code (e.g., ASCII). Character type variable can hold
a single character. As there are signed and unsigned int (either short or long),
in the same way there are signed and unsigned chars; both occupy I byte
each, but having different ranges. Unsigned characters have values between
0
and255, signed characters have values from -128 to 127 '
Syntax: char <variable name>;
ForExamPle: a, b, g, S, j.
Examples of char Variable Declaration
char cFirst;
char csecond, cThird;
char ch = 'a';
3) Type: float
Size: System dependent; Often 4 bytes.
#includecstdio.h>
/* main function */
int mainQ
{
/* declare and initialized variables */
int p = 2000; /* positive integer datatype
*l
short int q'-120; /* variation */
unsigned short int r= l2l; /* variation */
float s = 21.566578; /* float data type */
char t= 'r'; /* chat datatype *l
long u = 5678; /* long positive integer data type */
unsigned long v = 5678; /x variation */
long w = -5678; l* -.ve long integer datatype */
int x = -l7I; l* -ve integer data type x/
short Y = 17; le Short -ve integer data type */
unsigned short z = 99', /* variation x/
double a = 88.12345; /* double float data type*/
float b = -3.245823; /* float dataYpe *l
char Title[50] = "The Making of the Casino Royale";
pnntf( "\t--Data type again--\n" ) ;
printf("\t-------------------\n" ) ;
printf("\nl. \"int\" sample: \t\t 7od, the data size: Vodbytes", p, sizeof(p));
printf("\n2. \"short\" int sample: \t Vod, the data size: Vod bytes',, q,
sizeof(q));
printf("\n3. \"unsigned short int\" sample: Vod, the data size: Vod bytes,,, t,
sizeof(r)):
printf("\n4. \"float\" sample: \t\t7o.7f, the data size: Vodbytes", s, sizeof(s));
printf("\nS. \"char\" sample: \t\t%oc, the data size: Vodbyte", t, sizeof(t));
printf("\n6. \"long\" sample: \t\t 7od, the data size: Vodbytes", u, sizeof(u));
printf("\n7. \"unsigned long\" sample: \t vod, the data size: Tod bytes", v,
sizeof(v)):
printf("\nS. negative \"long\" sample: \t Vod, the data size: Tod bytes", w,
sizeof(w));
printf("\n9. negative \"int\" sample: \t vod, the data size: vod bytes", x,
sizeof(x));
printf("\r110. negative \"short\" sample: \t vod, the data size: vorl-bytes", y,
sizeof(y)):
printf("\nl1. unsigned \"short\" sample: \t vad, the data size: vod bytes", z,
sizeof(z));
printf("\n12. \"rlodbJe\" sample: \t\t To.4f, the data size: Vod bytes,,, a,
printf("\n13. negative \"float\" sample: \t Vo.Sf, the data size: ?od bytes", b,
sizeof(bl):
printf("\n14. The NULL terminated string data size: vod bytes\n",
sizeof(Title));
return 0;
Output
Comments are also statements which are used for understanding the program'
The comments are used for documentation. Comments are given by starting with
/* and ending with */. It can be of one or many number of lines'
For Example
1) Single Line Comment: /* THIS IS C PROGRAM *l
2) Multiple Line Comment
l*
F3;
b=a*cl
c=alb:'
*l
These include:
+ addition
subtraction
* multiplication
division
Vo modulus (remainder)
Each of these operators can work with ints, floats or chars values.
int main0
t,
l.
inta=3,b=4;
clrscr0;
printf("Initially: a = 3, b = 4\n");
printf("\na 4= S a = a + b = 7od\n", a+=b);
-; =
printf("a last value %od\n",a);
printf("\na *- b a = a * b = 7od\n", a*=b);
->= Vod\n",a);
printf("a last value
printf("\na -= | a = a -b = 7od\n", a-=b);
printf("a last value = 7od\n",a);
pt'intf("\na./=b a= a lb = 7od\n" , a/=b);
-> = %od\n", a);
printf("a last value
l) = %od\n", a:(b+l));
printf("a last value = Vod\n", a);
getch0;
return (0);
L.3.3. RelationalOPerators
The operands for relational operators are variables, constants or expressrons.
Characters are also represented internally as integers (by their ASCII codes),
elements to be compared can be characters as well. Relational operators
in C
include:
eoual to
t- not equal to
sreater than
less than
less than or equal to
sreater than or equal to
For Example
num==a
"';
ch!='C' -,
sum<=(x+y) I
These operators are used for cbmparing quantities. = = and != have the same
precedence which is lower than the (identical) precedence of the others'
bperators of equal precedence associate from left to right'
Output
Now when there is a need to trigger a code with the truth of any of the two
expressions in question then we have ll operator.
(expression 1) ll (exPression2)
The following table shows the result of combined expression of both logical
operators viz. && andll:
Combined of && and
Operands Results
Expression I Exnression 2 && il
0 0 0 0
0 Non-zero 0 Non-zero
Non-zero 0 0 Non-zero
Non-zero Non-zero Non-zero Non-zero
These operators follow a precedence like '!' has higher precedence than &&
which has higher precedence than ll. The operators && and ll associate from left
to right, and the evaluation of the expression stops as soon as its truth-value is
determined. Parentheses can be used to force a particular order of evaluation.
Output
L.3.5. AssignmentOperators
Assignment operator takes the form as,
variable = expression
The operator '=' associates from right to left, so the above is equivalent to
a=(b=(c=13))
These operators can be used either before or after their operand, i.e., in either
'prefix' or 'postfix' position, so we can have a++ (postfix) as well as ++d
(prefix).
Prefix and postfix operators have same effect if they are used in an isolated C
statement. For example, the effect of the following two statements would be
same:
a++;
++a;
b= **al
will first increase the value of 'a' to 6 and then assign that new value to 'b'. The
effect is exactly same as if the following two statements have been executed:
a=a+ l;
b=ai
On the other hand, execution of the statement
b = a**l
set the value of 'b' to 5 and then increase the value of 'a' to 6. The effect
will first
now is same as if the following two statements had been executed:
b=ai
a=a+ 1;
Output
Explanation: In the above Program the equation z = xt.y++ gives the result 200
because 'y' does not gets,increased' After multiplication 'y' increases to 11. The
second equation gives result 210.
#include<stdio.h>
#include<conio.h>
void main0
{
int a, b;
clrscr0;
a=10;
b=15;
printf("Greater no is VodV, (a > b) ? a:b);
getch0;
return (0);
)
Output
TabIe: Bitwise
Operator Meaning
& bitwise AND
bitwise OR
bitwise exclusive OR
shift left
shift rieht
l) Bitwise AND: This operator gives the net result one if bits of both the
operand have the valu'e one, otherwise zero.
Boolean Table: Bitwise AND
Bit I Bit2 Result
0 0 0
0 I 0
I 0 0
I I
For Example
x=5 00000101
Y=9 00001001
x&y 00000001
-1
2) Bitwise OR: This operator gives the net result 0 if both the operands have the
value 0 otherwise 1.
Boolean Table: Bitwise OR
Bit 1 Bir2 Result
0 0 0
0 I 1
I 0 I
1 I
For ExamPle
x=5 00000101
Y=9 00001001
x Iy 00001101
=13
3) Bitwise XOR: This operator gives the net result 1 if both the operands have
different values
"tT:;:rabre:
Bitwise XoR
Bit 1 Bit2 Result
0 0 0
0 I I
1 0 I
I I 0
For Example
x=5 00000101 d
Y=9 00001001 ft
x ^ y 00001101
=13 '
4) Bitwise Left Shifti This operator'is used for shifting the bits left' This
operator has two operands. Left shift indicates which bits are to be shifted.
For ExamPle
x=13 00001101
x<<6 01000000
-128
Y=9 00001001
y<<3 01001000
=136
5) Bitwise Right Shift: This operator is used for shifting the bits right. This
operator has two operands. Left shift indicates which bits are to be shifted.
Right operand indicates the number of bits to be shifted.
For Example
x=213 11010101
x>>4 00001101
-6
y=148 10010100
y>>6 00000010
_,,
Outnut
{--
s c:,,usemhn,",",*'n',.g."=ii*ftf.l-; l*-** t{ ---
1.3.9. Special OPerators
Comma bperator: The comma operator can be used to link the
related
1)
cxpressit-rns together. A comma-linked List of expressions
are evaluated left
to right and the value of right-most expression is the value of the
combined
expression. For example, the statement
value = (x = 10, y = 5, x+Y);
15 (i'e"
first assigns the value 10 to x, then assigns 5 to y, and finally assigns
precedence of all
10 + 5)L value. Since comma operator has the lowest
operators, the parentheses are necessary'
when used with
2)
' sizeof operator: The sizeof is a compile time operator and,
occupies. The operand
u, op".uird, it returns the number of bytes the operand
may be a variable' a constant or a data type qualifier'
For ExamPle
m = sizeof(sum);
n = sizeof(longint);
k = sizeof(235l);
The sizeof operator is normally used to determine the lengths of
arrays and
structures when their sizes are not known to the programmer. It is also used
to allocate memory space dynamically to variables during execution of a
program
Programl0:/*Programtoillustratetheusesizeofoperator*/
#include<stdio.h>
#include<conio.h>
main0
t
int x;
unsigned int i;
i=sizeof(x);
printf("The value of i is 7ou\n", i);
getchQ;
return (0);
)
optp;{- ,,,:.
ii i.:. ,.
, a: .,r".,.i,'.ire:.-
iUser:1.3rr'.'e:_' Desktnplt&he{.. ' t
evaluates the expression by starting on the left and ,roui"rrg to the rijlit
whereas the right-to-left associativity evaluates the expressionly starting
on
the right and moving ro the left.
Types of Expressions
nu.n typ" of^expression takes certain types of operands and uses a specific set of
op"rutoi.. Evaluation of every expression produces a value of specific type.
Eipressions are not statements, but may be components of statements'
For
x%o2=O Used to test whether the operand r is an even
number or not. The relational expression results in
value 1 ifx is even otherwise results in value 0'
3) Logical Expressions: A logical expression also produces a zero or non-zero
value. A logical expression is used to form a complex test condition in order
to take a decision.
For example,
(x>2)&&(xVo2=O) Used to form a test condition to check
whether the operand x is greater than 2 and x
is even (divisible by 2).T}.te resulr of this test
condition will be I only if both the
conditions hold true simultaneous