FINAL UNIT 1 Notes
FINAL UNIT 1 Notes
• Computer system,
• components of a computer system,
• computing environments,
• computer languages, creating and running programs,
• Preprocessor, Compilation process, role of linker, idea of invocation and execution
of a programme.
• Algorithms: Representation using flowcharts, pseudocode.
1. Input unit
3. Output unit
Input Unit
These components help users enter data and commands into a computer system. Data can be
in the form of numbers, words, actions, commands, etc. The main function of input devices is
to direct commands and data into computers. Computers then use their CPU to process this
data and produce output.
For example, a laptop’s keyboard is an input unit that enters numbers and characters. Similarly,
even a mouse can be an input unit for entering directions and commands. Other examples
include barcode readers, Magnetic Ink Character Readers (MICR), Optical Character Readers
(OCR), etc.
Another example of input devices is touch-screens. Users can simply touch these screens
without using any other device to enter commands. From smartphones to ATM machines, these
input devices are becoming very popular these days.
After receiving data and commands from users, a computer system now has to process it according
to the instructions provided. Here, it has to rely on a component called the central
processing unit. The CPU further uses these three elements:
a) Memory Unit
Once a user enters data using input devices, the computer system stores this data in its
memory unit. This data will now remain here until other components of CPU process it.
The memory unit uses a set of pre-programmed instructions to further transmit this data
to other parts of the CPU.
b) Arithmetic and Logic Unit
This part of the CPU performs arithmetic operations. It does basic mathematical
calculations like addition, subtraction, division, multiplication, etc. Further, it can even
perform logical functions like the comparison of data.
c) Control Unit
This unit is the backbone of computers. It is responsible for coordinating tasks between
all components of a computer system. The control unit collects data from input units and
sends it to processing units depending on its nature. Finally, it also further transmits
processed data to output units for users.
Output Unit
The third and final component of a computer system is the output unit. After processing of data,
it is converted into a format which humans can understand. After conversion, the output units
displays this data to users. Examples of output devices include monitors, screens, printers and
speakers. Thus, output units basically reproduce the data formatted by the computer for users’
benefit.
//*Units of Memory
A computer system uses binary numbers to store and process data. The binary digits 0 and 1,
which are the basic units of memory, are called bits. Further, these bits are grouped together to
form words. A 4-bit word is called a Nibble. Examples of nibble are 1001, 1010, 0010, etc. A
two nibble word, i.e., 8-bit word is called a byte, for example, 01000110, 01111100, 10000001,
etc.
Like any other standard unit, bytes are grouped together to make bigger chunks or units of
memory. Table 1.1 shows different measurement units for digital data stored in storage devices.
Computer
Table 1.1 Measurement units for digital data
KB (Kilobyte) MB (Megabyte) GB (Gigabyte) TB (Terabyte)
Description
1 KB = 1024 Bytes
1 MB = 1024 KB
1 GB = 1024 MB
1 TB = 1024 GB
Unit
PB (Petabyte)
EB (Exabyte)
ZB (Zettabyte)
YB (Yottabyte)
Description
1 PB = 1024 TB
1 EB = 1024 PB
1 ZB = 1024 EB
1 YB = 1024 ZB //*
Computing Environment
In the world of technology where every tasks are performed with help of computers, these
computers have become one part of human life. Computing is nothing but process of
completing a task by using this computer technology and it may involve computer hardware
and/or software. But computing uses some form of computer system to manage, process, and
communicate information.
When a problem is solved by the computer, during that computer uses many devices,
arranged in different ways and which work together to solve problems. This constitutes a
computing environment where various number of computer devices arranged in different
ways to solve different types of problems in different ways. In different computing
environments computer devices are arranged in different ways and they exchange
information in between them to process and solve problem. One computing environment
consists of many computers other computational devices, software and networks that to
support processing and sharing information and solving task.
Based on the organization of different computer devices and communication processes there
exists multiple types of computing environments. Now lets know about different types of
computing environments.
Types of Computing Environments :
Every computer works only on 0s and 1s, i.e., binary number system and can understand only
its own machine language which is its “natural language” defined by its hardware design.
Therefore , in machine language programming programmers have to instruct computers using
different combinations of 0s and 1s.
• Programs written in machine language can be executed very fast by the computer. This
is mainly because machine instructions are directly understood by the CPU and no
translation of the program is required.
• Efficient use of primary memory
Disadvantages of Machine Language:
• Machine dependent
• Difficult to program
• Difficult to modify
• Error prone
Assembly Language
• Long programs written in such languages cannot be executed on small sized computers.
• It takes lot of time to code or write the program, as it is more complex in nature.
• Difficult to remember the syntax
• Lack of portability of program between computers of different makes.
Despite the advent of assembly language, programmers still had to use many instructions to
accomplish even the simplest task . Thus to speed up the programming process, high level
languages were developed in which single statements could be written to perform substantial
tasks. High level language programming allowed the programmers to write instruction that
look almost like everyday English and contain commonly used mathematical notations.
Advantages of high level language
• High level languages are programmer friendly. They are easy to write , debug and
maintain.
• It provides higher level of abstraction from machine languages.
• It is machine independent language.
• Easy to learn
• Less error prone, easy to find and debug errors.
• Higher level programming results in better programming productivity.
Disadvantages of high level language
Compilation process in c
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 pre-processor takes the source code as an input, and it removes all the comments from the
source code. The pre-processor takes the pre-processor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the pre-processor 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:
• Pre-processor
• Compiler
• Assembler
• Linker
Pre-processor
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 pre-processor, and then the pre-
processor expands this code. After expanding the code, the expanded code is passed to the
compiler.
Compiler
The code which is expanded by the pre-processor 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.
hello.c
#include <stdio.h>
int main()
{
printf("Hello ABC");
return 0;
}
The algorithm and flowchart are two types of tools to explain the process of a program. In this
page, we discuss the differences between an algorithm and a flowchart and how to create a
flowchart to illustrate the algorithm visually.
Algorithms and flowcharts are two different tools that are helpful for creating new programs,
especially in computer programming. An algorithm is a step-by-step analysis of the process,
while a flowchart explains the steps of a program in a graphical way.
Writing a logical step-by-step method to solve the problem is called the algorithm. In other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or
computer problem, this is the first step in the process.
Input / Output
Process / Instruction
Decision
Connector / Arrow
The symbols above represent different parts of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colors. In a flowchart, we can
easily highlight certain elements and the relationships between each part.
Algorithm Flowchart
It is a procedure for solving problems. It is a graphic representation of a process.
The process is shown in step-by-step The process is shown in block-by-block information
instruction. diagram.
It is complex and difficult to understand. It is intuitive and easy to understand.
It is convenient to debug errors. It is hard to debug errors.
The solution is showcased in natural
The solution is showcased in pictorial format.
language.
It is somewhat easier to solve complex
It is hard to solve complex problem.
problem.
It costs more time to create an algorithm. It costs less time to create a flowchart.
It is not surprising that algorithms are widely used in computer programming. However, it can
be applied to solving mathematical problems and even in everyday life. Here comes a question:
how many types of algorithms? According to Dr. Christoph Koutschan, a computer scientist
working at the Research Institute for Symbolic Computation (RISC) in Austria, he has
surveyed voting for the important types of algorithms. As a result, he has listed 32 crucial
algorithms in computer science. Despite the complexity of algorithms, we can generally divide
algorithms into six fundamental types based on their function.
1. Recursive Algorithm
It refers to a way to solve problems by repeatedly breaking down the problem into sub-
problems of the same kind. The classic example of using a recursive algorithm to solve
problems is the Tower of Hanoi.
Traditionally, the divide and conquer algorithm consists of two parts: 1. breaking down a
problem into some smaller independent sub-problems of the same type; 2. finding the final
solution of the original issues after solving these more minor problems separately.
• If you can find the repeated sub-problems and the loop substructure of the original
problem, you may quickly turn the original problem into a small, simple issue.
• Try to break down the whole solution into various steps (different steps need different
solutions) to make the process easier.
• Are sub-problems easy to solve? If not, the original problem may cost lots of time.
Developed by Richard Bellman in the 1950s, the dynamic programming algorithm is generally
used for optimization problems. In this type of algorithm, past results are collected for future
use. Like the divide and conquer algorithm, a dynamic programming algorithm simplifies a
complex problem by breaking it down into some simple sub-problems. However, the most
significant difference between them is that the latter requires overlapping sub-problems, while
the former doesn’t need to.
4. Greedy Algorithm
This is another way of solving optimization problems – greedy algorithm. It refers to always
finding the best solution in every step instead of considering the overall optimality. That is to
say, what he has done is just at a local optimum. Due to the limitations of the greedy algorithm,
it has to be noted that the key to choosing a greedy algorithm is whether to consider any
consequences in the future.
The brute force algorithm is a simple and straightforward solution to the problem, generally
based on the description of the problem and the definition of the concept involved. You can
also use "just do it!" to describe the strategy of brute force. In short, a brute force algorithm is
considered as one of the simplest algorithms, which iterates all possibilities and ends up with
a satisfactory solution.
6. Backtracking Algorithm
Based on a depth-first recursive search, the backtracking algorithm focusing on finding the
solution to the problem during the enumeration-like searching process. When it cannot satisfy
the condition, it will return “backtracking” and tries another path. It is suitable for solving large
and complicated problems, which gains the reputation of the “general solution method.” One
of the most famous backtracking algorithm example it the eight queens puzzle.
Now that we have learned the definitions of algorithm and flowchart, how can we use a
flowchart to represent an algorithm? To create an algorithm flowchart, we need to use a handy
diagramming tool like EdrawMax to finish the work.
Algorithms are mainly used for mathematical and computer programs, while flowcharts can be
used to describe all sorts of processes: business, educational, personal, and algorithms. So
flowcharts are often used as a program planning tool to organize the program's step-by-step
process visually. Here are some examples:
Algorithm:
• Step 1: Initialize X as 0,
• Step 2: Increment X by 1,
• Step 3: Print X,
• Step 4: If X is less than 20 then go back to step 2.
Flowchart:
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Algorithm:
Flowchart:
Example 3: Determine Whether A Student Passed the Exam or Not:
Algorithm:
Flowchart:
Part 6: Conclusion
From the above, we can come to the conclusion that a flowchart is a pictorial representation of
an algorithm, an algorithm can be expressed and analyzed through a flowchart. An algorithm
shows you every step of reaching the final solution, while a flowchart shows you how to carry
out the process by connecting each step. An algorithm uses mainly words to describe the steps
while you can create a flowchart with flowchart symbols to make the process more logical.
Pseudo Code
Pseudo code uses the structural conventions of a programming language, but is intended for
human reading rather than machine reading. It typically omits details that are not essential for
human understanding of the algorithm, such as variable declarations, system-specific code and
some subroutines. The programming language is augmented with natural language description
details, where convenient, or with compact mathematical notation.
The purpose of using pseudo code is that it is easier for people to understand than conventional
programming language code, and that it is an efficient and environment-independent
description of the key principles of an algorithm. It is commonly used in textbooks and
scientific publications that are documenting various algorithms, and also in planning of
computer program development, for sketching out the structure of the program before the
actual coding takes place.
In the following example, the pseudocode is on program that can add 2 numbers together
then display the result.
Solution:
• Start Program
• Enter two numbers A,B.
• Add the two numbers together
• Print Sum
• End Program.
• History of C
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.
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
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> 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.
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.
printf("format string",argument_list);
Scanf() function
The scanf() function is used for input. It reads the input data to the console.
scanf("format string",argument_list);
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.
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
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.
o 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.
o 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.
o This assembly code is then sent to the assembler, which converts the assembly code
into object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.
• C tokens:
Tokens in C is the most important element to be used in creating a program in C. We can define
the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic component for creating
a program in C.
Classification of tokens in C
• Keywords can be defined as the pre-defined or the reserved words having its 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:
do if static while
• Identifiers in C
Identifiers are used for naming variables, functions, arrays, structures, etc. Identifiers in C are
the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore,
or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot
be used as keywords. Rules for constructing identifiers in C are given below:
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
Types of Constants in C
Constant Example
• Strings in C
Strings are always represented as an array of characters having null character '\0' at the end of
the string. This null character denotes the end of the string. Strings in C are enclosed within
double quotes, while characters are enclosed within single characters. The size of a string is a
number of characters that the string contains.
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
• Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing
the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.
• Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment operator
(++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the list of
the binary operators:
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator
• Data types
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
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
float 4 byte
double 8 byte
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is used
to represent them.
It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between around
-2 billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which takes up
one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4
x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places,
yields larger values. C treats floating point numbers as doubles by default if no explicit type is
supplied.
int age = 25;
char grade = 'A';
float temperature = 98.6;
double pi = 3.14159265359;
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables
for the number pi.
Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type.
It provides a mechanism for joining multiple targets of the same data under the same name.
The index is used to access the elements of the array, with a 0 index for the first entry. The size
of the array is fixed at declaration time and cannot be changed during program execution. The
array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:
#include <stdio.h>
int main() {
int numbers[5]; // Declares an integer array with a size of 5 elements
return 0;
}
Output:
Values in the array: 10 20 30 40 50
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by specifying
the memory address of the variable. Pointers are commonly used in tasks such as function
pointers, data structures, and dynamic memory allocation.
int main() {
int num = 42; // An integer variable
int *ptr; // Declares a pointer to an integer
return 0;
}
Output:
Value of num: 42
Structure:
A structure is a derived data type that enables the creation of composite data types by allowing
the grouping of many data types under a single name. It gives you the ability to create your
own unique data structures by fusing together variables of various sorts.
A structure's members or fields are used to refer to each variable within it.
Any data type, including different structures, can be a member of a structure.
A structure's members can be accessed by using the dot (.) operator.
return 0;
}
Output:
Name: John Doe
Age: 30
Height: 1.80
Union:
A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members
of a union all share a single memory space. A value can only be held by one member of a union
at any given moment. When you need to represent many data types interchangeably, unions
come in handy. Like structures, you can access the members of a union by using the dot
(.) operator.
Here is an example of a union being declared and used:
#include <stdio.h>
// Define a union representing a numeric value
union NumericValue {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Declare a variable of type union NumericValue
union NumericValue value;
// Assign a value to the union
value.intValue = 42;
// Accessing the union members
printf("Integer Value: %d\n", value.intValue);
// Assigning a different value to the union
value.floatValue = 3.14;
// Accessing the union members
printf("Float Value: %.2f\n", value.floatValue);
return 0;
}
Output:
Integer Value: 42
Float Value: 3.14
int main() {
// Declare a variable of type enum DaysOfWeek
enum DaysOfWeek today;
return 0;
}
Output:
Today is 2
Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
void processInput(void) { /* Function logic */ }
Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a
method for working with pointers to ambiguous or atypical types.
Example:
void* dataPtr;
The void data type is helpful for defining functions that don't accept any arguments when
working with generic pointers or when you wish to signal that a function doesn't return a value.
It is significant to note that while void* can be used to build generic pointers, void itself cannot
be declared as a variable type.
Here is a sample of code that shows how to utilize void in various situations:
#include <stdio.h>
// Function with void return type
void printHello() {
printf("Hello, world!\n");
}
// Function with void parameter
void processInput(void) {
printf("Processing input...\n");
}
int main() {
// Calling a void function
printHello();
return 0;
}
Output:
Hello, world!
Processing input...
Value of number: 10
• C Operators
An operator is simply a symbol that is used to perform 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.
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
• Arithmetic Operators
Arithmetic Operators are used to perform mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).
Increment and Decrement Operators are useful operators generally used to minimize the
calculation.
#include <stdio.h>
void main()
{
int a=5, b=5;
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
•
Relational Operator
Relational operators are used to comparing two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
C provides three logical operators when we test more than one condition
to make decisions. These are:
&& (meaning logical AND),
|| (meaning logical OR) and
! (meaning logical NOT).
Operator Description
&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to
False, the result is False)
Example
• Assignment operator
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.
Operator Description
= Assign
#include <stdio.h>
Int main()
{
Int a=5,c;
c =a;
printf(“c=%d\n”,c);
c +=a;
printf(“c=%d\n”,c);
c -= a;
printf(“c=%d\n”,c);
c*=a;
printf(“c=%d\n”,c);
c /=a;
printf(“c=%d\n”,c);
c %=a;
printf(“c=%d\n”,c);
return o;
}
•Bitwise Operator
C provides a special operator for bit operation between two variables
Operator Description
& Binary AND Operator copies a bit to the result if it exists in both operands.
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
~
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands value is moved left by the number
of bits specified by the right operand.
>> Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand.
Example of AND
12=00001100 (In binary)
25=00011001 (In Binary)
OUTPUT:
8
Example of OR
12=00001100 (In binary)
25=00011001 (In Binary)
OUTPUT:
29
Example of XOR
12=00001100 (In binary)
25=00011001 (In Binary)
OUTPUT:
21
35=00100011(in Binary)
Bitwise Complement operation of 35
~00100011
--------------
11011100 =220 (in decimal)
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output
-36
11
• Conditional Operator
C offers a ternary operator which is the conditional operator
(? : in combination) to construct conditional expressions.
Example
int number = 8;
(num%2 == 0) ? printf("Divisible by two") : printf("Not divisible by two");
• Special Operator in C
C supports some special operators
Operator Description
* Pointer to a variable.
• 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.
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
Type Conversion in C is used to convert a variable from one data type to another data type, and
after type casting compiler treats the variable as of the new data type.
#include <stdio.h>
main ()
{
int a;
a = 15/6;
printf("%d",a);
}
After type conversion is done before division to retain float value 2.500000.
MID TERM EXAMINATION
B.Tech Programmes
2nd Sem, May 2023
Paper Code:ES-102 Subject: Programming in C
Answer Key
Que1 (a) What is the ternary operator? Explain with an example? (CO1)(2.5)
Ans. Ternary operator in C is also known as the Conditional Operator. It is an operator which
takes three operands or variables, unlike the other operators which take one or two
operands. It is a way to shorten the simple if-else code of the block.
Syntax:
Condition?exp2:exp3
Working of Syntax:
• If the condition in the ternary operator is met (true), then the exp2 executes.
• If the condition is false, then the exp3 executes.
Example:
The following example explains the working of the Ternary Operator in C.
int max= 10>15?10:15
So, if the condition 10 > 15 is true (which is false in this case) max is initialized with
the value 10 otherwise with 15. As the condition is false so max will contain 15.
Ans: int m=10,a,b; //This line declares variables a,b and m and assigns value 10 to
variable m
a=++m; //As this statement uses pre-increment operator so the value of a and m
after execution of this line will be a=11 and m=11
b=m++; //As this statement uses post-increment operator so the value of b and
m after execution of this line is b=11 m=12
a--; //After this statement the value of a is 10
--b; //After this statement the value of b is 10
a-=b; //This statement is equivalent to a=a-b. After execution the value of a
becomes 0
printf("%d",a); //This statement prints the value of a to the user.
So the output of the above code will be 0 (Zero)
Que 1(c) Differentiate between identifier and variable? (CO1)(2.5)
Ans. Identifiers are used for the naming of variables, functions, and arrays. It is a string
of alphanumeric characters that begins with an alphabet, or an underscore (_ ) that
are used for variables, functions, arrays, structures, unions, and so on. We cannot
use keywords as identifier as keywords are reserved for special use.
A variable is a name that points to a memory location. It is the basic unit of storage
in a program. The value of a variable can be changed during program execution. All
the operations are done on the variable effects that memory location. In C, all the
variables must be declared before use.
Identifiers Variables
It is a unique name which is given to an A Variable is a name that is assigned to a
entity to distinctly identify it during the memory location, which is used to contain
execution of the source-code the corresponding value in it. Variables are
only the sort of identifiers.
C Code cannot have the same of two or All variables are identifiers whereas vice-
more identifiers. For example Structure versa isn’t true. The values can be Real, Char,
name, Function name, Enumerator name, String, Int, Float, Double, Unsigned, etc.
Union, etc. cannot be same.
An identifier name shouldn’t resemble The value that is stored in memory block can
with the keywords because keywords are be modified during the program
predefined. Double, Continue, float, else, execution. Similarly, as identifiers, two or
etc can’t be used as identifiers in a more variables also can’t have the same name
program. in a program.
Que 1(e) Write an algorithm and design a flowchart to print the factorial of a
number?(CO1)(2.5)
Ans: Algorithm to display factorial of a number
Step 1: Start
Step 2: Read a number say n
Step 2: Initialize variables: i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise go to step 6
Step 4: Calculate fact = fact * i
Step 5: Increment the value of i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop
Start
Read n
i=1
fact=1
Is No
i<=
n
Yes
Print fact
fact=fact*i
Que 2 (a) Write a program in C to print the table of two using all three basic
loops?(CO2)(5) i=i+1 Stop
#include <stdio.h>
void main()
{
int num=2,i;
for (i=1;i<=10;i++)
printf("%d * %d =%d\n",num,i,num*i);
}
#include <stdio.h>
void main()
{
int num=2,i=1;
while(i<=10)
{
printf("%d * %d =%d\n",num,i,num*i);
i++;
}
}
#include <stdio.h>
void main() {
int num=2,i=1;
do
{
printf("%d * %d =%d\n",num,i,num*i);
i++;
}while(i<=10);
}
Que 2(b) Explain break, continue , goto and jump statements with an
examples?(CO2)(5)
Ans. The break, continue and goto statements are known as Jump Statements. These
statements are used to alter the normal flow of a program.
Sometimes there is a need to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue
statements are used.
break statement
In C programming, break statement is used with conditional if statement. The break
is used in terminating the loop immediately after it is encountered. It is also used in
switch...case statement.
Example
#include<stdio.h>
void main(){
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}
sum=sum+num;
}
printf("Total is %d",sum);
}
continue statement
It is sometimes desirable to skip some statements inside the loop. In such cases,
continue statement is used. It is also used with if statement.
Example
#include<stdio.h>
void main()
{
int i,n;
printf("Enter Number of odd terms you want\n");
scanf("%d",&n);
for(i=1;i<=2*n;++i)
{
if(i%2==0)
continue;
printf(“%d”,i);
}}
goto statement
In C Language, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;
For Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}
}
// function definition
int add3(int a, int b)
{
Int c;
c=a+b;
return c;
If Statement Switch Case Statement
This statement Can be used check multiple Switch Statements Can be used to check a
conditions at a time single condition at a time
If more conditions are used, it is more Even if the number of conditions increase,
difficult to understand switch statement is still easier to understand
It is popular for nesting of a loop It is not popular for nesting of a loop
It is used for comparing string vs string It is used for Comparing int, byte, char,
long, short, and enum
#include<stdio.h> #include <stdio.h>
main() void main()
{ {
int a = 15, b = 20; int num; // Input a number from user
if (b > a) printf("Enter any number to check even or
{ odd: "); scanf("%d", &num);
printf("b is greater"); switch(num % 2) // If n%2 == 0
} {
} case 0: printf("Number is Even");
break;
case 1: printf("Number is Odd");
break;
}}