C Programming (1,2,3)
C Programming (1,2,3)
Problem Solving : The task of expressing the solution of complex problems in terms of
simple operations understood by the computer.
1. Problem definition : The problem should be defined in user’s language so that the
problem can be clearly understood. A proper definition helps in generating a proper solution
for the problem. In this step analysis of what should be done is decided.
2. Problem analysis : In this step the requirements of the problem are understood. The
requirements such as input-output, time constraints, processing requirements, memory
limitations etc are understood and the method to solve the problem is selected.
3. Designing of a solution : After defining and analyzing the problem, defining the solution is
necessary. The process of designing a solution involves certain design tools such as
algorithm and flowchart.
Algorithm
An algorithm is a step-by-step procedure to solve a given problem. The word algorithm is
derived from the name of 9th century Arab mathematician Al Khowarizmi, who developed
methods for solving problems which used specific step-by-step procedure.
Flowchart
A flowchart is a pictorial or graphical representation of a solution to a given problem.
Types of flowchart
Symbol Purpose
Terminal
Start and Stop
Input/ Output
Input or output of data
Processing
Represents calculations, data manipulations
or information processing
Decision Making
Represents comparison, a decision that
determines alternate paths to be followed
Predefined process
A group of operations not detailed in the
particular set of flowcharts
Connector
An entry from, or an exit to another part of
the flowchart
Flow direction
The direction of processing
4. Coding : The process of writing program instructions for the given problem. Each step of
the solution is converted to program instructions.
5. Testing and debugging: The process of detecting and correcting the errors in a program.
6. Program documentation :The written text and comments that make a program easier for
others to understand, use and modify.
Introduction to C programming
Characteristics of C
• C is a structured language where the program can be modularized.
• C is a general purpose programming language.
• C helps is development of system software and application software
• C is a portable language , program written in one machine can be run of different
machines with little or no modifications.
• C has rich set of built-in functions.
• C has limited set of reserved words.
• C is a flexible language, there is no rigid format.
Advantages of C
1. C being a structured language helps in modularizing the program i.e., dividing a
problem into number of modules.
2. C compiler is compact and can be easily ported on small machines including PC’s.
3. C is a middle level language, hence suitable for developing system software and
application software.
4. It is a portable language i.e., programs written in one machine can be easily run on
other machine without much modification.
5. Programs written in C execute faster than compared to other languages.
6. C provides rich set of built-in functions.
7. It is easily expandable .
8. It can deal with bits, bytes, word and addresses.
9. It has very few fundamental data types and keywords.
10. It has wide variety of derived data structures such as arrays, structures, unions and
pointers.
Executing of a C program
Executing of a C program has four phases:
1. Editing or creating phase : C programs can be written using Turbo C, Microsoft C etc.
In this phase the user types the program in the editor. This is called a source
program.
2. Compilation phase : In this phase the compiler checks the program for errors and
once all the errors are corrected the program is converted to machine
understandable form called the object program.
3. Linking phase: In this phase, the program is linked with the C-library. The compiled
linked program is called the executable code.
4. Execution phase : In this phase the program is executed.
Character set : It is a set of valid characters that a programming language can be identified.
In C language characters are grouped into the following categories,
1. Letters(all alphabets a to z & A to Z).
2. Digits (all digits 0 to 9).
3. Special characters, ( : ; “ . , + * - / & )
4. White spaces.
Keywords
Keywords are preserved words that have special meaning in C language. The meaning has
already been described. These meaning cannot be changed. There are total 32 keywords in
C language.
Auto double int struct
Break else long switch
Case enum register typedef
Const extern return union
Char float short unsigned
Continue for signed volatile
Default goto sizeof void
Do if Static while
Identifiers
In C language identifiers are the names given to variables, constants, functions and user-
defined data. These identifier are defined against a set of rules.
Rules for an Identifier
1. An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
2. The first character of an identifier can only contain alphabet or underscore.
3. Identifiers are also case sensitive in C. For example name and Name are two different
identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.
6. Identifier should be a whole word and no blank space should be used.
7. Generally the identifier length is 8 to 10 characters though few compilers allow up to 32
characters.
Integer Constant : An integer constant is a whole number without a decimal point. Integer
constants can be represented in three different number systems:
Octal constant : An octal constant can be any combination of digits from 0 to 7. The first
digit of an octal constant must be a 0 so as to differentiate it from a decimal constant.
Ex: 05, 0476, -07453
Float Constant: Floating point number contains both integer part and a fractional part.
Floating point numbers can be represented in two forms, decimal form(fractional form) and
exponential form.
Fractional Form : Floating point numbers are written with a decimal point. Both positive and
negative numbers can be represented in this form.
Ex: 19.6, 0.16, -5.76
Exponential Form: Very large and very small numbers are represented in this form. The
symbol ‘E’ or ‘e’ is called used to represent a real number. The number before ‘E’ is called
the mantissa and the number after ‘E’ is called the exponent.
Ex: 3.5E-3, -3.58E4, 64e-8
Character constant
Single character constant: A character constant is any character enclosed within single
quotes.
Ex: ch=’T’;
The escape sequence/ back slash characters are also considered to be a character constant.
Ex: ch=’\n’; // a new line character
Punctuators
Punctuators are the symbols available in C.
+ - * / , . ; : ‘ “
{ } \ ~ @ ^ _ = | [
] < > ?
Variable : A variable is the name given to a memory location that contains data value and
whose value can vary during the program execution.
Data Types
Data type indicates the type of data a variable can hold.
There are four types of data types
1. Primary / fundamental data types
2. User-defined data types
3. Derived data types
4. Empty data type
1. Primary / Fundamental Data Type
i) int ( Integer Type) : It represents that a number is of integer type. Integer occupies 2
bytes of memory space and the values range from -32768 to 32767. All the arithmetic
operations are possible with integer values.
ii) float ( Floating Point Type) : It represents a real number. It occupies 4 bytes of
memory space and the values range from 3.4e-38 to 3.4e38.
iii) char ( Character Type) : It represents that a character variable. It occupies 1 byte of
memory space and the range of values varied from -128 to 127 for signed characters.
The operations performed are input and output.
iv) double: It represents a double precision floating point number. It occupies 8 bytes of
memory space and the value ranges from 1.7e-308 to 1.7e308.
Modifiers : C allows to modify the range of values of the fundamental data types through
modifiers
i) short int : It is considered to be half of that of int. It occupies 1 byte of memory space and
the range is -128 to 127.
where type→ existing data type, identifier→ new name given to the existing data type.
Symbolic constant
Ex:
#define PI 3.142
#define MAX 100
Symbolic constants are defined using uppercase characters.
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.
Operator Description Example
+ Adds the operands on either side of it 240 + 60 results in 300
- Subtracts the operand on the right from the 620 – 20 results in 600
operand on the left.
* Multiplies the operands on either side of it 20 * 4 results in 80
/ Divides the operand on the left by the operand 440/ 8 results in 55
on the right
% Divides the operand on the left by the operand 56 % 6 results in 2
on the right and returns the remainder
Assignment Operator
Assignment operator assigns a value to a variable . ‘ = ‘ is used as an assignment operator.
General form: operand = value;
Ex: a= 10
Assignment operators can be used with arithmetic operators as a short hand notation
Relational operators
Relational operators compares the values of two operands and returns the result in either
True or False.
Operator Description Example
== Checks if two operands are equal 100 = = 120 → False
!= Checks if two operands are not equal. 120 != 220 → True
> Checks if operand on the left is greater 440 > 400 → True
than operand on the right
< Checks if operand on the left is smaller 610 < 400 → False
than operand on the right
>= Checks if left operand is greater than or 70 >= 80 →False
equal to the right operand
<= Checks if operand on left is smaller than 99 <= 155 →True
or equal to the right operand
Logical operators
Logical operators compares two or more relational expressions and results in either true or
false.
There are three logical operators in C
1. Logical AND (&&)
2. Logical OR ( || )
3. Logical NOT (! )
Logical AND ( && ) : Logical AND operator compares two or more relational expressions
and if all the expressions are true the result obtained is true otherwise false.
Expression 1 Expression 2 Expression 1 && Expression 2
False False False
False True False
True False False
True True True
Ex: i) (20==30 ) && ( 300>=50) results in False
ii) ( 100 != 150) && ( 200 < 150) && ( 510 >= 66) results in True
Bitwise operators
Bitwise operators works on bits and performs bit by bit operation.
The Bitwise operators in C are:
1. Bitwise AND (&)
2. Bitwise OR ( | )
3. Bitwise XOR ( ^ )
4. Bitwise One’s complement ( ~)
5. Bitwise Left Shift ( << )
6. Bitwise Right Shift ( >> )
1. Bitwise AND (& ): It compares the bits and if all the corresponding bits are 1, the resulting
bit is a 1, otherwise a 0
Operand1 Operand2 Operand1 & operand2
0 0 0
0 1 0
1 0 0
1 1 1
Ex: 10101010 & 11110000 results in 10100000
2. Bitwise OR (| ): It compares the bits and if any one of the corresponding bit is 1, the
resulting bit is a 1, otherwise a 0
Operand1 Operand2 Operand1 & operand2
0 0 0
0 1 1
1 0 1
1 1 1
Ex: 10101010 | 11110000 results in 11111010
5. Bitwise Left Shift (<<) : Left shift operator shifts the bits in the operand to the left. The
number of places the bits are sifted depends on the number following the operand. The
blanks created towards the right must be filled by 0’s.
Ex : a= 1011 0011
a << 1 results in 01100110
a<< 3 results inn 10011000
6. Bitwise Right Shift (>>) : Right shift operator shifts the bits in the operand to the right.
The number of places the bits are sifted depends on the number following the operand. The
blanks created towards the left must be filled by 0’s.
Ex : a= 1011 0011
a >> 2 results in 00101100
a>> 4 results in 00001011
Conditional operator : It is also called as ternary operator as it uses three expressions. The
ternary operator is used to replace a if-else statement in a program.
General form : variable = exp1 ? exp2 : exp3 ;
exp1 is evaluated and if it is true exp2 is assigned to variable and if exp1 is false exp3 is
assigned to variable.
Ex : Consider the following statement
if( n % 2 == 0)
even= 1;
else
odd=0;
the above if-else statement can be written as
even= (n%2==0) ? 1 : 0 ;
1. Comma operator ( , )
2. sizeof( ) operator
3. Address operator ( & )
4. Pointer operator ( * )
5. Dot operator ( . )
6. Arrow operator (→)
Comma operator : A comma operator is used to link the related expressions together. The
group of expressions are separated by comma (,).
Ex : sum =( a=20, b=25, a+b);
sizeof( ) operator : sizeof( ) returns the number of bytes necessary to store a variable.
General form: sizeof(operand);
Ex: i) int num;
sizeof(num);
return 2 (in bytes as num is an integer type)
ii) sizeof(float);
returns 4 (in bytes)
Expressions
An expression is a valid combination of operators and operands that computes to a value.
Consider the following expression
12 + b * 10
Here 12, b and 10 are the operands and +, * are the operators.
The expressions in C is classified into
1. Arithmetic expression
2. Relational expression
3. Logical expression
i. Integer mode expression : This type of expression consists of integer type operands and
arithmetic operators ( +, -, *, /, %).
Ex: i) 10 + 3 -2 which results in 11 ii) 10 + 6 % 3 results in 10
Logical Expressions: It consists of operands and relational expressions and results in either
true or false.
Ex: i) ( 100>=35) && ( 100<100) results in false ii) (44==66) || ( 56>30) results in true
iii) !( 60+40 ==100) results in false
Type conversions
The process of converting one predefined type into another is called type conversion.
There are two types of conversions
1. Implicit type conversion
2. Explicit type conversion( Type casting)
1. Implicit type conversion: This type conversion takes place automatically when operands
of different data types are manipulated.
Mathematical functions
Mathematical functions are defined in C library by including math.h header file in the
program.
A function is written in a program as
function _name(argument list);
3abc 3*a*b*c
2(a+b+c) 2*(a+b+c)
𝑎 a/b +c
+𝑐
𝑏
2x2+3x+5 2*x*x+3*x+5
√𝑎 2 + 𝑏 2 sqrt(a*a+b*b)
−𝑏 + √𝑏 2 − 4𝑎𝑐 (-b+sqrt(b*b-4*a*c))/(2*a)
2𝑎
(𝑎 + 𝑏)4 pow(a+b, 4)
2. Unformatted I/O statements : doesn’t allow to specify the type of data and the way it
should be read and written.
Unformatted I/0
Formatted I/O
Formatted Input
scanf() function is used to read the value for a variable from the keyboard. scanf() is used to
enter numeric, character and string data.
Syntax: scanf(“control string”, address-list);
where control string → contains the conversion specifiers.
address-list → address of the variables
Ex: scanf(“%d%d”,&a,&b);
Formatted output
printf() function is used to print the data on the screen.
Syntax: printf(“control string”, variable-list);
where control string → consists of text label, back slash characters or conversion characters.
variable-list → list of variables to be displayed.
Format specifiers
Inorder to print the output in a particular order, C provides format specifiers which begin
with % sign followed by a number and a conversion specifier.
Syntax : % -w. p
where
- is to left justify the value
w field width(optional)
p Number of places after decimal (precision)
Right justified : % w d
Left justified : % - w d
where w→ field width
Ex:
i) printf(“%d”, 2365); ii) printf(%8d”,2365);
2 3 6 5 2 3 6 5
2 3 6 5
1 2 3 . 5 6 7 0 0 0
ii) printf(“%10.2f”,n);
1 2 3 . 5 6
iii) printf(“%-10.2f”,n);
1 2 3 . 5 6
i) printf(“%c”,A); A
ii) printf(“%4c”,A); A
iii) printf(“%-4c”,A); A
Reading a string
Printing a string
puts() function is used to display a string.
Syntax: puts(string variable name);
Ex: char name[20]=”Dennis”;
puts(name);
will display “Dennis” on the screen.