CP Unit - Ii-1
CP Unit - Ii-1
UNIT-II
Introduction to C Programming- Identifiers, The main () Function, The printf () Function
Programming Style - Indentation, Comments, Data Types, Arithmetic Operations, Expression
Types, Variables and Declarations, Negation, Operator Precedence and Associativity, Declaration
Statements, Initialization.
Assignment - Implicit Type Conversions, Explicit Type Conversions (Casts), Assignment
Variations, Mathematical Library Functions, Interactive Input, Formatted Output, Format
Modifiers.
Introduction to C Programming:
Basic Structure of C Program: To write a C program, we first create functions and then put them
together. A C program may contain one or more sections. They are illustrated below.
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration
and executable part end with a semicolon.
6. Subprogram section: The subprogram section contains all the user-defined functions that
are called in the main () function. User-defined functions are generally placed immediately
after the main () function, although they may appear in any order.
Indentation is one of the most important aspects in any programming domain. But this is
often the most neglected part during the programming and the developers are mostly reluctant to
follow it.
Code Indentation
Programming style and indentation can be defined as the way you follow to organize and
document your source code. Code indentation is a part of style and it is more of aesthetic interest.
C Programming Page 2
Unit - II
If we follow proper style guide and indentation then a program can be just like a POEM. And the
reader will be comfortable enough to SAIL through it and understand the meaning. As we know a
proper code indentation will make it:
Easier to read
Easier to understand
Easier to modify
Easier to maintain
Easier to enhance
The purpose of code indentation and style is to make the program more readable and
understandable. It saves lots of time while we revisit the code and use it. A style guide provides a
road map which the developer should follow and implement in coding. So in a group of developers,
all the code generated will be of consistent in nature and reusable by any coder/developer. The
worst part of coding is not to follow the style and indentation guide when the project is in the mid
way of development. Some time it happens due to time pressure and many other factors. But we
need to keep in mind that good code is always better even if we need to give some more time
because in the long run it will save a lot of time. But unfortunately, it is often forgotten and the
trouble comes at a later stage. And in that stage it is very difficult to rectify and recover.
As we know, a program is written only once during coding but it is read many times at a
later stage. Following are some future points when we refer the code again.
During reading an understanding the program
During code debugging
During adding new code to the existing program
During updating the existing program
C Programming Page 3
Unit - II
else
{
computer_wins++;
printf("Your destiny is under my control!\n");
}
Following code sample shows the spacing best practices
// NOT Recommended // Recommended
test (i, j); test(i, j);
All binary operators should maintain a space on either side of the operator.
// NOT Recommended // Recommended
a=b-c; a = b - c;
a = b-c;
a=b - c;
All unary operators should be written immediately before or after their operand.
// NOT Recommended // Recommended
count ++; count++;
C Programming Page 4
Unit - II
All commas and semicolons must be followed by single whitespace.
// NOT Recommended // Recommended
for ( j = 0;j < 10;j++) for ( j = 0; j < 10; j++)
Identifiers:
Identifier refers to the name of variables, functions and arrays. These are user defined
names and consists of a sequence of letters and digits.
Both uppercase and lowercase letters can be used, and C language is case sensitive. A
special symbol underscore ( _ ) is also permitted.
Rules for identifiers
First character must be an alphabet or underscore.
Must consist of only letters, digits or underscore.
Should not be a keyword and should not have any blank space.
First 31 characters of an identifier are significant (32 bit computer)
C is a case – sensitive language i.e, AREA and area both are different identifiers.
Example : - int num;
Char name;
Where num and name are identifier names.
C Programming Page 5
Unit - II
Data types:
Data types in C refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
Integer Data Types: Integers are whole numbers with a range of values, range of values are
machine dependent. Generally an integer occupies 2 bytes memory space and its value range
limited to -32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign
and rest 15 bits for number.
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.
C Programming Page 6
Unit - II
Syntax:
int num1;
Floating Point Data Types: The float data type is used to store fractional numbers (real numbers)
with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the
accuracy of the floating point number is insufficient, we can use the double to define the number.
The double is same as float but with longer precision and takes double space (8 bytes) than float.
To extend the precision further we can use long double which occupies 10 bytes of memory space.
Syntax:
float num1;
double num2;
C Programming Page 7
Unit - II
Character type variable can hold a single character and are declared by using the keyword char. as
there are singed and unsigned int (either short or long), in the same way there are signed and
unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.
Syntax:
char ch = ‘a’;
Example: a, b, g, S, j.
MODIFIERS IN C:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the
amount of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase
the range by using long int which is 8 byte. We can decrease the range by using short int
which is 2 byte.
There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Below table gives the detail about the storage size of each C basic data type in 16 bit
processor.
Please keep in mind that storage size and range for int and float datatype will vary depend
on the CPU processor (8,16, 32 and 64 bit)
storage
S.No C Data types Size Range
C Programming Page 8
Unit - II
unsigned long
13 long int 8 2(power)64 –1
Signed data types can hold both positive and negative values.
Unsigned data types can hold large positive values but cannot hold negative values.
Variable:
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows:
C Programming Page 9
Unit - II
Syntax:
type variable_list;
Examples:
int i, j, k;
char c, ch;
float f, salary;
double d;
Example
Try the following example, where variables have been declared at the top, but they have been
defined and initialized inside the main function:
#include <stdio.h>
main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
}
Operators: An operator is a symbol that tells the computer to perform a specific operation of the
operands.
Operand : An operand is the data or the variable on which the operator performs the operation.
The operators are classified depending upon the number of operands for the operation.The
opearators are divided into following types:
C Programming Page 10
Unit - II
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Example: +x, -y
C Programming Page 11
Unit - II
Example program to illustrate the usage of arithmetic operators.
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators: Relational operators are used to compare two or more operands.
Operands may be variables, constants or expressions.
C Programming Page 12
Unit - II
Relational operators are used in decision making process, they are generally used in
conditional or control statements.
Example:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
C Programming Page 13
Unit - II
}
Output:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Logical Operators: Logical operators are used to combine the results of 2 or more conditions.
Example:
#include <stdio.h>
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
C Programming Page 14
Unit - II
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
Output:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Eg: x =10;
x = a+b;
x = y;
C Programming Page 15
Unit - II
Nested or multiple assignment: We can assign a single value or an expression to multiple
variables.
Example: i=j=k=1;
x=y=z=(i+j+k);
Example:
#include <stdio.h>
main()
{
int i,j,k;
k=(i=4, j=5);
printf(“ k=%d”,k);
Output: k=5
Increment and decrement operators: ‘C’ has two very useful operators not generally found in
other languages, these are increment (++) and drecement(--) operators.
These operators are called unary operators, because they act upon only one variable.
Operator Meaning
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post drecrement
Example:
#include<stdio.h>
main()
{
int a=10;
C Programming Page 16
Unit - II
printf(“a++=%d\n”, a++);
printf(“++a=%d\n”,++a);
printf(“—a=%d\n”,a--);
printf(“a--=%d\n”,--a);
}
output:
a++ = 10
++a = 12
--a = 11
a-- = 11
Two expressions are separated by colon (:) If the condition is true expression1 is
evaluated otherwise expression2 is evaluated.
Example:
#include<stdio.h>
main()
{
printf(“result =%d”, 2==3?4:5);
}
Output :
Result = 5
#include<stdio.h>
main()
{
3>2 ? printf(“true”) : printf(“false”);
}
Output:
True
Bitwise operators: Bitwise operators work on bits and perform bit-by-bit operation. These are
used for testing the bits or shifting them right or left. May not be applied for float/double. he
truth table for &, |, and ^ is as follows:
C Programming Page 17
Unit - II
A = 0011 1100
B = 0000 1101
----------------------
~A = 1100 0011
Example:
#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Expression types: An expression is any legal combination of symbols that represents a
value. There are 3 types of expressions
1. Simple ex:c=++a
2. Combined ex: c=a+b
3. Complex ex:d=(a*x+b)/c
Formatted output:
[arg = argurment]
C Programming Page 19
Unit - II
:The control string indicates how many arguments follow and what the types are:”. The
arguments (arg1, arg2, …… argn) are the variables whose values are formatted and printed
according to the specifications of control string.
Example :
#include<stdio.h>
main()
{
printf(“Pragati Engineering College\n”);
printf(“Mechanical Engineering\n”);
}
Output:
Pragati Engineering College
Mechanical Engineering
Note: The number type and order of arguments should match with the format specifiers.
Example:
int i=1234;
printf(“%6d”,i); 1 2 3 4
printf(“%-6d”,i);
1 2 3 4
printf(%d”,i);
printf(%06d”,i); 0 0 1 2 3 4
C Programming Page 20
Unit - II
Example:
Float f =56.7891;
Printf(“%9.4f”,f); 5 6 . 7 8 9 1
Printf(“%7.2f”,f); 5 6 . 7 9
Printf(“%-7.2f”,f); 5 6 . 7 9
Output format for characters:
Example:
#include<stdio.h>
main()
{
char ch = ‘a’;
printf(“%3c”, ch);
}
Output:
A
Formatted input:
C Programming Page 21
Unit - II
Example :
#include<stdio.h>
main()
{
int i;
printf(“enter the value of i:”);
scanf(“%d”,&i);
printf(“\n%d”,i); or printf(“\nthe value of i is %d”, i);
}
Output:
Enter the value of i: 5
The value of i is 5
Operator Precedence:
C Programming Page 22
Unit - II
Type Conversion: The ‘C’ language allows mixing of constants or variables of different data
types, and then it follows a rule for evaluating those expressions.
The type conversion or type casting refers to the process of changing one data type to
another. There are two types of conversions.
1. Implicit type conversion – it is referred as Coercion
2. Explicit type conversion – it is referred as Casting
Implicit conversion: It is an automatic type conversion. When the types of the two operands in a
binary expression are different, C automatically converts one type to another. This is known as
implicit type conversion.
Example-1:
int i = 1234;
float f = 35.0;
char c = ‘a’;
i = c; /* value of I is 65 */
f = i; /* value of f is 1234.0 */
C Programming Page 23
Unit - II
Example-2:
#include<stdio.h>
main()
{
int i = 3650;
float d = 245.3;
char c = ‘a’;
printf(“ int * float is = %f\n”, i * d);
printf(“float * char is = %f \n”, d*c);
}
Explicit type conversion: It can be made possible to convert one data type to another forcefully
by ourselves.
To convert data from one type to another, we specify the new type in parenthesis before
the conversion.
Syntax: var1 = (data type) variable2;
Example: int a =10;
float(a);
float (a) will contain 10.00
Example: float a = 6.5;
Float b = 6.5;
int result = (int) a + (int) b;
int result = 12;
Hence the result is 12 instead of 13.
Example:
#include<stdio.h>
main()
{
int a=100,b=45;
float c;
c=(float)(a/b);
printf(“float = %f”,c);
C Programming Page 24
Unit - II
}
Output:
float = 2.22
Mathematical Library functions:
The math.h header defines various mathematical functions and one macro. All the functions
available in this library take double as an argument and return double as the result.
Function & Description:
1. double exp(double x)
returns the value of e raised to the x power
2. double log(double x)
returns natural log of x; x must be zero or positive
3. double log10(double x)
returns base-10 log of x; x must be zero or positive
4. double pow(double x, double y)
returns the value of x raised to the y power
Note: to square a number, multiply it by itself:
x_sqd = x * x;
This is much faster! The pow function calculates and uses logarithms, and does not check
for the power being a small integer.
5. double sqrt(double x)
returns square root of x; x must be zero or positive
6. double cos(double x)
returns cosine of x
7. double sin(double x)
returns sine of x
8. double tan(double x)
returns tangent of x
9. double acos(double x)
returns arc cosine of x
10. double asin(double x)
returns arc sine of x
C Programming Page 25
Unit - II
C Tokens:
C Programming Page 26
Unit - II
Keywords:
Keyword serves as the building blocks for program statements. All keywords have a fixed
meaning and cannot be changed.
Keywords cannot be used as normal identifier names.
There are 32 keywords available in traditional C.
Few examples of keywords used in C are listed below
auto else long switch break enum
register typedef case extern return union
char float short unsigned const for
signed void continue goto sizeof volatile
default if static while do int
struct _packed double
Additional keywords have been added in C99 and they are as follows:
complex bool imaginary inline
restrict
C TYPE QUALIFIERS The keywords which are used to modify the properties of a variable are
called type qualifiers.
1. const
2. volatile
1. CONST KEYWORD:
Constants are also like normal variables. But, only difference is, their values can’t be
modified by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax: const data_type variable_name; (or) const data_type *variable_name;
2. VOLATILE KEYWORD:
When a variable is defined as volatile, the program may not change the value of the variable
explicitly.
C Programming Page 27
Unit - II
But, these variable values might keep on changing without any explicit assignment by the
program. These types of qualifiers are called volatile.
For example, if global variable’s address is passed to clock routine of the operating system to
store the system time, the value in this address keep on changing without any assignment by
the program. These variables are named as volatile variable.
Syntax: volatile data_type variable_name; (or) volatile data_type *variable_name;
Constants:
A constant refers to fixed values that do not change during the execution of a program.
Basic types of C constants are shown in the flowchart
TYPES OF C CONSTANTS:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
Constant
S.no type data type Example
intunsigned
int long 53, 762, -478 etc 5000u,
Integer int long 1000U
1 constants long int etc483,6472,147,483,680
C Programming Page 28
Unit - II
Real or
Floating
point
2 constants float doule 10.456789600.123456789
character
5 constants char ‘A’ , ‘B’, ‘C’
string
6 constants char “ABCD” , “Hai”
1. INTEGER CONSTANTS IN C:
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.
2. REAL CONSTANTS IN C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
C Programming Page 29
Unit - II
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Hexadecimal constant (N –
\XN hex.dcml cnst)
Strings:
Strings are nothing but array of characters ended with null character (‘\o’). This
null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by
single quotes in C.
Example :- char name[10];
In this example the variable name can store upto 10 bytes.
C Programming Page 30
Unit - II
Special Symbols :
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose.
[] () {} , ; : * … = #
Braces {}: These opening and ending curly braces marks the start and end of a block of
code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
C Programming Page 31