parajulirajesh.com.np

Unit 8

What is program?

The program is the set of  instructions that command thecomputer to perform a particular operation or a specific task.

  • Instruction is a statement.
  • A statement is an instruction to do only one task.
  • A group of statements is composed together to form a program.

Unit 1 Introduction of programming Language

A programming language is a computer language that is used by programmers (developers) to communicate with computers. It is a set of instructions written in any specific language ( C, C++, Java, Python) to perform a specific task.

  • A programming language is a language that allows people to write specific commands to be executed on a computer.
  • A programming language is mainly used to develop desktop applications, websites, and mobile applications.
  • Most commonly used Programming Language are Python, JAVA, C, C++, C#, RUBY, PHP … etc.

Types of Programming Language
1. Low-level Language
2. High Level Language

Translator:

Translator is a software that translates or converts instructions written in assembly or high level language (source code) into Machine Level Language (Object code). 

Why use translator?  

The program is developed in assembly or in high level language for the easyness, understandable (Convenience) of the programmer but computer does not understands these statements directly, so the translator is used which converts high level statements (source code) in a machine executable format(object code).

Computers understand only machine code:

  • Human languages like Python, C, or Java cannot be executed directly.
  • Translator converts them into machine code (0s and 1s).

Makes programming easier:

  • Programmers can write in a high-level language, which is easier to understand.
  • Translator handles the conversion to low-level instructions.

Detects errors:

  • Compilers/interpreters can show syntax or logical errors in the code.

Portability:

  • High-level code can run on different machines if translated properly.

Assembler: Assembler is a translator that converts the code of the assembly language (Source Code) into the machine language (Object Code). When assembler completed it converted process then only it started to execute the program.
Compiler: A Compiler is a translator which translates the complete high level program (Source Code) into the machine code
(object code) at once if the program doesn’t contain syntax errors. Programming languages like C, C++, Java use the compiler.
Interpreter: An interpreter is a language translator which translates high-level language into the machine language at one line at a
time and executes the line of the program after it has been translated. It translates statements line by line.

Differences between Compiler and interpreter?

CompilerInterpreter
Translates the entire program into machine code at once.Translates the program line-by-line.
Translation is faster once compiled.Translation is slower because it works one line at a time.
Stores the machine code on disk after compilation.Does not store machine code on disk.
Shows all errors after compiling the whole program; debugging is harder.Shows errors line-by-line; debugging is easier.
Examples: C, C++, JavaExamples: Python, PHP, BASIC, C#

Syntax

In a programming language, Syntax defines the rules that governs the structure and arrangement of keywords, symbols, and other elements. Syntax doesn’t have any relationship with the meaning of the statement; it is only associated with the grammar and structure of the programming language.

  • A line of code is syntactically valid and correct if it follows all the rules of syntax.
  • Syntax does not have to do anything with the meaning of the statement.
  • Syntax errors are easy to catch.
  • Syntax errors are encountered after the program has been executed.

Semantics

Semantics refers to the meaning of the associated line of code and how they are executed in a programming language. semantics helps interpret what function the line of code/program is performing.

  • If there is any semantic error and even when the statement has correct syntax, it wouldn’t perform the function that was
    intended for it to do. Thus, such errors are difficult to catch.
  •  Semantics are encountered at runtime.

Programming Design Tools

Program design Tools are the tools that are used to design a program before it actually developed. Program design tools are used by the developers. Some program design tools are: Algorithm, Flow Charts, Pseudo Code, Data flow Diagram(DFD), Usecase Diagram… etc.

Algorithm: An algorithm is a step-by-step procedure or set of instructions used to solve a problem.

  • An algorithm is the sequence of steps that needs to be followed in order to acheive certain task.
  • An algorithm is the fininte set of step by step set of statements that is used to solve a particular problem.
  •  It is written in simple human readable English Language.

An Algorithm should have the following properties:
1. It should have an input.
2. The steps mentioned in an algorithm can be executable by the computer
3. Each and every instruction should be in a simple language.
4. The number of steps should be finite.
5. It should not depend on a particular computer language or computer.
6. The algorithm should give an output after executing the finite numbers of steps.

Algorithm: Find the Sum of Two Numbers

Step 1: START
Step 2: Read the two numbers A and B
Step 3: Add the numbers → S = A + B
Step 4: Display S
Step 5: STOP

Algorithm: Find the Simple Interest (SI)

Step 1: START
Step 2: Read the principal (P), rate (R), and time (T)
Step 3: Multiply P, R, and T → Product = P × R × T
Step 4: Divide the product by 100 to get SI → SI = (P × R × T) / 100
Step 5: Display SI
Step 6: END

Algorithm: Print numbers from 1 to 20

Step 1: START
Step 2: Initialize X = 0
Step 3: Increment X by 1
Step 4: Print X
Step 5: If X < 20, go back to Step 3
Step 6: STOP

PRACTICE QUESTIONS 

  1. Find the area of a rectangle

  2. Find the square of a number

  3. Print the first 10 natural numbers

  4. Find the average of three numbers

  5. Check if a number is positive or negative

  6. Check if a number is even or odd.

  7. Swap Two Numbers

Flowchart

A flowchart is a pictorial representation of an algorithm. Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use simple geometric shapes to depict processes and arrows to show relationships and process/data flow.

Difference between Algorithm and Flowchart?

AlgorithmFlowchart
It is a procedure for solving problems.It is a graphic representation of a process.
The process is shown in step-by-step instructions.The process is shown in block-by-block 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 language.The solution is showcased in pictorial format.
It is somewhat easier to solve complex problems.It is harder to solve complex problems.
It takes more time to create an algorithm.It takes less time to create a flowchart.

Features of good programme

 

  1. Correctness
    A good program gives the right output for the given input. It does what it is supposed to do.

  2. Readability
    The program should be easy to read and understand. This is done by using proper names, spacing, and comments.

  3. Simplicity
    A good program is simple, not unnecessarily complicated. Simple code is easier to write, understand, and fix.

  4. Efficiency
    The program should use less time and memory. It should work fast and not waste computer resources.

  5. Maintainability
    The program should be easy to update or fix in the future if changes are needed.

  6. Modularity
    The program should be divided into small parts (functions or modules). This makes it easier to test and understand.

  7. Portability
    A good program can run on different computers or systems with little or no change.

  8. Reliability
    The program should work properly every time and handle errors smoothly without crashing.

C programming is a general-purpose, procedural programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. e The UNIX OS was totally written in C.

History of C

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. C was developed to overcome the problems of previous languages such as B, BCPL, etc.

Basic Structure of C program

  1. Documentation Section
  2. Link Section
  3. Definition Section
  4. Global Declaration Section
  5. main() Function
  6. User-Defined Functions

In C language, all these six sections together make up the Basic Structure of C Program

1. Documentation Section

Programmers write comments in the Documentation section to describe the program. The compiler ignores the comments and does not print
them on the screen. Comments are used only to describe that program.

/* File Name -: Hello.c
Author Name -: Rajesh parajuli
Founder of parajulirajesh.com.np
Date -: 12/09/2023
Description -: Basic Structure of C program */
//This is a single line comment

2. Link Section or Preprocessor Section

Includes header files needed by the program. Header files contain predefined functions. Within the Link Section, we declare all the Header Files that are used in our program. From the link section, we instruct the compiler to link those
header files from the system libraries, which we have declared in the link section in our program.

#include <stdio.h>

3. Definition Section

The Definition Section of a C program is used to define constants and macros using the #define directive. The values defined in this section do not change during program execution. It helps make the program easy to understand, avoids repeating fixed values, and allows changes to be made in one place. This section is written before the main() function and improves the readability and maintainability of the program.

#define PI 3.14
#define SQUARE(x) (x * x)

4. Global Declaration Section

The Global Declaration Section of a C program is where global variables and function prototypes are declared. Variables declared here, called global variables, can be used in any part of the program, including main() and other functions. Function prototypes tell the compiler about functions that will be defined later. This section is written before the main() function and helps make the program organized, easy to understand, and maintain.

int total; // global variable
void display(); // function prototype

5.main() Function

The main() function is the starting point of a C program where execution begins. All the program’s instructions are written inside it, and it can call other functions. It usually returns 0 to indicate that the program ran successfully.

int main() {
// statements
return 0;
}

6.User-Defined Functions

User-defined functions are the functions written by the programmer to perform specific tasks in a C program. They help make the program organized, reusable, and easy to understand.

#include <stdio.h>
void greet() { // user-defined function
printf(“Hello!”);
}
int main() {
greet(); // calling the function
return 0;
}

Character Set

As every language contains a set of characters used to construct words, statements, etc., C language also has a set of characters which
include alphabets, digits, and special symbols. C language supports a total of 256 characters. Every character in C language has its equivalent
ASCII (American Standard Code for Information Interchange) value.

Every C program contains statements. These statements are constructed using words and these words are constructed using characters from C
character set. C language character set contains the following set of characters:
1. Alphabets
2. Digits
3. Special Symbols
Alphabets:
C language supports all the alphabets from the English language. Lower and upper case letters together support 52 alphabets.
lower case letters — a to z
UPPER CASE LETTERS — A to Z
Digits: C language supports 10 digits which are used to construct numerical values in C language.

Digits — 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols:
C language supports a rich set of special symbols that include symbols to perform mathematical operations, to check conditions, white spaces,
backspaces, and other special symbols.
Special Symbols -~ @#$%*&*()_-+={}[]5:5″/?.>,<\]

A token is a smallest individual element of a program which is meaningful to the compiler. The compiler that breaks a program into the smallest
units is called tokens and these tokens proceed to the different stages of the compilation. Tokens in C are building blocks which means a program can’t be created without tokens.

Classification of Tokens are:  

  1. Keywords
  2. Identifiers
  3. Constants
  4. Strings
  5. Special Symbols
  6. Operators

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and
they cannot be used as an identifier.
 C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all Keywords allowed in ANSI C.

C Predefined 32 Keywords

Identifier

Identifiers in C 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:

  • An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters and digits) and underscore( _ ) symbol.
    Identifier names must be unique
  • The first character must be an alphabet or underscore.
  • You cannot use a keyword as an identifier.
  • Only the first thirty-one (31) characters are significant.
    It must not contain white spaces.
  • Identifiers are case-sensitive.

For Example:
int cprogram;
Char Bicte_firstsemester;
here, int and Char is keywords and cprogram and Bicte_firstsemester is identifier.

Constants:

The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant
can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.

What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared in the program. We can not make any
change in the value of the constant variables after they are defined.

Syntax to Define Constant
const data_type var_name = value;

Strings:

  • Sequence of Characters is known as Strings.
  • Every String is terminated by \0
  •  String Constant is a sequenced os 0 or more characters enclosed between double quotes ”” is known as string constant e.g. “S”, “XYZ”,
    “123”, “hello world”
  • All characters are converted into their corresponding ASCII value and then stored in memory as contiguous allocation.
  • String Variable is the array of character type. For e.g. char[10];
    char greeting[6] = {H’, ‘e’, ‘I’, I’, ‘o’, ‘\O’};
             If you follow the rule of array initialization then you can write the above statement as follows —
             char greeting[] = “Hello’;

#include <stdio.h>

int main() {
char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
printf(“Greeting message: %s\n”, greeting);
return 0;
}

#include <stdio.h>

int main()
{
char name[6];

printf(“Enter name: “);
scanf(“%5s”, name); // limit input to 5 characters

printf(“Your name is %s.”, name);
return 0;
}

Like many other programming languages, strings in C are enclosed within double quotes(” “), whereas characters are enclosed within single
quotes(‘ ‘). When the compiler finds a sequence of characters enclosed within the double quotation marks, it adds a null character (\0) at the end
by default.

1. Character arrays are used for declaring strings in C.
2. The general syntax for declaring them is:

char variable[array_size];

Special Symbols are symbols in C language that have special meaning and can not be used for any other purpose.

  • Brackets[]: Opening and closing brackets are used as array element references. These indicate single and multidimensional subscripts.
  • Parentheses(): These special symbols are used to indicate function calls and function parameters.
  • Braces{}: These opening and ending curly braces mark the start and end of a block of code containing more than one executable
    statement.
  • Comma (, ): It is used to separate more than one statement like for separating parameters in function calls.
  • Colon(:): It is an operator that essentially invokes something called an initialization list.
  • Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s why each individual statement must
    be ended with a semicolon.
  • Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
  • Assignment operator(=): It is used to assign values and for logical operation validation.
  • Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before
    actual compilation.
  • Period (.): Used to access members of a structure or union.
  • Tilde(~): Used as a destructor to free some space from memory.
  • Square Brackets [ |
    The opening and closing square brackets represent single and multi-dimensional subscripts and they are used as array element reference for
    accessing array elements.
    int arr[10]; //For declaring array, with size defined in square brackets
  • Simple Brackets () The opening and closing circular brackets are used for function calling and function declaration.

           get_area(100); //Function calling with 100 as parameter passed in circular brackets

Curly Braces { }
In C language, the curly braces are used to mark the start and end of a block of code containing executable logical statements.
int main{
printf(“Illustrating the use of curly braces!”);
}
Comma (,)
Commas are used to separate variables or more than one statement just like separating function parameters in a function call.
int a=10,b=20,c=30; //Use of comma operator
Pre-Processor / Hash (#)
It is a macro-processor that is automatically used by the compiler and denotes that we are using a header file.
#include<stdio.h> //For defining header-file
#define Il long
int main(){
printf(“Hello World!”);
}
Asterisk (*)
Asterisk symbols can be used for multiplication of variables and also for creating pointer variables. Example:
int main({
int a = 20,b = 10;
int sum = a*b; //Use of asterisk in multiplication
int *ptr = &a;
//Pointer variable ptr pointing to address of integer variable a
}
Tilde (~)
It is used as a destructor to free some space from the memory.
int main({
int n = 2;
printf(“Bitwise complement of %d: %d”, n, ~n);
//Bitwise complement of 2 can be found with the help of tilde operator and the result here is -3
}
Period (.)
It is used to access members of a structure or a union.
#include <stdio.h>
#include <string.h>

struct Person { //structure defined
int city_no; //members of structure
float salary;
}person1;
int main(){
person1.city_no = 100;
//accessing members of structure using period (.) operator
person1.salary = 200000;
printf(“City_Number: %d”,person1 .city_no);
printf(“\nSalary: %.2f”,person1.salary);
return 0;
}
Colon (:)
It is used as a part of conditional operator (?:) in C language.
Example:
int a = 10,b = 20,c;
c=(a<b)?a:b;
//\f a<b is true, then c will be assigned with the value of a else b
printf(“%d”, c);
int a=10; //Semi-colon is widely used in C programs to terminate a line
Semicolon (;)
It is known as a statement terminator and thus, each logical statement of C language must be ended with a semi-colon.
Example: int a=10; //Semi-colon is widely used in C programs to terminate a line 

Assignment Operator (=)
It is used to assign values to a variable and is sometimes used for logical operation validation.
Example:
int a = 10, b = 20; //Assignment operator is used to assign some values to the variables

Operators are symbols used to perform operations on variables or values. C provides a rich set of built-in operators to carry out mathematical, relational, logical, and other types of computations on operands.

Types of operators:

1. On the Basis of Number of Operands Required

TypeDescriptionExample
Unary OperatorsWork with one operand++a, --a
Binary OperatorsWork with two operandsa + b, a > b, a && b
Ternary OperatorWorks with three operands(a>b) ? a : b

Unary Operators

#include <stdio.h>

int main() {
int a = 5;

printf(“Initial value: a = %d\n”, a);

a++; // increment by 1
printf(“After a++: a = %d\n”, a);

a–; // decrement by 1
printf(“After a–: a = %d\n”, a);

return 0;
}

Ternary program Example

#include <stdio.h>

int main() {
int num;

printf(“Enter a number: “);
scanf(“%d”, &num);

// Using ternary operator to check even or odd
(num % 2 == 0) ? printf(“%d is even.\n”, num)
: printf(“%d is odd.\n”, num);

return 0;
}

2. On the Basis of Utility (Function) of Operators

According to the utility and action, operators are classified into following categories:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C program. They can be used in
programs to define expressions and mathematical formulas

OperatorNameAction / DescriptionSyntax Example
+AdditionAdds two operandsx + y
-SubtractionSubtracts the second operand from the firstx - y
*MultiplicationMultiplies two operandsx * y
/DivisionDivides the first operand by the secondx / y
%ModulusReturns remainder of division

x % y

#include <stdio.h>

int main()
{
int a = 10, b = 4, res;

// printing a and b
printf(“a is %d and b is %d\n”, a, b);

res = a + b; // addition
printf(“a + b is %d\n”, res);

res = a – b; // subtraction
printf(“a – b is %d\n”, res);

res = a * b; // multiplication
printf(“a * b is %d\n”, res);

res = a / b; // division
printf(“a / b is %d\n”, res);

res = a % b; // modulus
printf(“a %% b is %d\n”, res);

return 0;
}

Output:

a is 10 and b is 4
a + b is 14
a – b is 6
a * b is 40
a / b is 2
a % b is 2

Relaional/ Comparison Operators

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.

OperatorNameExampleResult / Meaning
==Equal tox == yReturns 1 if x is equal to y
!=Not equal tox != yReturns 1 if x is not equal to y
>Greater thanx > yReturns 1 if x is greater than y
<Less thanx < yReturns 1 if x is less than y
>=Greater than or equal tox >= yReturns 1 if x is greater than or equal to y
<=Less than or equal tox <= yReturns 1 if x is less than or equal to y

#include <stdio.h>

int main()
{
int a = 10, b = 4;

// Greater than example
if (a > b)
printf(“a is greater than b\n”);
else
printf(“a is less than or equal to b\n”);

// Greater than or equal to
if (a >= b)
printf(“a is greater than or equal to b\n”);
else
printf(“a is less than b\n”);

// Less than example
if (a < b)
printf(“a is less than b\n”);
else
printf(“a is greater than or equal to b\n”);

// Less than or equal to
if (a <= b)
printf(“a is less than or equal to b\n”);
else
printf(“a is greater than b\n”);

// Equal to
if (a == b)
printf(“a is equal to b\n”);
else
printf(“a and b are not equal\n”);

// Not equal to
if (a != b)
printf(“a is not equal to b\n”);
else
printf(“a is equal to b\n”);

return 0;
}

Output:

a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

Logical operators
Logical Operators are used to compare or evaluate logical and relational expressions. The operands of logical operators must be either Boolean
value (1 or 0) or expressions that produces Boolean value. The Output of these operators is always either 1 true or 0 False. The logical Operators
supported in C are:

  • && logical AND : it produces true if each operand is true otherwise it produces false.
  • || Logical OR : it produces true when any of the conditions is true.
  • !Logical NOT- it reverse to the operand.

Write a program to illustrate the output of logical operators.

#include <stdio.h>

int main()
{
int a = 10, b = 5, c = 40;

// Logical AND (&&)
printf(“a < b && a < c is %d\n”, (a < b && a < c));
printf(“a > b && b > c is %d\n”, (a > b && b > c));

// Logical OR (||)
printf(“a < b || a < c is %d\n”, (a < b || a < c));
printf(“a > b || b < c is %d\n”, (a > b || b < c));
printf(“a > c || b > c is %d\n”, (a > c || b > c));

// Logical NOT (!)
printf(“!a is %d\n”, !a);
printf(“!b is %d\n”, !b);

return 0;
}

Assignment Operators

Assignment Operators are also binary operators and they are used to assign result of an expression to a variable. The mostly used assignment operator is ‘=’. There are other shorthand assignment operators supported by C. They are +=,-=,*=,/+ and %=. These Operators are also known as arithmetic assignment operators.

  • += Addition Assignment (a+=b, means a=a+b) assign sum of a and b to a.
  • -= Subtraction Assignment ( a-=b, means a=a-b) assign subtraction of a and b to a) 
  • *= Multiplication Assignment (a*=b, means a=a*b) assign multiplication of a and b to a)
  • /= Division Assignment (a/=b, means a=a/b) assign division of a and b to a)
  • %= Remainder Assignment (a%=b, means a=a%b) assign remainder of a divisible by b to a)

#include <stdio.h>

int main()
{
int a = 10, b = 5;

b += a; // same as b = b + a

printf(“b = %d”, b);

return 0;
}

Increment and decrement operators

The increment operator is used to increase the value of an operand by 1; and the decrement operator is used to decrease the value of an
operand by 1. They take one operand, so called unary operator. The syntax for the operator is:

  • ++ variable
  • variable++
  • –variable
  • variable–

#include <stdio.h>

int main() {
int x = 10;

printf(“Initial value of x: %d\n”, x);

x++; // Increment
printf(“After increment (x++): %d\n”, x);

x–; // Decrement
printf(“After decrement (x–): %d\n”, x);

return 0;
}

Output:

Initial value of x: 10
After increment (x++): 11
After decrement (x–): 10

Conditional Operators

The Operator named “?:” is known as conditional Operator. It takes three operands. Thus, it is also called ternary operator. The syntax is :

value= expression ? expression2: expression3

working principal
If(expression 1)
variable = expression2;
else
variable = expression3;

Write a program to read two numbers from user and determine the larger number using conditional operator.

#include <stdio.h>
int main()
{
int n1, n2, larger;
printf(“Enter two numbers: “);
scanf(“%d %d”, &n1, &n2);
larger = (n1 > n2) ? n1 : n2;
printf(“The larger number is %d”, larger);
return 0;
}

Output:

Enter two numbers: 8 12
The larger number is 12

Bitwise Operator

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. It can be used only integer type values not float, double etc.

The bitwise operators are the operators used to perform operations on the data at the bit-level. When we perform bitwise operations, 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. Bitwise operators can be used only with integer type values, not float, double, etc.

We have different types of bitwise operators in the C programming language. The following is the list of the bitwise operators:

OperatorName of the Operator
&Bitwise AND operator
``
^Bitwise exclusive OR operator
~One’s complement operator (unary operator)
<<Left shift operator
>>Right shift operator

Truth Table of Bitwise Operators

Let’s look at the truth table of the bitwise operators:

XYX & YX | YX ^ Y
00000
01011
10011
11110
  • Bitwise AND (&) gives 1 if both corresponding values are 1.

  • Bitwise OR (|) gives 1 if at least one corresponding value is 1.

  • Bitwise XOR (^) gives 0 if both corresponding values are the same, and 1 if they are different.

#include <stdio.h>

int main()
{
int a = 7, b = 14;

printf(“Bitwise AND: %d\n”, a & b); // 7 & 14 = 6
printf(“Bitwise OR: %d\n”, a | b); // 7 | 14 = 15
printf(“Bitwise XOR: %d\n”, a ^ b); // 7 ^ 14 = 9

return 0;
}

Left Shift Operator

The left shift operator is a type of Bitwise shift operator, which performs operations on the binary bits. It is a binary operator that requires two
operands to shift or move the position of the bits to the left side and add zeroes to the empty space created at the right side after shifting the bits.

Bitwise Left shift operator is used to shift the binary sequence to the left side by specified position.

Example
Let’s take a number 14.

Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8 bit)

14 = (00001110)base2

Then 14 << 1 will shift the binary sequence 1 position to the left side.  Like,

Empty boxes will be marked as 0.

#include <stdio.h>

int main()
{
int num;
printf(“Enter a positive number: “);
scanf(“%d”, &num);
num = (num << 2);
printf(“\nAfter shifting the binary bits to the left side”);
printf(“\nThe new value of num = %d”, num);
return 0;
}

Output:

5 = 00000101
Shift left by 2 → 00010100 = 20

In general, if we shift a number by n position to left, the output will be number * (2″).

Right Shift Operator

The right shift operator is a type of bitwise shift operator used to move the bits at the right side, and it is represented as the double (>>) arrow
symbol. Like the Left shift operator, the Right shift operator also requires two operands to shift the bits at the right side and then insert the
zeroes at the empty space created at the left side after shifting the bits.

Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.

Example
Let’s take a number 14.
Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8 bit)
14 = (00001110)base 2
Then 14 >> 1 will shift the binary sequence by 1 position to the right side.

#include <stdio.h>

int main()
{
// declare local variable
int num;

printf(“Enter a positive number: “);
scanf(“%d”, &num);

// use right shift operator to shift the bits
num = (num >> 2); // shifts bits two positions to the right

printf(“\nAfter shifting the binary bits to the right side.”);
printf(“\nThe new value of the variable num = %d”, num);

return 0;
}

Output:

Enter a positive number: 12

After shifting the binary bits to the right side.
The new value of the variable num = 3

#include<stdio.h>
struct student
{
int id;
char name[50];
};
int main()
{
FILE *ptr;
struct student s[3];
ptr=fopen(“rajesh.txt”,”w”);
int i;
 
for(i=0;i<3;i++)
{printf(“enter id and name: “);
  scanf(“%d%s”,&s[i].id,s[i].name);
}
for(i=0;i<3;i++)
{
fprintf(ptr,”%d student record: “,i+1);
fprintf(ptr,”student id =%d and name=%s\n”,s[i].id,s[i].name);
}
return 0;
}
Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE