0% found this document useful (0 votes)
96 views21 pages

Unit - I To C Programming, Operators & Expressions To C Programming

C is a structured programming language developed in 1973 at Bell Labs. It was influenced by languages like ALGOL, BCPL, and B. A C program structure includes documentation, header files, definitions, global declarations, the main function, subprograms, and tokens like identifiers and keywords. C supports primitive data types like integers, floats, characters, and void. Data types specify how data is entered and stored, with each type having a predefined size and range. Constants are values that don't change during program execution, including integer, floating, character, and string constants.

Uploaded by

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

Unit - I To C Programming, Operators & Expressions To C Programming

C is a structured programming language developed in 1973 at Bell Labs. It was influenced by languages like ALGOL, BCPL, and B. A C program structure includes documentation, header files, definitions, global declarations, the main function, subprograms, and tokens like identifiers and keywords. C supports primitive data types like integers, floats, characters, and void. Data types specify how data is entered and stored, with each type having a predefined size and range. Constants are values that don't change during program execution, including integer, floating, character, and string constants.

Uploaded by

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

UNIT – I

INTRODUCTION TO C PROGRAMMING, OPERATORS &


EXPRESSIONS
INTRODUCTION TO C PROGRAMMING
INTRODUCTION:

 C is a structured programming language developed by Dennis Ritchie in 1973 at Bell


Laboratories.
 C language has developed from three different structured language ALGOL, BCPL and B
Language
 It uses many concepts from these languages and introduced many new concepts such as
data types, struct, pointer.
 In 1988, the language was formalized by American National Standard Institute(ANSI)
 In 1990, a version of C language was approved by the International Standard Organization
(ISO) and that version of C is also referred to as C89.

C Language features:

 Simple
 Portability
 Powerful
 Platform dependent
 Structure oriented
 Case sensitive
 Modularity
 Middle level language
 Efficient use of pointers
The C Character Set:
 A character denotes any alphabet, digit or special symbol used to represent PROGRAM.
EX:
Alphabets: A-Z & a-z.

Digits: 0,1,2,………… 9

Special symbols : ~‘!@#%^&*()_-+=|\{}[]:;"'<>,.?/

White Spaces: \ n, \ t, \ b etc.

Writing First Program of C:

structure of a c program:

Documentation Section:
 The documentation section contains a set of comment including the name of the program
other necessary details.
 Comments are ignored by compiler and are used to provide documentation to people who
read that code.
Comments are be giving in C programming in two different ways

 Single Line Comment // this is single line comment


 Multi Line Comment /* c program for printing
Sum of two numbers */
Link Section/ Header file Section
 The link section consists of header files while contains function prototype of Standard
Library functions which can be used in program.
Ex: #include <stdio.h>
#include<math.h>

Definition Section
 The definition section defines all symbolic constants
 A symbolic constant is a constant value given to a name which can't be changed in program

Ex: #define PI 3.14, #define a 215.

Global Declaration
 In global declaration section, global variables and user defined functions are declared

Main() Function Section


 The main () function section is the most important section of any C program
 The compiler start executing C program from main() function
 The main() function is mandatory in C programming.
It has two parts:

 Declaration Part
 Executable Part
Declaration Part : All the variables that are later used in the executable part are declared in this
part.
Executable Part: This part contains the statements that are to be executed by the compiler.

Subprogram Section:
 The subprogram section contains all the user defined functions that are used to perform a
specific task
 These user defined functions are called in the main() function

C TOKENS

 In C Programming punctuation, individual words, characters etc are called tokens.

 Tokens are basic building blocks of C Programming


The smallest individual unit of a program is called as Token
Identifiers and Keywords:
Identifiers:
In C language identifiers are the names given to variables, constants, functions and user-define
data.
Ex: int amount; double totalbalance
In the above example amount and totalbalance are identifiers
Rules for Naming Identifiers:

 An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits)
and underscore( _ ) symbol.

 Identifier names must be unique

 The first character must be an alphabet or underscore.

 You cannot use a keyword as identifiers.

 Only first thirty-one (31) characters are significant.

 Must not contain white spaces.

 Identifiers are case-sensitive.(i.e sum and Sum are different identifiers)

Keywords:

 Keywords are special words in C programming which have their own predefined meaning

 The functions and meanings of these words cannot be altered

 The keywords cannot be used as variable names because if we do so we are trying to


assign a new meaning to the keyword, which is not allowed by the computer

 The keywords are also called ‘Reserved words’

A list of 32 keywords in c language is given below:


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Data types:

 Data types specify how we enter data into our programs and what type of data we enter.

 C language has some predefined set of data types to handle various kinds of data that we
use in our program.
 These data types have different storage capacities.

Primitive Data Types

Integer type: Integers are used to store whole numbers.


Type Size(bytes Range
)
int or signed int 2 -32,768 to 32767(-215 to 215 - 1)
unsigned int 2 0 to 65535( 0 to 216 -1)
short int or signed short 1 -128 to 127(-27 to 27 - 1)
int
unsigned short int 1 0 to 255( 0 to 28 - 1)
long int or signed long int 4 -2,147,483,648 to 2,147,483,647 (-231 to 231 - 1)
unsigned long int 4 0 to 4,294,967,295( 0 to 232- 1)
Floating type: Floating types are used to store real numbers. It is used to store decimal numbers
(numbers with floating point value) with single precision.
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type

Character types are used to store characters value.


Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
Void type: void type means no value. This is usually used to specify the type of functions
The following table will illustrates about all data types.

Data Type Memory (bytes) Range Format Specifier


short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld


unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f

double 8 %lf

long double 12 %Lf

Ex: #include <stdio.h>


int main()
{
int a = 1;
char b ='G';
double c = 3.14;
printf("Hello World!\n");

printf(“size of int a is %d\n”,sizeof(a));


printf(“size of char b is %c\n”,sizeof(b));
printf(“size of duoble c is %lf”,sizeof(c));
return 0; }
Output:
size of int a is 2
size of char b is 1
size of duoble c is 8

Constants:
 Constant in C means the content whose value does not change at the time of execution of a
program
 . constants are also called as literals
There are four basic types of constants in C
 Integer constants,
 Floating-point constants,
 Character constants
 String constants

Constant Type of Value Stored


Integer Constant Constant which stores integer value
Floating Constant Constant which stores float value
Character Constant Constant which stores character value
String Constant Constant which stores string value
Integer constants:
 An integer literal can be a decimal, octal, or hexadecimal constant
 A prefix specifies the base or radix

A decimal integer constant:

 A decimal integer constant can consist of any combination of digits taken from the set 0
through 9
Ex: 0 1 743 5280 32767 9999
An octal integer constant:
 An octal integer constant can consist of any combination of digits taken from the set 0
through 7.
Ex: 0 01 0743 077777

A hexadecimal integer constant

 A hexadecimal integer constant must begin with either Ox or OX.


 It can then be followed by any combination of digits taken from the sets 0 through 9 and a
through f (either upper- or lowercase)
 Note that the letters a through f (or A through F) represent the (decimal) quantities 10
through 15, respectively.
Ex: 0x12 0x54 0x9e

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Floating-point Constants:
 A floating-point constant is a base- 10 number that contains either a decimal point or an
exponent (or both).
 While representing decimal form, you must include the decimal point, the exponent, or both;
and while representing exponential form, you must include the integer part, the fractional
part, or both
 The signed exponent is introduced by e or E.the part before e called as mantissa and the
part after called as exponent.

Here are some examples of floating-point literals :


3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants:
 Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type.
 A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t')

Ex: char c = ’a’;

String Constants: String literals or constants are enclosed in double quotes "".

Ex: char s[4]=”svec”;

Variables:
 When we want to store any information, we store it in an address of the computer.
 Instead of remembering the complex address where we have stored our information, we
name that address.
 The naming of an address is known as variable.
 Variable is the name of memory location.
 we can change value of a variable during execution of a program
 A programmer can choose a meaningful variable name. Example : average, height, age,
total etc.

Rules to define variable name:


 Variable name must not start with a digit.
 Variable name can consist of alphabets, digits and special symbols like underscore _.
 Blank or spaces are not allowed in variable name.
 Keywords are not allowed as variable name.

Declaration and Definition of variable:


 Declaration of variables must be done before they are used in the program
Syntax: Data type variablename = value:
Ex: int a=14;
Float b=12.54;
 Declaration does two things.
o It tells the compiler what the variable name is.
o It specifies what type of data the variable will hold.
Ex:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum; //variable declaration
a=10; //variable definition
b=20; //variable definition
sum=a+b;
printf("Sum is %d",sum);
getch();
} output: 30

Statements:
 In c language every statements ends with semicolon
 A statement causes the computer to carry out some action
There are three different classes of statements in C
 Expression statements,
 Compound statements
 Control statements

Arrays:
 An array is an identifier that refers to a collection of data items that all have the same name.
 The data items must all be of the same type.
Syntax: : Datatype arrayname[size];
Ex:
Int a[10]; // array holding the 10 integer type of elements.
Initialization:
type array-name[size] = { list of values };
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; //Compile time error

Note: For more information visit http://www.geeksforgeeks.org


Symbolic Constants:
 A symbolic constant is a name that substitutes for a sequence of characters.
 The characters may represent a numeric constant, a character constant or a string constant.
 Thus, a symbolic constant allows a name to appear in place of a numeric constant, a
character constant or a string
 a program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence
 Symbolic constants are usually defined at the beginning of a program.
Syntax: #define name text

Ex: #define TRUE 1


#define FALSE 0
#define FRIEND "Susan"

Expressions:
 An expression is a combination of operators and operands
 An expression represents a single data item, such as a number or a character
Ex:
Algebraic Expression C Expression

axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a*b/c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x/y+c

Evaluation of Expressions :
Expressions are evaluated using an assignment statement of the form
Syntax: Variable = expression;
 Variable is any valid C variable name
 When the statement is encountered, the expression is evaluated first and then replaces the
previous value of the variable on the left hand side
 All variables used in the expression must be assigned values before evaluation is attempted.

Operator Precedence and Associativity in C:


Operator precedence:

Operator precedence determines which operator is performed first in an expression with


more than one operators with different precedence
Ex: x = 2 * 3 + 4 * 5;
The products 2 * 3 and 4 * 5 are evaluated first; the sum 6 + 20 is computed next; finally the
assignment of 26 is made to x.
Associativity:
 Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left
Ex: x = 7*6 % 15/9;
 Each of the operators above has equal priority; each groups from left to right.
 Therefore, the multiplication 7 * 6 (= 42) is done first, then the residue-modulo with respect
to 15 (42 % 15 =12), and finally the division (of 12) by 9.
 Since the division of one integer by other yields the integer part of the quotient and truncates
the remainder, 12/9 gives the value 1.
 x is therefore assigned the value 1.

An example of the use of precedence of operators


#include <stdio.h>
int main()
{
int a;
int b = 4;
int c = 8;
int d = 2;
int e = 4;
int f = 2;
a = b + c / d + e * f;
/* result without parentheses */
printf(“The value of a is = %d \n”, a);
a = (b + c) / d + e * f;
/* result with parentheses */
printf(“The value of a is = %d \n”, a);
a = b + c / ((d + e) * f);
/* another result with parentheses */
printf(“The value of a is = %d \n”, a);
return 0;
}

Output:
The value of a is = 16
The value of a is = 14
The value of a is = 6
OPERATORS

 An operator is a symbol that specifies the mathematical, logical, or relational operation to be


performed.

Arithmetic Operators :

 There are three types of arithmetic operators in C:


 Binary
 Unary
 Ternary.

Binary Arithmetic Operators:

 An arithmetic operator performs mathematical operations such as addition, subtraction and


multiplication on numerical values.

Operator Description Example


+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an integer B %A= 0
division.
 Except for remainder (%), all other arithmetic operators can accept a mix of integer and real
operands.
 Generally, if both operands are integers, the result will be an integer
 However, if one or both of the operands are real, the result will be a real.
 Integer division always results in an integer outcome, i.e., the result is always rounded off
by ignoring the remainder.

Ex: 9/2 gives 4, not 4.5


–9/2 gives –4, not 4
Unary Arithmetic Operators:

 C programming has more unary operators some of them are increment ++ and decrement --
to change the value of an operand (constant or variable) by 1.
 Increment operators(++)
 Decrement operators(--)

Increment operators(++)

Pre Increment operator( ++ a):

step1: increment the value by 1


step2: assignment will be done.
Ex: int a=5,b;
b=++a;
b value prints 6
Post Increment operator( a ++):

step1: first assignment will be done


step2: increment the value by 1
Ex: int a=5,b;
b=a++;
b value prints 5
Decrement operators(--)

Pre Decrement operator( - - a):

step1: increment the value by 1


step2: assignment will be done.
Ex: int a=5,b;
b=--a;
b value prints 4
Post Decrement operator( a - -):

step1: first assignment will be done


step2: increment the value by 1
Ex: int a=5,b;
b=a- - ;
b value prints 5
Ternary Arithmetic Operators:

 A conditional operator is a ternary operator, that is, it works on 3 operands.


Syntax: expression 1 ? expression 2 : expression 3 ;

 When evaluating a conditional expression, expression I is evaluated first


 If expression 1 is true(i.e., if its value is nonzero), then expression 2 is evaluated and this
becomes the value of the conditional expression
 However, if expression 1 is false (i.e., if its value is zero), then expression 3is evaluated and
this becomes the value of the conditional expression.
Ex: Int i=1;
(i < 0) ? 0 : 100); Output: 100.

 The expression (i < 0) is evaluated first


 If it is true (i.e., if the value of i is less than 0), the entire conditional expression takes on the
value 0(Zero).
 Otherwise (if the value of i is not less than 0),the entire conditional expression takes on
the value 100.
Relational operators & Equality Operators:

 A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Operator Description Example
== Check if two operands are equal 5 = = 3 returns 0
!= Check if two operands are not equal. 5 > 3 returns 1
> Check if operand on the left is greater than operand on the 5 < 3 returns 0
right
< Check operand on the left is smaller than right operand 5 != 3 returns 1
>= check left operand is greater than or equal to right operand 5 >= 3 returns 1
<= Check if operand on left is smaller than or equal to right 5 <= 3 return 0
operand

C program to demonstrate working of relational operators


#include <stdio.h>
int main()
{
int a=10, b=4;

if (a > b)
printf("a is greater than b\n");
else printf("a is less than or equal to b\n");

if (a >= b)
printf("a is greater than or equal to b\n");
else printf("a is lesser than b\n");

if (a < b)
printf("a is less than b\n");
else printf("a is greater than or equal to b\n");

if (a <= b)
printf("a is lesser than or equal to b\n");
else printf("a is greater than b\n");

if (a == b)
printf("a is equal to b\n");
else printf("a and b are not equal\n");

if (a != b)
printf("a is not equal to b\n");
else printf("a is equal b\n");

return 0;
}
Output: a is greater than b

a is greater than or equal to b

a is greater than or equal to b

a is greater than b

a and b are not equal

a is not equal to b

Logical operators:
 :An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false
 Logical operators are commonly used in decision making in C programming.

Operator Meaning of Operator Example


Logical AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)
&&
operands are true && (d > 5)) equals to 0.
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5) ||
||
operand is true (d > 5)) equals to 1.
Logical NOT. True only if the If c = 5 then, expression! (c == 5) equals to
!
operand is 0 0.

C program to demonstrate working of logical operators


#include <stdio.h>

int main()
{
int a=10, b=4, c = 10, d = 20;

if (a>b && c= =d)


printf("a is greater than b AND c is equal to d\n");
else printf("AND condition not satisfied\n");

if (a>b || c= =d)
printf("a is greater than b OR c is equal to d\n");
else printf("Neither a is greater than b nor c is equal "
" to d\n");

if (!a)
printf("a is zero\n");
else printf("a is not zero");

return 0;
}

Output: AND condition not satisfied


a is greater than b OR c is equal to d

a is not zero
Bitwise Operators:

 During computation, mathematical operations like: addition, subtraction, addition and


division are converted to bit-level which makes processing faster and saves power.
 Bitwise operators perform manipulations of data at bit level. These operators also perform shifting
of bits from right to lef
 Bitwise operators are not applied to float or double

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

/* C Program to demonstrate use of bitwise operators */


#include<stdio.h>
int main()
{
unsigned char a = 5, b = 9; // a = 4(00000101), b = 8(00001001)
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}
Output:

a = 5, b = 9

a&b = 1

a|b = 13

a^b = 12

~a = 250

b<<1 = 18

b>>1 = 4
Assignment operator:

 An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =

Syntax: L=R;
Ex: int a=20
Float f=33.38
L = ; // prints error i.e R value required
= R ; // prints error i.e L value required

Arithmetic assignment operators(SHORTHAND):


Assignment operators supported by C language are as follows.

Operator Description Example


= assigns values from right side operands to left side a=b
operand
+= adds right operand to the left operand and assign the a+=b is same as a=a+b
result to left
-= subtracts right operand from the left operand and assign a-=b is same as a=a-b
the result to left operand
*= mutiply left operand with the right operand and assign a*=b is same as a=a*b
the result to left operand
/= divides left operand with the right operand and assign the a/=b is same as a=a/b
result to left operand
%= calculate modulus using two operands and assign the a%=b is same as a=a%b
result to left operand

Special Opearators:

 Comma Operator
Comma operators are used to link related expressions together. For example:
Example: int i,j,k;
 The sizeof operator
The sizeof is an unary operator which returns the size of data (constant, variables, array,
structure etc).
sizeof() operator is used in different way according to the operand type.
1 When operand is a Data Type.
When sizeof() is used with the data types such as int, float, char… etc it simply return amount
of memory is allocated to that data types.
Ex:
#include<stdio.h>
int main()
{
printf("%d\n",sizeof(char));
printf("%d\n",sizeof(int));
printf("%d\n",sizeof(float));
printf("%d", sizeof(double));
return 0;
}
Output
1

2. When operand is an expression When sizeof() is used with the expression, it returns size of the
expression
Ex:
#include<stdio.h>
int main()
{
int a = 0;
double d = 10.21;
printf("%d", sizeof(a+d));
return 0;
}

Output:
8

Type Conversion and Type Casting


Type conversion in c can be classified into the following two types:

 Implicit type casting


 Explicit type casting

Implicit type casting:

 Also known as ‘automatic type conversion’


 When the type conversion is performed automatically by the compiler without programmer’s
intervention, such type of conversion is known as implicit type conversion or type promotion.
 All the data types of the variables are upgraded to the data type of the variable with largest data
type.
 It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
The usual arithmetic conversions are implicitly performed to cast their values to a common type.
The compiler first performs integer promotion; if the operands still have different types, then they
are converted to the type that appears highest in the following hierarchy.

// An example of implicit conversion

#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}
Output: x=107 z=108.000000

Example for Type Promotion


Explicit Type Conversion:

This process is also called type casting and it is user defined. Here the user can type cast the result
to make it of a particular data type.

Syntax: (type) expression

// C program to demonstrate explicit type casting


#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}
Output:

sum = 2

Advantages of Type Conversion

 This is done to take advantage of certain features of type hierarchies or type representations.
 It helps us to compute expressions containing variables of different data types.

You might also like