BPL C Programming 2024
BPL C Programming 2024
[email protected]
i
Table of Contents
Module-1
C Programming: decision making, control structures and arrays
C Structure, Data Types, Input-Output Statements, Decision making with if statement, simple if statement,
the if..else statement, nesting of if..else statements, the else.if ladder, the switch statement, the ?: operator,
the goto statement, the break statement, programming examples. The while statement, the do...while
statement, the for statement, nested loops, jumps in loops, the continue statement, programming
examples. One dimensional and two dimensional arrays, declaration and initialization of arrays, reading,
writing and manipulation of above types of arrays.
Module-2
Structures
Defining a structure, declaring structure variables, accessing structure members, structure initialization,
copying and comparing structure variables, operations on individual members, array of structures,
structures within structures, structures and functions, Unions, size of structures.
iii
Module-3
Pointers
Pointers in C, Declaring and accessing pointers in C, Pointer arithmetic, Functions , Call by value, Call by
reference, Pointer as function arguments, recursion, Passing arrays to functions, passing strings to functions,
Functions returning pointers, Pointers to functions, Programming Examples.
Module-4
Binary Systems and Combinational Logic
Digital Computers and Digital Systems, Binary Numbers, Number Base Conversion, Octal and Hexadecimal
Numbers, subtraction using r’s and r-1 complements, Binary Code, Binary Storage and Registers, Binary Logic,
Integrated Circuits, Digital Logic Gates
Module-5
Basic Structure of Computer Hardware and Software
Computer Types, Functional Units, Basic Operational Concepts, Bus structure, Software, Performance,
Multiprocessing and Multi computers, Machine Instruction: Memory Locations and Addresses, Memory
Operations, Instructions and Instruction Sequencing, Addressing Modes, Interrupts
iii
Chapter 1
Fundamental of C Programming
Language
and
Basic Input/Output Function
5
Chapter 1: Fundamental of C and Input/Output
6
History of C language
The base or father of programming languages is 'ALGOL.' It was first
introduced in 1960. 'ALGOL' was used on a large basis in European countries.
'ALGOL' introduced the concept of structured programming to the developer
community. In 1967, a new computer programming language was announced called
as 'BCPL' which stands for Basic Combined Programming Language.
BCPL was designed and developed by Martin Richards, especially for writing
system software. This was the era of programming languages.
Just after three years, in 1970 a new programming language called 'B' was
introduced by Ken Thompson that contained multiple features of 'BCPL.' This
programming language was created using UNIX operating system at AT&T and Bell
Laboratories. Both the 'BCPL' and 'B' were system programming languages.
What is C programming?
C is a general-purpose programming language that is extremely popular, simple and
flexible. It is machine-independent, structured programming language which is used
extensively in various applications.
C was the basic language to write everything from operating systems (Windows and
many others) to complex programs like the Oracle database, Git, Python interpreter
and more.
It is said that 'C' is a god's programming language. One can say, C is a base for the programming. If
you know 'C,' you can easily grasp the knowledge of the other programming languages that uses
the concept of 'C'
It is essential to have a background in computer memory mechanisms because it is an important
aspect when dealing with the C programming language.
In 1972, a great computer scientist Dennis
Ritchie created a new programming language
called 'C' at the Bell Laboratories. It was created
from 'ALGOL', 'BCPL' and 'B' programming
languages. 'C' programming language contains all
the features of these languages and many more
additional concepts that make it unique from
other languages.
History of C
How 'C' Works?
C is a compiled language. A compiler is a special tool that compiles the program
and converts it into the object file which is machine readable. After the compilation
process, the linker will combine different object files and creates a single executable file
to run the program. The following diagram shows the execution of a 'C' program
Nowadays, various compilers are available online, and you can use any of
those compilers. The functionality will never differ and most of the compilers will
provide the features required to execute both 'C' and 'C++' programs.
Summary
• 'C' was developed by Dennis Ritchie in 1972.
• It is a robust language.
• It is a low programming level language close to machine language
• It has the full support of various operating systems and hardware platforms.
• Many compilers are available for executing programs written in 'C'.
Preprocessor
Preprocessor program
Phase 2 : Disk
processes the
code.
Compiler creates
Phase 3 : Compiler Disk object code and
stores it on Disk.
13
C Development Environment cont
Primary
Memory
Phase 5 : Loader
Loader puts
Program in
: Memory
.
Primary
Memory
Phase 6 : C P U (execute) CPU takes each instruction
and executes it, storing
new data values as the
: program executes.
.
14
C Program Structure
An example of simple program in C
#include <stdio.h>
main(void)
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
}
15
Preprocessor directives
a C program line begins with # provides an instruction to
the C preprocessor, It is executed before the actual
compilation is done.
Two most common directives :
• #include
• #define
return 0;
} } } }
17
The curly braces { }
Identify a segment / body of a program
The start and end of a function
}
19
Statement cont…
Executable statements
Program lines that are converted to machine language
instructions and executed by the computer
20
C program skeleton
In short, the basic skeleton of a C program looks like
this:
statement(s);
} End of segment
21
Identifiers
Words used to represent certain program entities
(variables, function names, etc).
Example:
int my_name;
my_name is an identifier used as a program variable
22
Variables
Variable a name associated with a memory
cell whose value can change
23
Basic Data Types
There are 4 basic data types :
• int
• float
• double
• char
int
used to declare numeric program variables of integer type
whole numbers, positive and negative
keyword: int
int number;
number = 12;
24
Basic Data Types cont…
float
fractional parts, positive and negative keyword:
float
float height;
height = 1.72;
double
used to declare floating point variable of higher precision or
higher range of numbers exponential numbers, positive and
negative
keyword: double double valuebig;
valuebig = 12E-3;
25
Basic Data Types cont…
char
equivalent to ‘letters’ in English language Example of
characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
single character keyword:
char
char my_letter;
The declared character must be
my_letter = 'U'; enclosed within a single quote!
27
Constants cont…
Character constants
A character enclosed in a single quotation mark Example:
– const char letter = ‘n’;
– const char number = ‘1’;
– printf(“%c”, ‘S’);
» Output would be: S
Enumeration
Enumeration is a user defined datatype in C language. It is used to assign
names to the integral constants which makes a program easy to read and
maintain. The keyword “enum” is used to declare an enumeration.
syntax
enum enum_name{const1, const2, ....... };
enum week{sunday, monday, tuesday, wednesday, thursday, friday,
saturday};
enum week day; 28
Constant example – volume of a cone
#include <stdio.h>
void main(void)
{
const double pi = 3.412;
double height, radius, base, volume;
29
#define
You may also associate constant using #define preprocessor directive
#include <stdio.h>
#define pi 3.412
void main(void)
{
double height, radius, base, volume;
30
Input/Output Operations
When we say Input, it means to feed some data into a program. An input can
be given in the form of a file or from the command line.
C programming provides a set of built-in functions to read the given input
and feed it to the program as per requirement.
31
The Standard Files
C programming treats all the devices as files.
Standard File File Pointer Device
Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen
Input/Output Functions
A C function that performs an input or output operation
A few functions that are pre-defined in the header file stdio.h
such as :
printf()
scanf()
getchar() & putchar()
32
You must be wondering what is the purpose of %d inside
the scanf() or printf() functions. It is known as format string and this informs
the scanf() function, what type of input to expect and in printf() it is used to give a
heads up to the compiler, what type of output to expect.
34
The printf function cont…
Example:
printf(“Thank you”);
printf (“Total sum is: %d\n”, sum);
%d is a placeholder (conversion specifier)
– marks the display position for a type integer variable
\n is an escape sequence
– moves the cursor to the new line
35
Escape Sequence
Escape Sequence Effect
\a Beep sound
\b Backspace
\f Formfeed (for printing)
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\” “ sign
\o Octal decimal
\x Hexadecimal
\O NULL
36
Placeholder / Conversion Specifier
No Conversion Output Type Output Example
Specifier
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'
37
The scanf function
Read data from the standard input device (usually
keyboard) and store it in a variable.
General format:
scanf(“Format string”, &variable);
Notice ampersand (&) operator :
C address of operator
it passes the address of the variable instead of the
variable itself
tells the scanf() where to find the variable to store the
new value
38
The scanf function cont…
Example : int age;
printf(“Enter your age: “);
scanf(“%d”,&age);
Common Conversion Identifier used in
printf and scanf functions.
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s
39
The scanf function cont…
If you want the user to enter more than one value, you
serialise the inputs.
Example:
float height, weight;
printf(“Please enter your height and weight:”); scanf(“%f
%f”, &height, &weight);
40
getchar() & putchar() functions
The getchar() function reads a character from the terminal
and returns it as an integer. This function reads only single
character at a time. You can use this method in a loop in case
you want to read more than one character.
The putchar() function displays the character passed to it
on the screen and returns the same character. This function too
displays only a single character at a time. In case you want to
display more than one characters, use putchar() method in a
getchar() and putchar()
getchar() - read a character from standard input
putchar() - write a character to standard output
Example: #include <stdio.h> void
main(void)
{
char my_char;
printf(“Please type a character: ”);
my_char = getchar();
printf(“\nYou have typed this character: ”);
putchar(my_char);
}
42
getchar() and putchar() cont
Alternatively, you can write the previous code using
normal scanf and %c placeholder.
Example
#include <stdio.h>
void main(void)
{
char my_char;
printf(“Please type a character: ”);
scanf(“%c”,&my_char);
printf(“\nYou have typed this character: %c ”, my_char);
}
43
gets() & puts() functions
The gets() function reads a line from stdin(standard input)
into the buffer pointed to by str pointer, until either a
terminating newline or EOF (end of file) occurs.
is stored.
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space as
character too.
If you enter name as Study Tonight using scanf() it will only read and
store Study and will leave the part after space. But gets() function will
read it completely.
Few notes on C program…
C is case-sensitive
Word, word, WorD, WORD, WOrD, worD, etc are all different
variables / expressions
Eg. sum = 23 + 7
What is the value of Sum after this addition ?
46
Few notes on C program cont…
Reserved Words
Keywords that identify language entities such as
statements, data types, language attributes, etc.
Have special meaning to the compiler, cannot be used as
identifiers (variable, function name) in our program.
Should be typed in lowercase.
Example: const, double, int, main, void,printf, while, for,
else (etc..)
47
Few notes on C program cont…
Punctuators (separators)
Symbols used to separate different parts of the C
program.
These punctuators include:
[ ] ( ) { } , ; “: * #
Usage example:
void main (void)
{
int num = 10;
printf (“%d”,num);
}
48
Few notes on C program cont…
Operators
Tokens that result in some kind of computation or action
when applied to variables or other elements in an
expression.
Example of operators:
* + = - / Usage example:
result = total1 + total2;
49
Common Programming Errors
Debugging Process removing errors from a
program
Three (3) kinds of errors :
Syntax Error
a violation of the C grammar rules, detected during
program translation (compilation).
statement cannot be translated and program
cannot be executed
50
Common Programming Errors cont…
Run-time errors
• An attempt to perform an invalid operation, detected
during program execution.
• Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number
by zero.
• The computer will stop executing the program, and
displays a diagnostic message indicates the line where
the error was detected
51
Common Programming Errors cont…
Logic Error/Design Error
• An error caused by following an incorrect algorithm
53
C - Operator Types
What is Operator? Simple answer can be given using expression 4 + 5 is equal
to 9. Here 4 and 5 are called operands and + is called operator. C language
supports following type of operators.
Arithmetic Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Misc Operators
Lets have a look on all operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
&& Called Logical AND operator. If both the operands are non (A && B) is true.
zero then then condition becomes true.
Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
There are following Bitwise operators supported by C language
Operator Description Example
Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is 0000
&
exists in both operands. 1100
Binary OR Operator copies a bit if it exists in eather (A | B) will give 61 which is 0011
| operand. 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
^
operand but not both. 0001
Binary Ones Complement Operator is unary and has (~A ) will give -60 which is 1100
~ the efect of 'flipping' bits. 0011
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the A << 2 will give 240 which is 1111
0000
right operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the A >> 2 will give 15 which is 0000
1111
right operand.
Assignment Operators:
There are following assignment operators supported by C language:
Show Examples
Operator Description Example
Simple assignment operator, Assigns values from right side operands to C = A + B will assigne
=
left side operand value of A + B into C
Add AND assignment operator, It adds right operand to the left operand C += A is equivalent to C
+=
and assign the result to left operand =C+A
Subtract AND assignment operator, It subtracts right operand from the C -= A is equivalent to C
-=
left operand and assign the result to left operand =C-A
Multiply AND assignment operator, It multiplies right operand with the C *= A is equivalent to C
*=
left operand and assign the result to left operand =C*A
Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C
/=
operand and assign the result to left operand =C/A
Modulus AND assignment operator, It
= takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
• while loop
• for loop
• do while loop
1. while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
• Variable initialization.(e.g int x = 0;)
• condition(e.g while(x <= 10))
• Variable increment or decrement ( x++ or x-- or x = x + 2 )
Goto statement in C
C supports a unique form of a statement that is the goto Statement which is used to branch
unconditionally within a program from one point to another. Although it is not a good habit to use the
goto statement in C, there may be some situations where the use of the goto statement might be
desirable.
goto label;
A label is an identifier required for goto statement to a place where the branch is to be made. A label is a
valid variable name which is followed by a colon and is put immediately before the statement where the
if(age>=18)
goto g; //goto label g
else
goto s; //goto label s
getch();
}
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Runtime initialization of a two dimensional Array
String and Character Array