Unit 1
Unit 1
Course Objective:
This course introduces the basic concepts of programming in C and various programming statements of the C
languages. This Course introduces Data structures and types of data structures namely linear and non-linear types.
UNIT – I INTRODUCTION
Program development steps: Algorithm, flowchart, structure of C program, A Simple C program, identifiers, basic
data types and sizes, Constants, variables, Operators, expressions, type conversions, conditional expressions,
Input-output statements, statements and blocks: if and switch statements, loops- while, do-while and for
statements, break, continue, go to and labels, programming examples.
Arrays – types: one- dimensional, multi-dimensional, Designing structured programs: Functions, user defined
functions, standard library functions, recursive functions, C program examples.
Derived types: structures, nested structures, self-referential structures, unions, typedef, pointers-dynamic memory
managements functions, command line arguments, C program examples.
Introduction to data structures: Linear Data structures – Array, Stack, Queue – Applications of Array: Searching -
Linear and binary search methods, sorting- Application of stack: Postfix evaluation.
COURSE OUTCOME:
CO2: Write programs using the various control structures and functions.
TEXT BOOKS:
1. Computer science, A structured programming approach using C, B.A. Forouzan and R.F.Gilberg, Third edition,
Thomson
REFERENCES:
2. C Programming with problem solving, J.A. Jones & K. Harrow, Dreamtech Press Programming in C - Stephen
G. Kochan, III Edition, and Pearson Education.
Unit – I:
Algorithm:
The step-by-step procedure to solve any logical and mathematical problem is called an Algorithm.
Three characteristics of an algorithm are:
1. Input — An algorithm accepts an input.
2. Generality — An algorithm works in a set of inputs.
3. Definiteness — Each instruction should be written in a simple and precise manner so that everyone can
understand it.
Flowchart:
A flowchart is a diagrammatic representation of a problem-solving process in which steps are laid out in logical
order.
Flowcharts normally use standard symbols to represent the different types of instructions. These symbols are used
to construct the flowchart and show the step-by-step solution to the problem.
History of C language:
Dennis Ritchie is called as "The Father of C Programming Language". ’C’ is a powerful programming language
which is strongly associated with the UNIX operating system. Even most of the UNIX operating system is coded
in ‘C’. Initially ‘C’ programming was limited to the UNIX operating system, but as it started spreading around the
world, it became commercial, and many compilers were released for cross-platform systems. Today ‘C’ runs under
a variety of operating systems and hardware platforms. As it started evolving many different versions of the
language were released. At times it became difficult for the developers to keep up with the latest version as the
systems were running under the older versions. To assure that ‘C’ language will remain standard, American
National Standards Institute (ANSI) defined a commercial standard for ‘C’ language in 1989. Later, it was
approved by the International Standards Organization (ISO) in 1990. ‘C’ programming language is also called as
‘ANSI C’.
Turbo C compiler:
Turbo C is an IDE (Integrated Development Environment) and compiler for the C programming language. It was
launched in 1987. It is a free and open-source compiler for C and C++. It was the most popular IDE and compiler
because of its small size, fast compilation speed, and, comprehensive manuals.
Structure of C Program:
Comment line - It indicates the purpose of the program used for increasing the readability of the program. Two
types: Single (//) and multi-line (/*… */) comments
Preprocessor Directive:
In this section we include the header files into our source program by using preprocessor command which starts
with #.
Global variable: 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.
main(): Every C program must have one main function. Main function is the starting point of program from where
the program execution starts.
Local variable: a variable declared within a function or a block of code is called a local variable. Local variables
are frequently used to temporarily store data in a defined scope where they can be accessed and manipulated.
They are stored in the memory stack, Once the function or block of code in which the local variable is declared
finishes executing. The variable is automatically removed from the memory.
User-defined functions are generally placed immediately after the main () function, although they may appear in
any order.
Simple C program:
#include <stdio.h>
int main ()
{
printf ("welcome to c Programming language.\n");
return 0;
}
Identifiers:
Identifiers are basically names given to program elements such as variables, arrays, and functions. They are
formed by using a sequence of letters (both uppercase and lowercase), numerals, and underscores.
Keywords:
Like every computer language, C has a set of reserved words often known as keywords that cannot be used as an
identifier. All keywords are basically a sequence of characters that have a fixed meaning. By convention, all
keywords must be written in lower case letters. The following table contains the list
of keywords in C.
Data type determines the set of values that a data item can take and the operations that can be performed on the
item.
C also supports four modifiers—two sign specifiers (signed and unsigned) and two size specifiers (short and long).
Variables:
A variable is defined as a meaningful name given to a data storage location in the computer memory. When using
a variable, we actually refer to the address of the memory where the data is stored. C language supports two basic
kinds of variables.
Numeric Variables
Numeric variables can be used to store either integer values or floating-point values. Modifiers like short, long,
signed, and unsigned can also be used with numeric variables. The difference between signed and unsigned
numeric variables is that signed variables can be either negative or positive but unsigned variables can only be
positive. Therefore, by using an unsigned variable we can increase the maximum positive range. When we omit
the signed/unsigned modifier, C language automatically makes it a signed variable. To declare an unsigned
variable, the unsigned modifier must be explicitly added during the declaration of the variable.
Character Variables
Character variables are just single characters enclosed within single quotes. These characters could be any
character from the ASCII character set—letters (‘a’, ‘A’), numerals (‘2’), or special characters (‘&’).
Declaring Variables
To declare a variable, specify the data type of the variable followed by its name. The data type indicates the kind
of values that the variable can store. Variable names should always be meaningful and must reflect the purpose
of their usage in the program. In C, variable declaration always ends with a semi-colon. For example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Initializing Variables
While declaring the variables, we can also initialize them with some value. For example,
int emp_num = 7;
float salary = 9800.99
char grade = ‘A’;
double balance_amount = 100000000;
Constants
Constants are identifiers whose values do not change. While values of variables can be changed at any time, values
of constants can never be changed. Constants are used to define fixed values like pi or the charge on an electron
so that their value does not get changed in the program even by mistake.
Declaring Constants
To declare a constant, precede the normal variable declaration with ‘const’ keyword and assign it
a value.
Constant Meaning
\a (Beep sound) Gives beep sound in printing results on output screen.
\b (Backspace) Prints the output one space back
\f Form Feed Gives the form feed
\n New Line Prints the output in new line
\r Carriage Return Cursor is returned to the required place
\t Tab (Horizontal) Prints tab space on the output screen
\v Vertical Tab Prints tab space vertically
\\ Backslash Prints the backslash
\´ Single Quote Prints the single quote
\" Double Quote Prints the double quote
\? Question Mark Prints the question mark
\0 Null Used to terminate the string
Expressions:
An expression in C is a combination of operands and operators. Example A + B * C where A, B, C are operands
and +, * are operators
Operators:
It is a special kind of symbols for performing particular tasks. Based on the number of operands, operators are
classified into 3 types.
1. Unary Operator
2. Binary Operator
3. Ternary Operator
When we are working with unary operator it required to use only one operand. Binary operator takes 2 operands
and ternary operator takes 3 operands
Operators are classified into
1. Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands.
If a = 9, b = 3 then result of arithmetic operations are,
2. Relational Operator:
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.
3.Logical Operators:
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or
false.
4.Assignment operators:
An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
5.Increment and Decrement operators:
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are
unary operators, meaning they only operate on a single operand.
Two types:
• pre increment / pre decrement
• post increment / post decrement
6.Bitwise operators:
Bitwise operators perform operations at the bit level. These operators include: bitwise AND, bitwise OR, bitwise
XOR, and shift operators.
7.Conditional Operators/expressions (Ternary operators):
exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result of the expression,
otherwise exp3 is evaluated and becomes the result of the expression.
For example,
large = (a > b) ? a : b
The conditional operator is used to find the larger of two given numbers. First exp1, that is a > b, is evaluated. If
a is greater than b, then large = a, else large = b. Hence, large is equal to either a or b, but not both.
8.special operators:
Comma Operator
Comma operators are used to link related expressions together.
Operator precedence:
The following table lists the operators that C language supports in the order of their precedence (highest
to lowest). The associativity indicates the order in which the operators of equal precedence in an
expression is evaluated.
Type conversions/Type casting:
Type Conversions are used to convert the value of one data type into another.
There are two types of conversion in C:
● Implicit Conversion (automatically)
● Explicit Conversion (manually)
Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to another.
For example, if you assign an int value to a float type:
float myFloat = 9;
printf("%f", myFloat); // 9.000000
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Input-output statements:
scanf()
The scanf()function is used to read formatted data from the keyboard. The syntax of the scanf()
function can be given as,
scanf ("control string", arg1, arg2, arg3 ...argn);
The control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by the arguments, arg1, arg2, ...,argn.
The prototype of the control string can be given as,
%[*][width][modifier]type
* is an optional argument that suppresses assignment of the input field. That is, it indicates that
data should be read from the stream but ignored (not stored in the memory location).
width is an optional argument that specifies the maximum number of characters to be read.
However, if the scanf function encounters a white space or an unconvertible character, input is
terminated.
modifier is an optional argument (h, l, or L) , which modifies the type specifier. Modifier h is
used for short int or unsigned short int, l is used for long int, unsigned long int, or double values.
Finally, L is used for long double data values.
type specifies the type of data that has to be read. It also indicates how this data is expected to
be read from the user. The type specifiers for scanf function are given in Table.
Type specifiers
The scanf function ignores any blank spaces, tabs, and newlines entered by the user. The function simply returns
the number of input fields successfully scanned and stored. As we have not studied functions till now,
understanding scanf function in depth will be a bit difficult here, but for now just understand that the scanf function
is used to store values in memory locations associated with variables. For this, the function should have the address
of the variables. The address of the variable is denoted by an & sign followed by the name of the variable. Look
at the following code that shows how we can input value in a variable of int data type:
int num;
scanf(" %4d ", &num);
The scanf function reads first four digits into the address or the memory location pointed by num.
printf()
The printf function is used to display information required by the user and also prints the values
of the variables. Its syntax can be given as:
printf ("control string", arg1,arg2,arg3,...,argn);
After the control string, the function can have as many arguments as specified in the control
string. The control string contains format specifiers which are arranged in the order so that they
correspond with the arguments in the variable list. It may also contain text to be printed such as
instructions to the user, identifier names, or any other text to make the text readable.
Note that there must be enough arguments because if there are not enough arguments, then
the result will be completely unpredictable. However, if by mistake you specify more number of
arguments, the excess arguments will simply be ignored. The prototype of the control string can
be given as below:
%[flags][width][.precision][modifier]type
flags is an optional argument, which specifies output justification like decimal point, numerical
sign, trailing zeros or octadecimal or hexadecimal prefixes. Table shows different types of
flags with their descriptions.
width is an optional argument which specifies the minimum number of positions that the output
characters will occupy. If the number of output characters is smaller than the specified width,
then the output would be right justified with blank spaces to the left. However, if the number of
characters is greater than the specified width, then all the characters would be printed.
precision is an optional argument which specifies the number of digits to print after the decimal
point or the number of characters to print from a string.
type is used to define the type and the interpretation of the value of the corresponding argument.
The type specifiers for printf function are given in Table 1.5.
For float x = 8900.768, the following examples show output under different format specifications:
The if block may include 1 statement or n statements enclosed within curly brackets. First
the test expression is evaluated. If the test expression is true, the statements of the if block are
executed, otherwise these statements will be skipped and the execution will jump to statement x.
The statement in an if block is any valid C language statement, and the test expression is any
valid C language expression that evaluates to either true or false. In addition to simple relational
expressions, we can also use compound expressions formed using logical operators. Note that
there is no semi-colon after the test expression. This is because the condition and statement should
be put together as a single statement.
if–else Statement
We have studied that using if statement plays a vital role in conditional branching. Its usage is
very simple. The test expression is evaluated, if the result is true, the statement(s) followed by the
expression is executed, else if the expression is false, the statement is skipped by the compiler.
What if you want a separate set of statements to be executed if the expression returns a false
value? In such cases, we can use an if–else statement rather than using a simple if statement.
The general form of simple if–else statement is shown
In the if–else construct, first the test expression is evaluated. If the expression is true, statement
block 1 is executed and statement block 2 is skipped. Otherwise, if the expression is false, statement
block 2 is executed and statement block 1 is ignored. In any case after the statement block 1 or
2 gets executed, the control will pass to statement x. Therefore, statement x is executed in every
case.
if–else–if Statement
C language supports if–else–if statements to test additional conditions apart from the initial test
expression. The if–else–if construct works in the same way as a normal if statement. Its construct
is given here.
Note that it is not necessary that every if statement should have an else block as C supports
simple if statements. After the first test expression or the first if branch, the programmer can
have as many else–if branches as he wants depending on the expressions that have to be tested.
switch–case Statement
A switch-case statement is a multi-way decision statement that is a simplified version of an if–
else–if block. The general form of a switch statement is shown
The power of nested if–else–if statements lies in the fact that it can evaluate more than one
expression in a single logical structure. switch statements are mostly used in two situations:
• When there is only one variable to evaluate in the expression
• When many conditions are being tested for
When there are many conditions to test, using the if and else–if constructs becomes complicated
and confusing. Therefore, switch case statements are often used as an alternative to long if
statements that compare a variable to several ‘integral’ values (integral values are those values
that can be expressed as an integer, such as the value of a char). Switch statements are also used
to handle the input given by the user.
We have already seen the syntax of the switch statement. The switch case statement compares
the value of the variable given in the switch statement with the value of each case statement that
follows. When the value of the switch and the case statement matches, the statement block of that
particular case is executed.
Did you notice the keyword default in the syntax of the switch case statement? Default is the
case that is executed when the value of the variable does not match with any of the values of the
case statements. That is, default case is executed when no match is found between the values of
switch and case statements and thus there are no statements to be executed. Although the default
case is optional, it is always recommended to include it as it handles any unexpected case.
In the syntax of the switch–case statement, we have used another keyword break. The break
statement must be used at the end of each case because if it is not used, then the case that matched
and all the following cases will be executed. For example, if the value of switch statement matched
with that of case 2, then all the statements in case 2 as well as the rest of the cases including default
will be executed. The break statement tells the compiler to jump out of the switch case statement
and execute the statement following the switch–case construct. Thus, the keyword break is used
to break out of the case statements.
Iterative statements:
Iterative statements are used to repeat the execution of a sequence of statements until the specified
expression becomes false. C supports three types of iterative statements also known as looping
statements. They are
• while loop
• do–while loop
• for loop
while loop
The while loop provides a mechanism to repeat one or more statements while a particular condition
is true. Figure shows the syntax and general form of a while loop.
Note that in the while loop, the condition is tested before any of the statements in the statement
block is executed. If the condition is true, only then the statements will be executed, otherwise if
the condition is false, the control will jump to statement y, that is the immediate statement outside
the while loop block.
do–while Loop
The do–while loop is similar to the while loop. The only difference is that in a do–while loop, the
test condition is tested at the end of the loop. As the test condition is evaluated at the end, this
means that the body of the loop gets executed at least one time (even if the condition is false).
Figure shows the syntax and the general form of a do–while loop.
Note that the test condition is enclosed in parentheses and followed by a semi-colon. The
statements in the statement block are enclosed within curly brackets. The curly brackets are
optional if there is only one statement in the body of the do–while loop.
The do–while loop continues to execute while the condition is true and when the condition
becomes false, the control jumps to the statement following the do–while loop.
The major disadvantage of using a do–while loop is that it always executes at least once, so even
if the user enters some invalid data, the loop will execute. However, do–while loops are widely
used to print a list of options for menu-driven programs.
for Loop
Like the while and do–while loops, the for loop provides a mechanism to repeat a task till a particular
condition is true. The synax and general form of a for loop is given in the figure.
When a for loop is used, the loop variable is initialized only once. With every iteration, the value of the loop
variable is updated and the condition is checked. If the condition is true, the statement block of the loop is
executed, else the statements comprising the statement block of the for loop are skipped and the control jumps to
the statement following the for-loop body.
In the syntax of the for loop, initialization of the loop variable allows the programmer to give it a value. Second,
the condition specifies that while the conditional expression is true, the loop should continue to repeat itself.
Every iteration of the loop must make the condition to exit the loop approachable. So, with every iteration, the
loop variable must be updated. Updating the loop variable may include incrementing the loop variable,
decrementing the loop variable or setting it to some other value like, i +=2, where i is the loop variable.
Note that every section of the for loop is separated from the other with a semi-colon.
It is possible that one of the sections may be empty, though the semi-colons still have to be there. However, if the
condition is empty, it is evaluated as true and the loop will repeat until something else stops it. The for loop is
widely used to execute a single or a group of statements for a limited number
of times.
break Statement
In C, the break statement is used to terminate the execution of the nearest enclosing loop in which
it appears. We have already seen its use in the switch statement. The break statement is widely used
with for, while, and do–while loops. When the compiler encounters a break statement, the control
passes to the statement that follows the loop in which the break statement appears. Its syntax is
quite simple, just type keyword break followed by a semi-colon.
break;
continue Statement
Like the break statement, the continue statement can only appear in the body of a loop. When the
compiler encounters a continue statement, then the rest of the statements in the loop are skipped
and the control is unconditionally transferred to the loop-continuation portion of the nearest
enclosing loop. Its syntax is quite simple, just type keyword continue followed by a semi-colon.
continue;
Goto statement:
The C goto statement is a jump statement which is sometimes also referred to as an unconditional
jump statement. The goto statement can be used to jump from anywhere to anywhere inside the block of program.
The syntax is,
Disadvantages of goto:
• The use of the goto statement is highly discouraged as it makes the program logic very complex.
• The use of goto makes tracing the flow of the program very difficult.
• The use of goto makes the task of analyzing and verifying the correctness of programs (particularly
those involving loops) very difficult.
• The use of goto can be simply avoided by using break and continue statements.