[go: up one dir, main page]

0% found this document useful (0 votes)
62 views51 pages

Tye Sem-5 P-2 Unit-2 Full

The document outlines the syllabus for a T.Y.B.Sc. Electronic Science course focusing on Microcontroller Architecture and C Programming. It covers the basics of C programming, including its history, features, compilation process, keywords, and identifiers. The document also provides instructions on installing a C compiler and writing a simple C program.

Uploaded by

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

Tye Sem-5 P-2 Unit-2 Full

The document outlines the syllabus for a T.Y.B.Sc. Electronic Science course focusing on Microcontroller Architecture and C Programming. It covers the basics of C programming, including its history, features, compilation process, keywords, and identifiers. The document also provides instructions on installing a C compiler and writing a simple C program.

Uploaded by

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

SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE

T.Y.B.Sc. ELECTRONIC SCIENCE 2021 PATTERN CBCS


Discipline Specific Elective Course: EL352
Paper II: Microcontroller Architecture and Programming
UNIT 2: Basics of C Programming
Topics to be covered: (12 lectures)
Types of Programming languages, Algorithm, flowcharts, instructions, syntax, hex files, linkers,
compilers, Basic data types, variables, Structure of C program, Operators in C, Array concept,
one, two-dimensional and multi-dimensional arrays, pointers, Input output statement, Decision
making statements, Control loops, Functions: Library functions and user defined functions.

What is C language?
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is known
as mother language.
It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the
programming languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are being used
in many languages like C++, Java, C#, etc.

2) C as a system programming language


A system programming language is used to create system software. C language is a system
programming language because it can be used to do low-level programming (for example driver
and kernel). It is generally used to create hardware devices, OS, drivers, kernels, etc. For example,
Linux kernel is written in C.
It can't be used for internet programming like Java, .Net, PHP, etc.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 1
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared before being
used.

4) C as a structured programming language


A structured programming language is a subset of the procedural language. Structure means to
break a program into parts or blocks so that it may be easy to understand.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both low-level and
high-level languages. C language program is converted into assembly code, it supports pointer
arithmetic (low-level), but it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent,
fast to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.

C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the C
program code.

File: main.c

#include <stdio.h>
int main ()
{
printf ("Hello C Programming\n");
return 0;
}

History of C Language
History of C language is interesting to know. Here we are going to discuss a brief
history of the c language.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.


NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 2
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features
of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee

Features of C Language

C is the widely used language. It provides many features that are given below.
1. Simple 6. Memory Management
2. Machine Independent or Portable 7. Fast Speed
3. Mid-level programming language 8. Pointers
4. Structured programming language 9. Recursion
5. Rich Library 10. Extensible

1) Simple

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 3
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with some machine
specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system applications
such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is
known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free () function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and
hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the pointers.
We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.

How to install C
There are many compilers available for c and C++. You need to download any one. Here, we are
going to use Turbo C++. It will work for both C and C++. To install the Turbo C software, you need
to follow following steps.

1. Download Turbo C++


2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
3. Double click on install.exe file
4. Click on the tc application file located inside c:\TC\BIN to write the c program

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 4
1) Download Turbo C++ software
You can download TURBO C++ from many sites.

2) Create turboc directory in c drive and extract the tc3.zip


Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in
c:\truboc directory.

3) Double click on the install.exe file and follow steps


Now, click on the install icon located inside the c:\turboc

First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first c
program.
To write the first C program, open the C console and write the following code:
#include <stdio.h>
int main ()
{
printf ("Hello C Language");
return 0;
}

#include <stdio.h> : It includes the standard input output library functions. The printf () function
is defined in stdio.h

int main(): The main() function is the entry point of every program in c language.
printf (): The printf() function is used to print data on the console.
return 0 : The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

How to compile and run the c program


There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.

By shortcut
Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.
Now press Esc to return to the Turbo C++ console.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 5
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the help
of the compiler. The compiler checks the source code for the syntactical or structural errors, and if
the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or machine
code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the source
code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the directive
and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into an
executable form:

1. Preprocessor 3. Assembler
2. Compiler 4. Linker
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 6
Preprocessor
The source code is the code which is
written in a text editor and the source code
file is given an extension ".c". This source
code is first passed to the preprocessor, and
then the preprocessor expands this code.
After expanding the code, the expanded
code is passed to the compiler.
Compiler
The code which is expanded by the
preprocessor is passed to the compiler. The
compiler converts this code into assembly
code. Or we can say that the C compiler
converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is
'.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the
object file would be 'hello.obj'.

Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The main
working of the linker is to combine the object code of library files with the object code of our
program. Sometimes the situation arises when our program refers to the functions defined in other
files; then linker plays a very important role in this. It links the object code of these files to our
program. Therefore, we conclude that the job of the linker is to link the object code of our program
with the object code of the library files and other files. The output of the linker is the executable file.
The name of the executable file is the same as the source file but differs only in their extensions. In
DOS, the extension of the executable file is '.exe', and in UNIX, the executable file can be named as
'a.out'. For example, if we are using printf () function in a program, then the linker adds its
associated code in an output file.
Let's understand through an example.
File name: hello.c
#include <stdio.h>
int main ()
{
printf ("Hello Friends!");
return 0;
}
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 7
Now, we will create a flow diagram of the above program:

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 8
In the above flow diagram, the following steps are taken to execute a program:

• Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts
the source code into expanded source code. The extension of the expanded source code would
be hello.i.
• The expanded source code is passed to the compiler, and the compiler converts this expanded
source code into assembly code. The extension of the assembly code would be hello.s.
• This assembly code is then sent to the assembler, which converts the assembly code into object
code.
• After the creation of an object code, the linker creates the executable file. The loader will then
load the executable file for the execution.

Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having their own importance, and
each keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so
they cannot be used as the variable names. If the keywords are used as the variable names, it means that we
are assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords
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

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays, structures, unions,
labels, etc. An identifier can be composed of letters such as uppercase, lowercase letters, underscore, digits,
but the starting letter should be either an alphabet or an underscore. If the identifier is not used in the external
linkage, then it is called as an internal identifier. If the identifier is used in the external linkage, then it is called
as an external identifier.
We can say that an identifier is a collection of alphanumeric characters that begins either with an alphabetical
character or an underscore, which are used to represent various programming elements such as variables,
functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters (uppercase and
lowercase), underscore character, and ten numerical digits (0-9) that represent the identifiers. There is a total
of 63 alphanumerical characters that represent the identifiers.
Rules for constructing C identifiers
o The first character of an identifier should be either an alphabet or an underscore, and then it can be
followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 9
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers
are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers:


total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

Identifier Reason of invalidity


2sum starts with a numerical digit
int reserved word
char reserved word
m+n special character, i.e., '+'
Types of identifiers
o Internal identifier
o External identifier

Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier. The internal
identifiers can be local variables.

External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The external identifiers
can be function names, global variables.
Differences between Keyword and Identifier
Keyword Identifier
Keyword is a pre-defined word. The identifier is a user-defined word
It must be written in a lowercase letter. It can be written in both lowercase and uppercase letters.
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It is a combination of alphabetical characters. It is a combination of alphanumeric characters.
It does not contain the underscore character. It can contain the underscore character.

Let's understand through an example.

int main ()
{
int a = 10;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 10
int A = 20;
printf ("Value of a is: %d", a);
printf ("\nValue of A is: %d", A);
return 0;
}

Output:
Value of a is: 10
Value of A is: 20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we conclude
that the identifiers are case sensitive.
Constants in C
A constant is a value that can't be changed in the program, for example: 10, 20, 'a', 3.4, "C programming" etc.
There are different types of constants in C programming.

List of Constants in C

Constant Example
Decimal Constant 10, 20, 450 etc.
Real or Floating-point Constant 10.3, 20.2, 450.6 etc.
Octal Constant 021, 033, 046 etc.
Hexadecimal Constant 0x2a, 0x7B, 0Xaa etc.
Character Constant 'a', 'b', 'x' etc.
String Constant "C", "C program", "Welcome to C" etc.

2 ways to define constant in C

There are two ways to define constant in C programming


1. const keyword
2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming as follows.
const float PI = 3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>

int main ()
{
const float PI = 3.14;
printf ("The value of PI is: %f", PI);
return 0;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 11
}

Output:
The value of PI is: 3.140000

If you try to change the value of PI, it will render compile time error.

#include<stdio.h>
int main ()
{
const float PI = 3.14;
PI = 4.5;
printf ("The value of PI is: %f", PI);
return 0;
}

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive
later.

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.

There are the following data types in C language.

Types Data Types

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 12
Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range


char 1 byte −128 to 127
signed char 1 byte −128 to 127
unsigned char 1 byte 0 to 255
short 2 byte −32,768 to 32,767
signed short 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 65,535
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte
double 8 byte
long double 10 byte

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and
it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:

type variable_list;

The example of declaring the variable is given below:


float b;
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 13
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a = 10, b = 20; //declaring 2 variable of integer type
float f = 20.8;
char c = 'A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:


int a;
int _ab;
int a30;

Invalid variable names:


int 2;
int a b;
int long;

Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.

void function1()
{
int x = 10; //local variable
}
You must have to initialize the local variable before it is used.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 14
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value = 20; //global variable

void function1()

int x = 10; //local variable


}

Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
void function1() {
int x = 10; //local variable
static int y = 10; //static variable
x = x+1;
y = y+1;
printf ("%d, %d", x, y);
}
If you call this function many times, the local variable will print the same value for each function
call, e.g. 11,11,11 and so on. But the static variable will print the incremented value in each function
call, e.g. 11, 12, 13 and so on.

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.

void main () {

int x = 10; //local variable (also automatic)

auto int y = 20; //automatic variable

External Variable
We can share a variable in multiple C source files by using an external variable. To declare an
external variable, you need to use extern keyword.

myfile.h

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 15
extern int x = 10; //external variable (also global)

program1.c

#include "myfile.h"

#include <stdio.h>

void printValue ()

printf ("Global variable: %d", global_variable);

printf() and scanf() functions in C


The printf () and scanf () functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

printf () function
The printf () function is used for output. It prints the given statement to the console.
The syntax of printf () function is given below:

printf ("format string", argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf () function
The scanf () function is used for input. It reads the input data from the console.

scanf ("format string", argument_list);

Program to print cube of given number


Let's see a simple example of c language that gets input from the user and prints the cube of the
given number.

#include<stdio.h>

int main ()

int number;

printf ("Enter a number: ");

scanf ("%d", &number);

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 16
printf ("Cube of number is: %d ", number*number*number);

return 0;

Output
Enter a number: 5
Cube of number is: 125

The scanf ("%d", &number) statement reads integer number from the console and stores the given
value in number variable.

The printf ("Cube of number is: %d ", number*number*number) statement prints the cube of
number on the console.

Program to print sum of 2 numbers


Let's see a simple example of input and output in C language that prints addition of 2 numbers.

#include<stdio.h>
int main ()
{
int x = 0, y = 0, result = 0;
printf ("Enter first number: ");
scanf ("%d", &x);
printf ("Enter second number: ");
scanf ("%d", &y);
result = x+y;
printf ("Sum of 2 numbers: %d ", result);
return 0;
}
Output
Enter first number: 9
Enter second number: 9
Sum of 2 numbers: 18

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase, lowercase
letters, underscore, digits, but the starting letter should be either an alphabet or an underscore. If

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 17
the identifier is not used in the external linkage, then it is called as an internal identifier. If the
identifier is used in the external linkage, then it is called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with an
alphabetical character or an underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical
characters (uppercase and lowercase), underscore character, and ten numerical digits (0-9) that
represent the identifiers. There is a total of 63 alphanumerical characters that represent the
identifiers.

Rules for constructing C identifiers


o The first character of an identifier should be either an alphabet or an underscore, and then it
can be
Identifier Remark Reason of invalidity
followed
2sum Invalid Starts with a numerical digit
by any of the
int Invalid Reserved word
character,
char Invalid Reserved word
digit, or
m+n Invalid Use of special character, i.e., '+'
underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Examples of valid identifiers:
total, sum, average, _m _, sum_1, etc.
Examples of invalid identifiers:
1_no, int, price-list, item#2

Types of Identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier. The
internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The external
identifiers can be function names, global variables.
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 18
Differences between Keyword and Identifier
Keyword Identifier
Keyword is a pre-defined word. The identifier is a user-defined word
It can be written in both lowercase and uppercase
It must be written in a lowercase letter.
letters.
Its meaning is pre-defined in the C
Its meaning is not defined in the c compiler.
compiler.
It is a combination of alphabetical
It is a combination of alphanumeric characters.
characters.
It does not contain the underscore
It can contain the underscore character.
character.
Let's understand through an example.

int main ()
{
int a = 10;
int A = 20;
printf ("Value of a is: %d", a);
printf ("\nValue of A is: %d", A);
return 0;
}
Output:
Value of a is: 10
Value of A is: 20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we
conclude that the identifiers are case sensitive.
Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in the C language.

1. Single Line Comments


2. Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of a single line
comment in C.

#include<stdio.h>

int main () {

//printing information
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 19
printf ("Hello Friend!");

return 0;

Output:
Hello Friend!
Even you can place the comment after the statement.

For example:

printf ("Hello Friend!"); //printing information

Multi-Line Comments
Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code,
but it can't be nested.
Syntax:
/*
code
to be commented
*/
Let's see an example of a multi-Line comment in C.

#include<stdio.h>
int main () {
/*printing information
Multi-Line Comment*/
printf ("Hello Friend!");
return 0;
}

Output:
Hello Friend!

C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format string
determines the format of the input and output. The format string always starts with a '%' character.

The commonly used format specifiers in printf () function are:

Format
Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that the
variable can hold both positive and negative values.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 20
It is used to print the unsigned integer value where the unsigned integer means that
%u
the variable can hold only positive value.
It is used to print the octal unsigned integer where octal integer value always starts
%o
with a 0 value.
It is used to print the hexadecimal unsigned integer where the hexadecimal integer
%x value always starts with a 0x value. In this, alphabetical characters are printed in
small letters such as a, b, c, etc.
It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
%X
characters in uppercase such as A, B, C, etc.
It is used for printing the decimal floating-point values. By default, it prints the 6
%f
values after '.'.
%e or %E It is used for scientific notation. It is also known as Mantissa or Exponent.
It is used to print the decimal floating-point values, and it uses the fixed precision,
%g i.e., the value after the decimal in input would be exactly the same as the value in the
output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.
Let's understand the format specifiers in detail through an example.
Use of %d
int main ()
{
int b = 6;
int c = 8;
printf ("Value of b is: %d”, b);
printf ("\nValue of c is: %d", c);
return 0;
}
In the above code, we are printing the integer value of b and c by using the %d specifier.
Output:
Value of b is: 6
Value of c is: 8

Use of %u

int main ()
{
int b = 10;
int c = -10;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 21
printf ("Value of b is: %u", b);
printf ("\nValue of c is: %u", c);
return 0;
}
Output:
Value of b is: 10
Value of c is: -4294967286
In the above program, we are displaying the value of b and c by using an unsigned format specifier,
i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it does not print
the value of c as c contains the negative value.

Use of %o

int main ()

int a = 0100;

printf ("Octal value of a is: %o", a);

printf ("\nInteger value of a is: %d", a);

return 0;

In the above code, we are displaying the octal value and integer value of a.

Output:
Octal value of a is: 100
Integer value of a is: 64

Use of %x and %X

int main ()

int y = 0xA;

printf ("Hexadecimal value of y is: %x", y);

printf ("\nHexadecimal value of y is: %X", y);

printf ("\nInteger value of y is: %d", y);

return 0;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 22
In the above code, y contains the hexadecimal value 'A'. We display the hexadecimal value of y in
two formats. We use %x and %X to print the hexadecimal value where %x displays the value in
small letters, i.e., 'a' and %X displays the value in a capital letter, i.e., 'A'.

Output:

Hexadecimal value of y is: a


Hexadecimal value of y is: A
Integer value of y is: 10
Use of %f

int main ()

float y = 3.4;

printf ("Floating point value of y is: %f", y);

return 0;

The above code prints the floating value of y.

Output:
Floating point value of y is: 3.400000

Use of %e

int main ()

float y = 3.45;

printf ("Exponential value of y is: %e", y);

return 0;

Output:
Exponential value of y is: 3.450000e+00

Use of %E

int main ()

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 23
{

float y = 3.45;

printf ("Exponential value of y is: %E", y);

return 0;

Output:
Exponential value of y is: 3.450000E+00

o %g

int main ()
{
float y = 3.8;
printf ("Float value of y is: %g", y);
return 0;
}

In the above code, we are displaying the floating value of y by using %g specifier. The %g specifier displays
the output same as the input with a same precision.

Output
Float value of y is: 3.8

o %p

int main ()
{
int y = 5;
printf ("Address value of y in hexadecimal form is: %p", &y);
return 0;
}

Output

Address value of y in hexadecimal form is: 0x7ffeb01a53ec

o %c

int main()
{
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 24
char a = 'c';
printf ("Value of a is: %c", a);
return 0;
}

Output:

Value of a is: c

o %s

int main()
{
printf ("%s", "MSG College");
return 0;
}
Output:
MSG College
Minimum Field Width Specifier
Suppose we want to display an output that occupies a minimum number of spaces on the screen. You can
achieve this by displaying an integer number after the percent sign of the format specifier.
int main ()
{
int x = 900;
printf ("%8d", x);
printf ("\n%-8d", x);
return 0;
}

In the above program, %8d specifier displays the value after 8 spaces while %-8d specifier will make a value
left-aligned.

Output:

9 0 0

9 0 0

Now we will see how to fill the empty spaces. It is shown in the below code:

int main ()
{
int x = 12;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 25
printf ("%08d", x);
return 0;
}
In the above program, %08d means that the empty space is filled with zeroes.
Output:
0 0 0 0 0 0 1 2

Specifying Precision
We can specify the precision by using '.' (Dot) operator which is followed by integer and format specifier.
int main ()
{
float x = 12.2;
printf ("%.2f", x);
return 0;
}

Output:

1 2 . 2 0

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside
string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents new line.
List of Escape Sequences in C
Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\nnn octal number
\xhh hexadecimal number
\0 Null

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 26
Escape Sequence Example
#include<stdio.h>
int main ()
{
int number = 50;
printf ("You\nare\nlearning\n\'c\' language\n\"Do you know C language? \"");
return 0;
}

Output:
You
are
learning
'c' language
"Do you know C language?”

C Operators
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform
addition. C has a wide range of operators to perform various operations. There can be many types of operations
like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Shift Operators
o Increment and Decrement Operators
o Ternary or Conditional Operators
o Assignment Operator
o Miscellaneous Operators

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The associativity
specifies the operator direction to be evaluated; it may be left to right or right to left.
Let's understand the precedence by the example given below:

int y = 10 + 20*10;

The variable y will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

The precedence and associativity of C operators is given below:

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 27
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Arithmetic Operators in C
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constants and variables).
Arithmetic Operator Meaning of Operator
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division (modulo division)

Example: Arithmetic Operators


// Working of arithmetic operators
#include <stdio.h>
int main () {
int a = 9, b = 4, c;
c = a+b;
printf("a + b = %d \n", c);
c = a-b;
printf("a - b = %d \n", c);
c = a*b;
printf("a * b = %d \n", c);
c = a/b;
printf("a / b = %d \n", c);
c = a%b;
printf("Remainder when a divided by b = %d \n", c);
return 0;}

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 28
Output:

a + b = 13
a - b = 5
a * b = 36
a / b = 2
Remainder when a divided by b = 1

The operators +, - and * compute addition, subtraction, and multiplication respectively as you might have
expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the C program.
It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler
neglects the term after the decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1.
The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

// When either one of the operands is a floating-point number


a/b = 2.5
a/d = 2.5
c/b = 2.5
// When both operands are integers
c/d = 2

Relational Operators in C
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.
Relational operators are used in decision making and loops.
Relational Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0

Example: Relational Operators


// Working of relational operators
#include <stdio.h>
int main(){
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 29
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;}
Output:

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

Logical Operators in C
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.
Logical Operator Meaning 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 0.
operand is 0
Example: Logical Operators
// Working of logical operators

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

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 30
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);
return 0;
}

Output:

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

Explanation of logical operator program


• (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
• (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
• (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
• (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
• !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
• !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

Bitwise Operators in C
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are
converted to bit-level which makes processing faster and saves power. Bitwise operators are used in C
programming to perform bit-level operations.
We have different types of bitwise operators in the C programming language. The following is the list of the
bitwise operators:

Bitwise Operator Meaning of operator


& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
~ One's complement operator (unary operator)
<< Left shift operator
>> Right shift operator

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 31
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we
perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either
0 or 1. It is mainly used in numerical computations to make the calculations faster.
Let's look at the truth table of the bitwise operators.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1

Bitwise AND operator


Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both
sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise
AND operation is 1; otherwise, the output would be 0.
For example,
We have two variables a and b.
a = 6;
b = 4;
The binary representation of the above two variables are given below:
a = 0110
b = 0100
When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output would be:
Result = 0100
As we can observe from the above result that bits of both the variables are compared one by one. If the bit of
both the variables is 1 then the output would be 1, otherwise 0.
Let's understand the bitwise AND operator through the program.
#include <stdio.h>
int main ()
{
int a = 6, b = 14; // variable declarations
printf ("The output of the Bitwise AND operator a&b is: %d", a&b);
return 0;
}

In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b' are 6 and 14
respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively. When we apply the AND operator
between these two variables,

a AND b = 0110 && 1110 = 0110

Output:
The output of the Bitwise AND operator a&b is: 6

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 32
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both
sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.
For example,
We consider two variables,
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output would be:
Result = 0001 1111
As we can observe from the above result that the bits of both the operands are compared one by one; if the
value of either bit is 1, then the output would be 1 otherwise 0.
Let's understand the bitwise OR operator through a program.

#include <stdio.h>
int main ()
{
int a = 23, b = 10; // variable declarations
printf ("The output of the Bitwise OR operator a|b is: %d", a|b);
return 0;
}

Output:
The output of the Bitwise OR operator a|b is: 31

Bitwise Exclusive OR operator

Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the
exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 0; otherwise
1.
For example,
We consider two variables a and b,
a = 12;
b = 10;
The binary representation of the above two variables would be:
a = 0000 1100
b = 0000 1010
When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the result would be:
Result = 0000 0110
As we can observe from the above result that the bits of both the operands are compared one by one; if the
corresponding bit value of any of the operand is 1, then the output would be 0; otherwise 1.
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 33
Let's understand the bitwise exclusive OR operator through a program.
#include <stdio.h>
int main ()
{
int a = 12, b = 10; // variable declarations
printf ("The output of the Bitwise exclusive OR operator a^b is: %d", a^b);
return 0;
}

Output:

The output of the Bitwise exclusive OR operator a^b is: 6

Bitwise complement operator


The bitwise complement operator is also known as one's complement operator. It is represented by the symbol
tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we
apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.

For example,

If we have a variable named 'a',


a = 8;
The binary representation of the above variable is given below:
a = 1000
When we apply the bitwise complement operator to the operand, then the output would be:

Result = 0111
As we can observe from the above result that if the bit is 1, then it gets changed to 0 else 1.
Let's understand the complement operator through a program.

#include <stdio.h>
int main ()
{
int a = 8; // variable declarations
printf ("The output of the Bitwise complement operator ~a is: %d", ~a);
return 0;
}

Output:

The output of the Bitwise complement operator ~a is: 7

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 34
Bitwise Shift Operators
Two types of bitwise shift operators exist in C programming. The bitwise shift operators will shift the bits
either on the left-side or right-side. Therefore, we can say that the bitwise shift operator is divided into two
categories:

o Left-shift operator
o Right-shift operator

Left-shift operator
It is an operator that shifts the number of bits to the left-side.
Syntax of the left-shift operator is given below:

Operand << n;

Where, Operand is an integer expression on which we apply the left-shift operation and n is the number of
bits to be shifted.
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the left side will be
popped out, and 'n' bits on the right-side are filled with 0.
For example,
Suppose we have a statement:
int a = 5;
The binary representation of 'a' is given below:
a = 0101
If we want to left-shift the above representation by 2, then the statement would be:
a << 2;
0101<<2 = 00010100

Let's understand through a program.

#include <stdio.h>
int main ()
{
int a = 5; // variable initialization
printf ("The value of a<<2 is: %d ", a<<2);
return 0;
}
Output:
The value of a<<2 is: 20

Right-shift operator
It is an operator that shifts the number of bits to the right side.
Syntax of the right-shift operator is given below:

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 35
Operand >> n;

Where, Operand is an integer expression on which we apply the right-shift operation and n is the number
of bits to be shifted right.

In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on the right-side
will be popped out, and 'n' bits on the left-side are filled with 0.

For example,
Suppose we have a statement,
int a = 7;
The binary representation of the above variable would be:
a = 0111
If we want to right-shift the above representation by 2, then the statement would be:
a>>2;
0000 0111 >> 2 = 0000 0001

Let's understand through a program.

#include <stdio.h>
int main ()
{
int a = 7; // variable initialization
printf ("The value of a>>2 is: %d ", a>>2);
return 0;
}
Output:
The value of a>>2 is: 1

Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change the value of an operand (constant
or variable) by 1.
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.

Example: Increment and Decrement Operators


// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 36
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}

Output:

++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes
like a++ and a--.

Ternary or Conditional Operator in C


The conditional operator is also known as a ternary operator. The conditional statements are the decision-
making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?'
and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behaviour of the conditional operator is similar to the ‘if-else’ statement as 'if-else' statement is also a
decision-making statement.
Syntax of a conditional operator:
Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:

Meaning of the above syntax.


o In the above syntax, the expression1 is a Boolean condition that can be either true or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 37
Let's understand the ternary or conditional operator through an example.
#include <stdio.h>
int main ()
{
int age; // variable declaration
printf ("Enter your age: ");
scanf ("%d", &age); // taking user input for age variable
(age>=18)? (printf ("Eligible for voting")) : (printf ("Not eligible for voting")); // conditional operator
return 0;
}

In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition
by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is
greater than or equal to 18, then the statement1 will execute, i.e., (printf ("Eligible for voting")) otherwise,
statement2 will execute, i.e., (printf ("Not eligible for voting")).

Let's observe the output of the above program.


If we provide the age of user below 18, then the output would be:
Output:
Enter your age: 15
Not eligible for voting

If we provide the age of user above 18, then the output would be:

Enter your age: 36


Eligible for voting
As we can observe from the above two outputs that if the condition is true, then the statement1 is executed;
otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and based on condition, it
executes the statements. Now, we will see how a conditional operator is used to assign the value to a variable.
Let's understand this scenario through an example.

#include <stdio.h>
int main()
{
int a = 5, b; // variable declaration
b = ((a == 5)?(3):(2)); // conditional operator
printf ("The value of 'b' variable is: %d", b);
return 0;
}

In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a' variable. After
the declaration, we are assigning value to the 'b' variable by using the conditional operator. If the value of 'a'
is equal to 5 then 'b' is assigned with a 3 value; otherwise with a 2 value.
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 38
Output:
The value of 'b' variable is: 3

The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is equal to 5. As we
know that the behaviour of conditional operator and 'if-else' is similar but they have some differences. Let's
look at their differences.
o A conditional operator is a single programming statement, while the 'if-else' statement is a
programming block in which statements come under the parenthesis.
o A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else'
statement cannot be used for the assignment purpose.
o It is not useful for executing the statements when the statements are multiple, whereas the 'if-else'
statement proves more suitable when executing multiple statements.
o The nested ternary operator is more complex and cannot be easily debugged, while the nested 'if-else'
statement is easy to read and maintain.

Assignment Operator in C
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =. There are some short-hand assignment operators also as listed in the table below:
Short-hand Assignment Operator Example Same as
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b

Example: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main() {
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 39
}

Output:

c = 5
c = 10
c = 5
c = 25
c = 5
c = 0

Miscellaneous Operators in C
Comma Operator
Comma operators are used to link related expressions together.
For example:

int a, c = 5, d;

sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
Example: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n", sizeof(a));
printf("Size of float=%lu bytes\n", sizeof(b));
printf("Size of double=%lu bytes\n", sizeof(c));
printf("Size of char=%lu byte\n", sizeof(d));
return 0;
}

Output:

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

& Operator: It returns the address of a memory location of a variable.


For example,
&a; returns the actual address of the variable.
It can be any address in the memory like 4, 70,104 etc.

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 40
* Operator: It represents a pointer to a variable.
For example,
*a; points to the value of the variable a.

Control Statements in C (Decision Making Statements)


There are the following variants of if statement in C language.
o Simple if statement
o if-else statement
o if-else-if ladder
o Nested if

Simple if Statement
The if statement is used to check some given condition and perform some operations depending upon the
correctness of that condition. It is mostly used in the scenario where we need to perform the different
operations for the different conditions. The syntax of the if statement is given below.

if(expression)
{
//code to be executed
}

Let's see a simple example of C language if statement. Flowchart of simple if statement in C

#include<stdio.h>
int main()
{
int number = 0;
printf ("Enter a number: ");
scanf ("%d", &number);
if(number%2==0)
{
printf ("%d is even number", number);
}
return 0;
}

Output1:
Enter a number: 6
6 is even number
Output2:
Enter a number: 7
Program to find the largest number out of three.
#include <stdio.h>
int main()

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 41
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a>b && a>c)
{
printf("%d is the largest", a);
}
if(b>a && b > c)
{
printf("%d is the largest", b);
}
if(c>a && c>b)
{
printf("%d is the largest", c);
}
if(a == b && a == c)
{
printf("All are equal");
}
}

Output:
Enter three numbers: 23 65 18
65 is the largest

if-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is an
extension to the if statement using which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that
if and else block cannot be executed simultaneously. Using if-else statement is always preferable since it
always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}

Flowchart of the if-else statement in C


NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 42
Let's see the simple example to check whether a number is even or odd using if-else statement in C language.
#include<stdio.h>
int main()
{
int num = 0;
printf("Enter a number: ");
scanf("%d", &num);
if(num%2==0)
{
printf("%d is an even number", num);
}
else
{
printf("%d is an odd number", num);
}
return 0;
}
Output:
Enter a number: 6
6 is an even number
Enter a number: 3
3 is an odd number
Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 43
int age;
printf("Enter your age: ");
scanf("%d", &age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}

Output:

Enter your age: 20


You are eligible to vote...
Enter your age: 15
Sorry ... you can't vote
if else-if ladder Statement
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there
are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true
then the statements defined in the if block will be executed, otherwise if some other condition is true then the
statements defined in the else-if block will be executed, at the last if none of the condition is true then the
statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar
to the switch case statement where the default is executed instead of else block if none of the cases is matched.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 44
Flowchart of else-if ladder statement in C:

The example of an if-else-if statement in C language is given below.

#include<stdio.h>
int main()
{
int num = 0;
printf("Enter a number: ");
scanf("%d", &num);
if(num==10)
{
printf("number is equal to 10");
}
else if(num==50)
{
printf("number is equal to 50");
}
else if(num==100)
{
printf("number is equal to 100");
}
else
{
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 45
printf("number is not equal to 10, 50 or 100");
}
return 0;
}

Output:
Enter a number: 4
number is not equal to 10, 50 or 100
Enter a number: 100
number is equal to 100

Program to calculate the grade of the student according to the specified


marks.
#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 46
Output:
Enter your marks: 58
You scored grade B…
Enter your marks: 85
You scored grade B+…

switch statement in C
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple
operations for the different possible values of a single variable called switch variable. Here, we can define
various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:

switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional
…........

default: //code to be executed if all cases are not matched with switch expression
}

Rules for switch statement in C language


1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the
case, all the cases will be executed present after the matched case. It is known as fall through the state of C
switch statement.

Let's try to understand the fall through state of switch statement by the example given below.

#include<stdio.h>
int main()
{
int number=0;
printf("Enter a number:");
scanf("%d", &number);
switch(number)
{

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 47
case 10:
printf("Number is equal to 10\n");
case 50:
printf("Number is equal to 50\n");
case 100:
printf("Number is equal to 100\n");
default:
printf("Number is not equal to 10, 50 or 100");
}
return 0;
}

Output1:
Enter a number:10
Number is equal to 10
Number is equal to 50
Number is equal to 100
Number is not equal to 10, 50 or 100

Output2:
Enter a number:50
Number is equal to 50
Number is equal to 100
Number is not equal to 10, 50 or 100

Looping statements in C
The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
There are three types of loops used in the C language.

Why use loops in C language?


The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program
so that instead of writing the same code again and again, we can repeat the same code for a finite number of
times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement
10 times, we can print inside a loop which runs up to 10 iterations.

Advantages of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of Loops in C
There are three types of loops in C language that is given below:
1. do while
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 48
2. while
3. for
do…while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts
of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least
once. The do-while loop is mostly used in menu-driven programs where the termination condition depends
upon the end user. Flowchart of do…while loop
Syntax:

do
{
//code to be executed
} while (condition);

Example:
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice, dummy;
do
{
printf("\n1. Print Hello\n2. Print Electronics\n3. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Hello");
break;
case 2:
printf("Electronics");
break;
case 3:
exit(0);
break;
default:
printf("Please enter valid choice");
}
printf("Do you want to enter more?…");
scanf("%c", &c);
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 49
} while (c == 'y');
}

Output
1. Print Hello
2. Print Electronics
3. Exit
1
Hello
Do you want to enter more?...
y
1. Print Hello
2. Print Electronics
3. Exit
2
Electronics
Do you want to enter more?...
p

while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed
multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The
while loop is mostly used in the case where the number of iterations is not known in advance.

Syntax: Flowchart of while loop in C

while (condition)
{
//code to be executed
}

Example:

Let's see the simple program of while loop that prints


numbers from 1 to 10.

#include<stdio.h>
int main()
{
int num = 1;
while(i<=10)
{
printf("%d \n", num);
num++;
}
return 0;
NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 50
}

Output:
1
2
3
4
5
6
7
8
9
10

to be continued………

NOTES ON TYBSC ELECTRONIC SCIENCE (2020 PATTERN) SEM-5 PAPER-2 UNIT-2: BASICS OF C PROGRAMMING. NOTES PREPARED BY
DR. D. K. HALWAR, MSG COLLEGE MALEGAON CAMP DIST- NASHIK-423105. 51

You might also like