0% found this document useful (0 votes)
14 views20 pages

C Fundamentals (Chapter 4)

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

C Fundamentals (Chapter 4)

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

Chapter 2 Page 1 siddhanath science campus

Chapter 4
C-Fundamentals
Introduction
C Language was originally developed at Bell Labs by Ken Thompson and Dennis Ritchie in the
mid of 1970’s. It is one of the most popular procedural, general purpose, and high-level
programming language used in all operating systems of today. Although C was designed for
writing system software, it is also widely used for developing application software. C is one of
the most popular programming languages of all time and there are very few computer
architectures for which a C compiler does not exist.
C has greatly influenced many other popular programming languages, most notably C++,
which began as an extension to C. It supports the programmer with a rich set of built-in functions
and operators. C supports different types of statements like sequential, selection, looping etc.
Procedural programming concept is well supported in C, this helps in dividing the programs into
function modules or code blocks.

Basic Structure
A C-program has the following basic structure:
Documentation Section
link Section
definition Section
global declaration Section
main()
{
}
Sub-program Section
function1()
{
}
function2()
{
}
…….

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 2 siddhanath science campus

The documentation section consists of a set of comment lines giving the name of the program,
the author and other details such as a short description of the purpose of the program etc. The
link section provides instructions to the compiler to link functions from the system library. The
definition section defines all the symbolic constants.
The variables can be declared inside the main function or before the main function. Declaring
the variables before the main function makes the variables accessible to all the functions in a C
language program, such variables are called Global Variables. Declaring the variables within
main function or other functions makes the usage of the variables confined to the function only
and not accessible outside. These variables are called Local Variables.
Every C program must have one main function. It contains different executable statements
between the opening and closing braces. The sub-program section contains all the user-defined
functions that are called in other and main function. User-defined functions are generally placed
immediately after the main function although they may appear in any order.
Example:
/*
Program is written by Ramesh Bhattal
Date: 2070/09/24
Program to find area and circumference of a circle
*/
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
float r,a,c;
float area();
float circumference();
void main()
{
clrscr();
printf("Radius=");
scanf("%f",&r);
a=area();

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 3 siddhanath science campus

c=circumference();
printf("Area=%f",a);
printf("\nCircumference=%f",c);
getch();
}
float area()
{
return PI*r*r;
}
float circumference()
{
return 2*PI*r;
}

Some Simple C Programs


1. Program to display the message “Hello World”
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Hello World");
getch();
}

2. Program to add two whole numbers


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c;

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 4 siddhanath science campus

printf("a=");
scanf("%d",&a);
printf("b=");
scanf("%d",&b);
c=a+b;
printf("Sum=%d",c);
getch();
}

The C Character Set


C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain
special characters as building blocks to form basic program elements. The special characters are
given below.

Identifiers
Identifiers are the names given to various program elements such as variables, functions, arrays,
and other user defined items. Identifiers can be a combination of letters, digits and underscore, in
any order, except that the first character must not be a digit.
In an identifier, upper- and lowercase are treated differently. For example, the identifier
count is not equivalent to Count or COUNT. There is no restriction on the length of an
identifier. However, only the first 31 characters are generally significant. For example, if your C
compiler recognizes only the first 3 characters, the identifiers pay and payment are same. Some
valid and invalid identifiers are given below.

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 5 siddhanath science campus

Keywords
There are certain reserved words, called keywords that have standard, predefined meanings in C.
these keywords can be used only for their intended purpose; they cannot be used as programmer-
defined identifiers. The ANSI (American National Standards Institute) C defines the following
32 keywords.

Data Types
C supports different types of data, each of which may be represented differently within the
computer’s memory. A data type defines the amount of memory that will be used during
program execution, valid range of values it can represent, and the operations that may be
performed on it. C is strongly typed language so every variable in C must be declared of specific
type explicitly. Data types can be either predefined or derived.
The C language supports four basic data types, each of which are represented differently
within the computer memory. The basic types for a particular compiler are listed below:

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 6 siddhanath science campus

The basic types can be augmented by the use of data type qualifiers short, long, signed, and
unsigned. The int type can be qualified by signed, short, long and unsigned. The char type
can be modified by unsigned and signed. You can also apply long to double.

Note: Memory requirements for each data type may vary from one C compiler to another.

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 7 siddhanath science campus

Data Type Conversion


As given below, c supports two types of data type conversion: implicit conversion and type
casting:

1. Implicit Type Conversion


C permits mixing of constants and variables of different types in an expression and automatically
converts any intermediate values to the proper type so that the expression can be evaluated
without losing any significance. This automatic type conversion is also known as automatic
promotion. If the operands are of different types the lower type is automatically converted to the
higher type before the operation proceeds and the result is of higher type. The hierarchy of data
types for automatic conversion is:

long double (highest type)


double
float
unsigned long int
long int
unsigned int
int (lowest type)
All short and char are automatically converted to int
2. Type Casting
Type casting represents a request by the programmer to do an explicit type conversion that is,
converting form higher type to lower type (narrowing conversion). Casting tells the compiler to
convert the data to the specified type even though it might lose data. In C programming, casts are
done via the () operator, with the name of the type to cast to inside. For example,
double val1 = 456.9876;
float val2 = (float)val1;
Note: Casting must be carefully done since it may result in loss of data

Variables
A variable is an identifier that is used to represent some specified type of information in a
program. It is a named location in memory. It is used to hold a value that can be modified by a
program. It has a type associated with it. Specifying a variable requires two things:
 You must give it a name and

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 8 siddhanath science campus

 You must identify what kind of data you propose


When you declare a variable, you instruct the compiler to set aside memory space for the
variable. All variables must be declared before you can use them.

Variable Initialization
When a variable is declared, its initial value is undefined. Before using a variable, you should
always initialize it to a known value. To initialize a variable, the declaration must consist of a
data type, followed by a variable name, and equal sign (=) and a literal constant of the
appropriate type. For example,
char ch = ‘a’;
int first = 0;
float balance = 123.23;

Constants
Like a variable, a constant is a data storage location used by your program. Unlike a variable,
the value stored in a constant can’t be changed during program execution. C has two types of
constants: literal constants (numeric, character, and string constants) and symbolic constants.
A literal constant is a value that is typed directly into the source code wherever it is needed.
Literal constants are also only referred as constants.

Literal Constants
1. Numeric Constants
Integer and floating point constants represent numbers. They are often referred to collectively as
numeric-type constants. Integer constants are written without decimal point and floating point

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 9 siddhanath science campus

constants are written with a decimal point and/or exponent. The following rules apply to all
numeric-type constants:
 Commas and blank spaces cannot be included within the constant.
 The constant can be preceded by a minus (-) sign if desired. The minus sign is an operator
that changes the sign of a positive constant.
 The value of a constant cannot exceed specified minimum and maximum bounds. For each
type of constant, these bounds will vary from one C compiler to another.

2. Character Constants
Character constant is a single character, enclosed in apostrophes. Character constants have
integer values that are determined by the computer’s particular character set. Most computers
make use of the ASCII character set. In ASCII, each individual character is numerically encoded
with its own unique 7-bit combination. For example,
Constant Value
‘A’ 65
‘3’ 51
‘y’ 121
‘?’ 63
‘’ 32

Escape Sequences

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 10 siddhanath science campus

Certain nonprinting characters like newline, as well as backslash (\), apostrophe ('), and certain
other characters can be expressed in terms of escape sequences. Escape sequences begin with a
backward slash and are followed by one or more special characters. An escape sequence is
regarded as a single character and is therefore valid as a character constant. It is also called
backslash character constant. The following are the commonly used escape sequences.
Character Escape Sequence ASCII Value
Bell (alert) \a 007
Backspace \b 008
Horizontal tab \t 009
Vertical tab \v 011
Newline (linefeed) \n 010
Form feed \f 012
Carriage return \r 013
Quotation mark (") \" 034
Apostrophe (') \' 039
Question mark (?) \? 063
Backslash (\) \\ 092
Null \0 000

3. String Constants
String constants consist of any number of consecutive characters (including none), enclosed in
(double) quotation marks. A character constant (e.g., 'A') and the corresponding single-character
string constant ("A") are not equivalent. For example,
“green” “mahendranagar” “science” “rs 50”

Symbolic Constants
Constant that is represented by a name (symbol) in your program is called symbolic constant.
The value represented by this constant cannot be changed during program execution. Whenever
you need the constant’s value in your program, you use its name as you would use a variable
name. Thus, a symbolic constant allows a name to appear in place of a numeric constant, a
character constant or a string constant. When a program is compiled, each occurrence of a
symbolic constant is replaced by its corresponding character sequence. C has two methods for
defining a symbolic constant: the #define directive and the const keyword. For example,

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 11 siddhanath science campus

#define PI 3.14159
...
...
area = PI * (radius)*(radius);
OR
const double PI = 3.14159;
...
...
area = PI * (radius)*(radius);

Writing Comments
Comments are sentences that are not treated as a part of the program. These are helpful in
identifying the program’s principal features or in explaining the underlying logic of various
program features. In C there are two ways of putting comments on the program codes.
1. Single line comments
It begins with // and end at the end of the line. For example,
// This program adds two whole numbers
2. Multi line comments
It is enclosed in /*………..*/. For example,
/* This program adds
two whole numbers */

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 12 siddhanath science campus

Operators
An operator is a symbol that is used to perform some action on one, two or three operands.
Operators that perform on one operand are called unary operators, that perform on two
operands are called binary operators, and that perform on three operands are called ternary
operators.
Operators and their corresponding associativity are given in the table below where high
precedence operators appear before low precedence operators and operators within the same
group have same precedence. The associativity indicates the order of execution of operators of
equal precedence in an expression. When an expression contains multiple operators, the
precedence of the operators controls the order in which the individual operators are evaluated.
For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has
higher precedence than the binary + operator. When an expression contains more than one
operand with the same precedence, the associativity of the operators controls the order in which
the operations are performed. Some operators are left-associative and some are right-associative
as shown in the table below. For example, x - y + z is evaluated as (x - y) + z. However, the
expression x = y = z is evaluated as x = (y = z). Precedence and associativity can be controlled
using parentheses. For example, x + y * z first multiplies y by z and then adds the result to x, but
(x + y) * z first adds x and y and then multiplies the result by z.
Operator Description Associativity

() Parentheses (function call and grouping sub expression) left-to-right


[] Brackets (array subscript)
. Member selection via variable
-> Member selection via pointer
++ -- Postfix increment/decrement

++ -- Prefix increment/decrement right-to-left


+ - Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (change type)
* Dereference
& Address
sizeof Determine size in bytes

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 13 siddhanath science campus

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to left-to-right


> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left
+= - = Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right

The ( ) [] . and -> operators


 ( ) operator is used for calling functions. For example, sqrt(n). Similarly, ( ) operator is used
as cast operator for type casting as discussed previously. In this case, it is unary operator.
For example, if we have a variable x of double type and we want to cast it to the int type we
must cast the variable x as (int)x. We can also use ( ) operator to group sub-expressions. For
example, a+(b-c).
 [] operator is used for accessing the array elements at particular position. For example, if we
have array1[5] then we are accessing 6th element of an array called array1.
 . operator is used for accessing members of a structure or union via non pointer. For example,
s.a

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 14 siddhanath science campus

 -> operator is used for accessing members of a structure or union via pointer. For example, s-
>a

The ++ and -- operators


The above two operators are unary operators. The ++ operator is called increment operator and
the -- operator is called decrement operator. The increment operator increases its operand by 1
and the decrement operator decreases its operand by 1. For example, the statement
x = x + 1; can be rewritten as x++; or ++x;
Similarly, the statement x = x – 1; is equivalent to x--; Or --x;
The increment/decrement operators can be applied before (prefix) or after (postfix) the
operand. The code x++; and ++x; will both end in x being incremented by one. The only
difference is that the prefix version (++x) evaluates to the incremented value, whereas the postfix
version (x++) evaluates to the original value.
If you are just performing a simple increment/decrement, it doesn't really matter which
version you choose. But if you use this operator in part of a larger expression, the one that you
choose may make a significant difference. For example,
int a = 1, b = 2, c, d;
c = ++b;
d = a++;
c++;
printf("a = %d" ,a); //a = 2
printf("b = %d" ,b); //b = 3
printf("c = %d" ,c); //c = 4
printf("d = %d" ,d); //d = 1
Note: You can use -- similarly.

The &operator
It is unary operator. This operator gives the address of its operand. For example, &a. This
operator can also be used as bitwise AND operator. In this case, it is binary operator. We will
discuss it later as a bitwise operator.

The sizeof operator

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 15 siddhanath science campus

It is unary operator. It gives the number of bytes reserved for a data type. For example,
printf("%d", sizeof(int));

The arithmetic operators


There are five arithmetic operators in C. These are division (/), multiplication (*), addition (+),
subtraction (-), and modulus (%).
 The division operator (/) is used for division. For example, 7.5/5=1.5, 7/5=1.
 The multiplication operator (*) is used for multiplication like 7*5=35. This operator is
also used to dereference the memory location that the pointer points to. In this case, it is
unary operator. For example, *a = 10.
 The addition operator (+) is used for addition. It is also used as unary plus. For example,
2+3=5, +5.
 The subtraction operator (-) is used for subtraction. It is also used as unary minus. For
example, 3-2= -1, -5.
 The modulus operator (%) operator is used for obtaining remainder after integer division.
For example, 5%3=2, 6%3= 0, 2%3 = 2.

Relational and Equality operators


These operators are used for comparing the operands. The outcome of using these operators is a
Boolean value: true (1) or false (0). C has various such operators as given below. The first two
are equality operators and the other operators are relational operators.
 Equal to operator (==) is used to verify whether two operands are equal.
 Not equal to operator (!=) is used to verify whether two operands are not equal.
 Greater than operator (>) is used to verify whether the first operand is greater than the
second operand or not.
 Greater than or equal to operator (>=) is used to verify whether the first operand is
greater than or equals to the second operand or not.
 Less than operator (<) is used to verify whether the first operand is less than the second
operand or not.
 Less than or equal to operator (<=) operator is used to verify whether the first operand is
less than or equals to the second operand or not.
For example,
int a = 23;

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 16 siddhanath science campus

int b = 23;
int c = 15;
printf(“%d”, a == b);
printf(“%d”, a != b);
printf(“%d”, a > c);
printf(“%d”, a >= b);
printf(“%d”, a < b);
printf(“%d”, a <= b);

Logical operators
Logical operators operate on one or more Boolean operands and results the value as true or false.
These operators are given below:
 Logical NOT operator (!) is used to negate the Boolean value i.e. if the value of the
Boolean variable is true then its negation will be false and vice versa. This is unary
operator.
 Logical AND operator (&&) outputs the result true if both the operands on which the
operator is operating are true, false otherwise.
 Logical OR operator (||) outputs the result false if both the operands on which the
operator is operating are false, true otherwise.
For example, !a>b, a>b&&a<=c, a<c||b>c etc.
Logical operators can also be described using truth tables. For example,

Truth Table: Logical NOT

Operand !Operand

1(true) 0(false)

0(false) 1(true)

Truth Table: Logical AND

Operand1 Operand2 Operand1&&Operand2

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 17 siddhanath science campus

1(true) 1(true) 1(true)

1(true) 0(false) 0(false)

0(false) 1(true) 0(false)

0(false) 0(false) 0(false)

Truth Table: Logical OR

Operand1 Operand2 Operand1||Operand2

1(true) 1(true) 1(true)

1(true) 0(false) 1(true)

0(false) 1(true) 1(true)

0(false) 0(false) 0(false)

Bitwise operators
The purpose of bitwise operators is to operate on the given integral operand in low level i.e. bit
level to represent the data. These operators are:
 & (bitwise-AND) operator compares each bit of its first operand to the corresponding bit
of its second operand. If both bits are 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
 | (bitwise-inclusive-OR) operator compares each bit of its first operand to the
corresponding bit of its second operand. If either bit is 1, the corresponding result bit is
set to 1. Otherwise, the corresponding result bit is set to 0.
 ^ (bitwise-exclusive-OR) operator compares each bit of its first operand to the
corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the
corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 18 siddhanath science campus

 ~ (bitwise NOT) operator is used to negate the individual bits of the operand. This
is unary operator.
 << (shift left) operator shifts its first operand left by a number of bits given by its second
operand, filling in new 0 bits at the right.
 >> (shift right) operator shifts its first operand right. If the first operand is unsigned, >>
fills in 0 bits from the left, but if the first operand is signed, >> might fill in 1 bits if the
high-order bit was already 1.
In the examples below, we assume 8 bit (short) values.
~2 = ~(00000010) = 11111101 = -3.
~-2 = ~(11111110) = 00000001 = 1.
5&2 = 00000101&00000010 = 00000000 = 0.
-5&-2 = 11111011&11111110 = 11111010 = -6.
5|2 = 0000 0101 | 0000 0010 = 00000111 = 7.
-5|-2 = 11111011|11111110 = 11111111 = -1.
5^2 = 00000101 ^ 0000 0010 = 00000111 = 7.
-5^-2 = 11111011^11111110 = 00000101 = 5.
35>>2 = 0010 0011 >> 2 = 0000 1000 = 8.
-5>>1 = 11111011>>1 = 11111101 = -3.
35<<2 = 00100011 << 2 = 10001100 = 140.
-5<<1 = 1111 1011<<1 = 1111 0110 = -10.

Conditional operator
This operator is ternary operator i.e. it requires three operands. The syntax for this operator is
condition ? statement1:statement2. Here we interpret like: if condition is true then statement 1 is
executed else statement 2 is executed. For example. int min = (x <= y) ? x : y; means if x <= y
then min = x, otherwise min = y. It is similar to if-else statement. We will discuss if-else
statement later.

Assignment operators
There are different assignment operators in C. These operators are given below:
 = operator is used to assign value of an expression to another expression. For example, if
we want to assign value 5 to the variable five, then we do five = 5;

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 19 siddhanath science campus

 Arithmetic assignment operators (+=, -=, *=, /=, %=): +=operator is used to assign
variable a value obtained by adding the previous value of the variable and value of the
other expression. For example a += b; is equivalent to the statement a = a + b; where a
and b are two expressions. Other assignment operators are similarly interpreted.
 We can also use bitwise assignment operators (&=, ^=, |=, <<=, >>=). For example
a&=b; is equivalent to a=a&b; Other operators are similarly interpreted.

Comma operator
The comma operator (,) is used to separate two or more expressions that are included where only
one expression is expected. When the set of expressions has to be evaluated for a value, only the
rightmost expression is considered. For example, the following code: a = (b=3, b+2); would first
assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain
the value 5 while variable b would contain value 3.

Expressions
Expressions are meaningful combinations of constants, variables, operators, and function calls. A
constant, a variable, or a function call by itself can also be considered an expression. Most
expressions have a value. For example, a+b, Sqrt(4), 5*a-pow(m,n), a, 6 etc. Some common
expressions are given below:
 Arithmetic expressions: Arithmetic expressions contain arithmetic operators. For
example, 2 + 8, a*b+c etc.
 Assignment expressions: In assignment expressions, we use assignment operator. For
example, i=7.
 Relational expressions: In relational expressions, we use relational operator. These
expressions yield either the int value 0 or the int value 1. For example, a<7.
 Equality expressions: In equality expressions, we use equality operators. These
expressions yield either the int value 0 or the int value 1. For example, a==7.
 Logical expressions: In logical expressions, we use logical operators. These expressions
yield either the int value 0 or the int value 1. For example, (a==7)&&(b>c).

Statements

Prepared by: Ramesh Prasad Bhatta


Chapter 2 Page 20 siddhanath science campus

A statement is a complete direction instructing the computer to carry out some task A statement
specifies an action. There are three different classes of statements in C: declarative statements,
expression statements, and control statements.
 Declarative statements: Statements declaring the variables. For example, int x = 101;
 Expression statements: An expression statement consists of an expression followed by
a semicolon. The execution of an expression statement causes the expression to be
evaluated. For example, a = 3; c = a+b; ++i; printf("Area = %f", area); etc.
 Control statements: These are used to create special program features, such as branches
and loops (detail later). Many control statements require that other statements be
embedded within them. For example,
int i;
for(i=0;i<=9;i++)
printf(“Hello world”);
We can create compound statements from other statements discussed before. Compound
statement consists of several individual statements enclosed within a pair of braces { }. The
individual statements may themselves be declaration statements, expression statements,
compound statements or control statements. Compound statement provides a capability for
embedding statements within other statements. Unlike an expression statement, a compound
statement does not end with a semicolon. For example,
{
pi = 3.141593;
circumference = 2. *pi * radius;
area = pi * radius * radius;
}

Prepared by: Ramesh Prasad Bhatta

You might also like