Linux Commands, C, C++, Java and Python Exercises For Beginners
Linux Commands, C, C++, Java and Python Exercises For Beginners
− Socrates
Manjunath.R
*Email: manjunath5496@gmail.com
Disclaimer
Despite my best efforts to assure the accuracy of the material in this book, I do not accept
and hereby disclaim any liability to any party for any loss, damage, or disruption caused by
mistakes or omissions, whether caused by negligence, accident, or any other cause.
As long as you comply by the conditions of the license, the licensor cannot revoke these rights.
You have to
I dedicate this book to every individual, programmer, teacher, educational institutions and
enterprise corporations in every country of the world for their immense contributions towards the
process of creating, designing, deploying and supporting software…
Acknowledgements
Without the amazing work of some renowned programmers, their creativity, and their inventiveness in the
field of software programming, this book would not have been accomplished. I would like to use this
opportunity to thank my dearest friend and well-wisher "Lawrence" for his unwavering support during
the COVID crisis and for giving me access to all the resources I needed to finish this book. I want to
express my gratitude to my family for their support and encouragement as I wrote this book, especially to
my mother, who has been a tremendous source of inspiration in my life. I owe a lot of gratitude to my
mother for teaching me how to be perseverant and strong in life. Finally, I want to emphasize how crucial
patience is when writing a book or taking on any other project in life.
Foreword
I'm neither the proprietor of a well-known publishing house or a top IT firm with hundreds of in-
house programmers who could easily produce anything I needed. I am a self-employed software
engineer who is passionate about what I do, and believe me when I say that a lot of work and
effort went into compiling this comprehensive edition. I'll be overjoyed if it helps even a few
others reach their ideal positions in their professions.
Thank You
− Manjunath.R
An Enjoyable Introduction to Coding
Introduction
Today's devices are mostly powered by software: almost everyone uses Facebook,
WhatsApp and Twitter to communicate, many phones have internet-connected desktops, and the
majority of office work requires using a computer to do tasks. As a response, there is a huge
increase in demand for programmers. Numerous books, interactive websites, and programmer
training courses make the bold claim that they can turn ambitious novices into software
engineers earning six figures. This book is for all programmers, whether you are a novice or an
experienced pro. Its numerous examples and well paced discussions will be especially beneficial
for beginners. Those who are already experienced with programming will probably gain more
from this book, of course. You will be at a modest level of programming proficiency when you
have finished this book, from where you can take yourself to next levels so that you can
automate simple tasks such as:
This book will make an amazing complement to any tutorial and serve as a source of information
to your specific inquiries if you are just learning what kind of animals C, C+ +, Java, PHP,
Python, and JavaScript are. Even if your career has nothing to do with computers, the skills you
learn from programming can be valuable at school and at work. Programming is a pleasant,
occasionally difficult and perhaps frustrating activity. Creativity, logic, and problem-solving are
all enhanced through programming.
As you progress through this book, keep in mind that programming can be enjoyable. Do not
consider of this as work. Consider programming as a means to develop entertaining games or
software applications that you can show off to others or your friends. Programming is a
tremendous brain workout and is essential today because so much of our everyday world is
automated. But above all, you have access to the quick-paced, creative world that depends on
machine connections.
"The only way to learn a new programming language is by writing programs in it."
– Dennis Ritchie
Note:
1. Always be aware of the purpose of your software program before beginning to write it.
2. Programming is not the solution; it is merely a means to achieve a solution.
3. Consider the problem rather than just the solution.
4. Always try to make things simpler; anyone can come up with a complicated answer to a
problem. To make a solution simple while remaining consistent, it requires extra work
and consideration.
5. Reduce Deeply Nested Ifs or Loops: When your software program is deeply nested, your
program becomes complicated and disorganized.
6. Delete Unnecessary Code. Make sure your software program is safe, secure, reliable,
testable and clear to read.
7. Give code reviews some attention so you can spot bugs early, before they cause serious
problems in your software application.
8. Reduce complexity. Software programs must have clear explanations.
9. Generalize your software program. Make sure your software program is documented.
Understanding the function of a certain component of the software application is greatly
aided by the documentation and comments.
10. Fancy algorithms and data structures are more difficult to implement. Use simple,
efficient, appropriate algorithms and data structures.
11. Refractor your software program frequently to improve its internal software attributes in
terms of upkeep, testing and comprehension.
12. Each time you make a change to your software program: check it, build it and test it.
13. Before being released, all software codes must pass each and every unit test.
14. Always use caution when using someone else's code. Maintain a standardized, orderly
and generally consistent coding style.
15. Avoid implementing a code style that is too hard to understand.
16. Because it makes the code more difficult to maintain, duplication is seen adversely in
software programming.
17. Look for bugs and flaws and fix them. Divide your software program into Brief, Concise
Units.
18. Avoid overdesigning. Focus your software design on the requirements of the clients.
19. Program defensively. Functions should be simple and do a distinct, defined task.
20. Create reusable functions and Keep the functions as simple, immutable and manageable
as possible.
21. When naming your variables and functions, choose names that are meaningful and
descriptive.
22. Put your software program's structure on view by using indentation.
23. Delete any unused variables and functions; do not comment them.
24. If you feel that a part of the software program is excessively unorganized, regroup and
modify it, or even split it up into different portions.
25. Avoid using GOTO statements because they cause the software program to be
unstructured, which makes it harder to understand and makes debugging more complex.
26. Avoid using the same identifier more than once.
27. The length of functions shouldn't be excessively long.
28. Think Twice, Code Once: Encourage yourself to consider the problem more before
coming up with a solution.
29. The very first step in making a software program readable by humans is to add
comments. Comments should be detailed explanations of a software program.
30. White space should be utilized regularly to increase code readability even though it has
little significance to compilers.
31. Coding standards must be followed while formatting code.
32. Avoid security pitfalls and Keep your software code portable.
33. All software design is redesign. Take advice from others' experience.
34. The writing of software program should make it simple for a future software developer
to correct errors or modify its functionality.
35. Never compromise clarity for a false sense of efficiency.
"More computing sins are committed in the name of efficiency (without necessarily
achieving it) than for any other single reason − including blind stupidity."
− W.A. Wulf
36. Enhance the appearance of software program by avoiding excessively long names or
ambiguous acronyms
37. Look for a method that employs a loop rather than duplicating lines. Compared to 100
individual blocks of code, one loop that can handle 100 repetitions is simpler to debug.
You're not coding to amaze strangers. You're in this
profession to find ways to resolve problems.
Important Programming Concepts Every Programmers and
1. Data Types: Understanding the various data types such as integers, floating-point numbers,
characters, and Booleans is crucial for any programmer.
2. Variables: Variables allow programmers to store and manipulate data in their programs.
3. Control Structures: Control structures such as if statements, loops, and switch statements allow
programmers to control the flow of their programs.
4. Functions: Functions allow programmers to break their programs down into smaller, more
manageable pieces.
5. Arrays: Arrays are a way to store multiple values in a single variable.
6. Pointers: Pointers are variables that hold memory addresses, and are used to manipulate memory
directly.
7. Object-Oriented Programming (OOP): OOP is a programming paradigm that focuses on
creating objects that encapsulate data and behavior.
8. Inheritance: Inheritance allows programmers to create new classes that inherit properties and
behaviors from existing classes.
9. Polymorphism: Polymorphism allows programmers to use the same method or operator to work
with different types of data.
10. Algorithms: Algorithms are step-by-step procedures for solving problems, and are a crucial part
of programming.
11. Debugging: Debugging is the process of finding and fixing errors in code, and is an essential
skill for any programmer.
12. Software Development Life Cycle (SDLC): SDLC is the process of developing software from
initial planning to final deployment.
Understanding these concepts and how to apply them will help programmers
no stage director, no emperor, however powerful, has ever exercised such absolute authority to arrange a
stage or field of battle and to command such unswervingly dutiful actors or troops."
− Joseph Weizenbaum
Top 10 Programming Languages and Their Applications
A skilled coder can identify the best solution to any problem and solve even the most challenging
issues. Being a good programmer requires constant knowledge upkeep and the acquisition of
new skills. A PhD isn't always necessary to become a skilled programmer, but discipline and
determination are. Being a successful programmer demands you to be one step ahead, while
becoming a respectable coder takes years of hard effort.
Image Credit: Wikipedia.org
Contents
LINUX COMMANDS 1
C Exercises 325
C − OVERVIEW 870
― Alan J. Perlis
LINUX COMMANDS
Linux is an open-source Unix-like operating system built on the Linux kernel, which Linus
Torvalds initially made available on September 17, 1991. People switching from Windows or
macOS may find Linux difficult to use and comprehend, and many people give up using it
because they are not aware of the commands and shortcuts that Linux offers. When using Linux,
you can accomplish tasks much more quickly than when using other operating systems by
becoming familiar with the useful commands and how to use them correctly. We'll examine a
few widely used Linux commands in this chapter.
When working with unstructured files in Linux, whether you are a sys admin or a database
administrator, there are a number of commands that will be very helpful to you in your everyday
job. Working as developers requires us to use the Linux command line occasionally. Linux is
typically considered to be dominant for public Internet servers, powering well over twice as
many servers as Windows Server. Linux has a monopoly on the supercomputer market,
powering all 500 of the TOP computers. It's quite easy to customize Linux. Your OS can be
modified. In this chapter, we'll look at some fundamental Linux commands that every
programmer should be familiar with.
1
17 Principles of the philosophy of UNIX
2
Principle of Least Surprise: Developers should be encouraged to create user-friendly,
intuitive products
Principle of Silence: Allow programmers and other programs to get the data they require
from a program's output without having to interpret unnecessary extensive and detailed
Principle of Repair: Programmers should create software that fails in a way that is simple
to identify and diagnose
Principle of Economy: Project development costs should be minimized
Principle of Generation: Programmers should develop abstract, high-level programs that
produce code rather than writing code by hand to decrease human error and save time
Principle of Optimization: Before you can optimize it, get it working. Software should
be developed and tested before being masterfully crafted by developers
Principle of Diversity: Make programs flexible, enabling their use in ways other than
those that their creators intended
Principle of Extensibility: Increase the usefulness and lifespan of the developer's written
code
3
Better skills come with increased learning.
Your main focus as a novice should be on becoming familiar with the ins and outs of
operating system architecture as well as discovering shortcuts and time-saving techniques.
4
CentOs is a wonderful option if you use Windows and want to learn Linux because it is one
of the best Linux distributions for beginners. Your first few days using CentOs won't be that
odd. But you must learn how to utilize Linux's command line interface if you want to
experience its full capabilities. You will initially experience some difficulty learning several
instructions. Although employing the instructions won't make you a genius, it will assist you in
carrying out certain fundamental tasks. Here are the most basic CentOs commands for new
users to ensure a smooth start. Let's get right into it!
5
"... being a Linux user is sort of like living in a
house inhabited by a large family of carpenters
and architects. Every morning when you wake
up, the house is a little different. Maybe there
is a new turret, or some walls have moved. Or
perhaps someone has temporarily removed the
floor under your bed."
Linux Commands
Description:
Command:
date
Description:
Display calendar.
Command:
cal
6
Description:
Command:
Description:
Command:
cal 8 2016
Description:
Command:
clear
Description:
Command:
exit
7
Description:
Command:
free
Description:
Command:
free -b
Description:
Command:
free -k
Description:
Command:
8
free -m
Description:
Command:
passwd
Description:
Command:
shutdown
Description:
Command:
shutdown -h now
Description:
9
Command:
shutdown -h +10
Description:
Command:
echo $PWD
Description:
Command:
echo $OLDPWD
Description:
Command:
!11
10
Description:
Command:
history
Description:
Command:
sudo reboot
Description:
Command:
ip address
Description:
Command:
ls -s
11
Description:
Command:
mount
Description:
Command:
du
Description:
Command:
uptime
Description:
Command:
12
date --set 1998-11-02
Description:
Command:
Description:
Command:
fdisk -l /dev/sda
Description:
Command:
ls
Description:
377
13
Command:
ps
Description:
Command:
df
Description:
Command:
df -H
Description:
Command:
rm -r *
14
Description:
Command:
top
Description:
Command:
reboot
Description:
Command:
kill
Description:
Command:
cd
15
Description:
Command:
login
Description:
Command:
lsof
Description:
Command:
lsusb
Description:
Command:
16
service network status
Description:
Command:
Description:
Command:
Description:
Command:
Description:
Report information about the users currently on the machine and their processes.
17
Command:
Description:
Command:
pwd
Description:
Displays CPU architecture information (such as number of CPUs, threads, cores, sockets, and
more).
Command:
lscpu
Description:
Command:
nproc
18
Description:
Command:
init 6
Description:
Command:
init 0
Description:
Command:
ls -lrt
Description:
Report information about storage devices such as hard disks, flash drives etc.
Command:
lsblk
19
Description:
Command:
echo $?
Description:
Command:
info
Description:
Command:
cal -y
Description:
Command:
20
service --status-all
Description:
Command:
date +%T
Description:
Tells when the user last logged on and off and from where.
Command:
last -1 username
Description:
Command:
ls -X
Description:
21
Command:
man pwd
Description:
Command:
pstree
Description:
Command:
reset
Description:
Command:
date -d fri
22
Description:
Command:
du -a
Description:
Command:
acpi
Description:
Command:
cd ../..
Description:
Command:
cd -
23
Description:
Command:
help
Description:
Command:
last yourusername
Description:
Command:
mkdir myfiles
Description:
Command:
24
rmdir myfiles
Description:
Command:
passwd -d root1
Description:
Command:
sudo su root1
Description:
Command:
logout
Description:
25
Command:
useradd "root1"
Description:
Command:
passwd "root1"
Description:
Command:
!!
Description:
Command:
whoami
26
Description:
Command:
logname
Description:
Command:
uname
Description:
Command:
uname -v
Description:
Command:
uname -o
27
Description:
Command:
uname -m
Description:
Command:
uname --version
Description:
Command:
uname -r
Description:
Command:
28
uname -n
Description:
Command:
netstat -a
Description:
Command:
netstat -at
Description:
Command:
netstat -au
Description:
29
Command:
netstat -I
Description:
Command:
netstat -It
Description:
Command:
netstat -lu
Description:
Reveal all the information about the current user (user id, username, group id, group name etc.).
Command:
id
30
Description:
Reveal all the information about the user "root1" (user id, username, group id, group name etc.).
Command:
id root1
Description:
Command:
arch
Description:
Command:
fc-list
Description:
Command:
31
Description:
Command:
Description:
Command:
Description:
Command:
Description:
Command:
32
apt update httpd
Description:
Command:
Description:
Command:
Description:
Command:
date --help
Description:
33
Command:
ss -tup
Description:
Command:
ss -tupl
Description:
Command:
netstat -lx
Description:
Command:
ifconfig
34
Description:
Command:
ifconfig -a
Description:
Command:
Description:
Tells you how many lines, words, and characters there are in a file (1.txt).
Command:
wc 1.txt
Description:
Command:
gzip 1.txt
35
Description:
Command:
gunzip 1.txt
Description:
Command:
cat 1.txt
Description:
Display calendar.
Command:
ncal
Description:
Command:
36
rm 1.txt
Description:
Command:
mv 1.txt 0.txt
Description:
Command:
cp 1.txt 0.txt
Description:
Command:
touch test.txt
Description:
37
Command:
tail 1.txt
Description:
Command:
tail -n N 1.txt
Description:
Command:
wc -w 1.txt
Description:
Command:
wc -m 1.txt
38
Description:
Command:
wc -L 1.txt
Description:
Print information about usb ports, graphics cards, network adapters etc.
Command:
lspci
Description:
Command:
less 1.txt
Description:
Command:
cal -3
39
Description:
Compare the contents of three files (1.txt, 2.txt, 3.txt) line by line.
Command:
Description:
Command:
Description:
Command:
Description:
Prints the CRC checksum and byte count for the file "myfiles.txt".
Command:
40
cksum myfiles.txt
Description:
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
41
Command:
Shortcuts:
Description:
Writes contents of a file (0.txt) to output, and prepends each line with line number.
Command:
nl 0.txt
Description:
Command:
mkdir test
cd test
pwd
touch test1.txt
42
Description:
Gather information about hardware components such as CPU, disks, memory, USB controllers
etc.
Command:
sudo lshw
Description:
Command:
sudo fdisk -l
Description:
Displays the line (good morning) in which the string (good) is found in the file (1.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt) using for loop.
43
Command:
Description:
Search for files (test.txt, test1.txt, test2.txt, test.php, test.html) in a directory as well as its sub-
directories.
Command:
find test*
Description:
Command:
stat 1.txt
###
| Command | Description |
|: | : |
| vi | Open vi editor |
| i | Go to Insert mode |
| | |
| a =20; b =64; | |
| print (a + b); | |
| Hit Escape to return to Normal mode. |
| :w hello.py | Save text |
| :q | Quit |
| python hello.py |Print the output:84 |
Description:
44
Download the file (file.txt) from url "http: //website.com/files/file.txt".
Command:
wget http://website.com/files/file.txt
Description:
Command:
hostid
Description:
Command:
file myfiles.txt
Description:
Command:
45
Description:
Command:
Description:
Command:
hostname -i
Description:
Command:
Description:
46
Command:
whatis cal
###
| Command | Description |
|: | : |
| vi | Open vi editor |
| i | Go to Insert mode |
| Type some text. | |
| Hit Escape to return to Normal mode. |
| :w test.txt | Save text |
| :q | Quit |
| :q! |Quit without saving |
###
| Command | Description |
|: | : |
| vi | Open vi editor |
| i | Go to Insert mode |
| $name = "Paul"; | |
| print "$name"; | |
| Hit Escape to return to Normal mode. |
| :w hello.pl | Save text |
| :q | Quit |
| perl hello.pl |Print the output: Paul |
###
| Command | Description |
|: | : |
| vi | Open vi editor |
| i | Go to Insert mode |
| echo "What is your name?" | |
| read PERSON | |
| echo "Hello, $PERSON" | |
| Hit Escape to return to Normal mode. |
| :w hello.sh | Save text |
| :q | Quit |
| sh hello.sh | Output: |
| | What is your name? |
| | If you enter: Zara Ali |
| | Hello, Zara Ali |
Description:
Check the network connectivity between host (your connection) and server (Google server).
47
Command:
ping google.com
Description:
Command:
whereis cal
427
412
48
cd /etc && ls
/bin/bash
49
[manju@localhost ~]$ prefix=John
a=5;echo $a
Hello World
touch myfiles.txt
1000
50
echo $HISTFILESIZE
1000
file1.txt
file1.txt
file1.txt
file1.txt
file23.txt file34.txt
51
[manju@localhost ~]$ ls test[5A].txt
testA.txt
testA.txt
file23.txt file34.txt
*
List all .txt files starting with a
[manju@localhost ~]$ ls [a-z]*[0-9].txt letter and ending in a number
52
ls ?????
ls [fF]*[3A].txt
# List all .txt files that start with f or F and end with 3 or A
ls f[iR]*[0-9].txt
# List all .txt files that start with f have i or R as second character and end in a number
ls [!f]*.txt
# List all .txt files that do not start with the letter "f"
Einstein36
Hilbert36
Lucy6 Lucy8
Hawking3 Hawking6
53
[manju@localhost ~]$ who | cut -d' ' -f1 | sort
Display a sorted list
manju of logged on users
manju
Display a sorted
[manju@localhost ~]$ who | cut -d' ' -f1 | sort | uniq list of logged on
root:x:0:0:root:/root:/bin/bash
manju:x:1000:1000:su,root,yopp,hhhhh:/home/manju:/bin/bash
# List of all filenames in /etc that contain the string "conf" in their filename
54
90% of the public cloud workload is run on Linux distros.
import os
os.system('ls')
current directory
subprocess.call ('ls')
59
428
55
Command:
last reboot
Description:
Command:
dmesg
Description:
Displays the messages from the kernel ring buffer (a data structure that records
messages related to the operation of the kernel)
Command:
cat /proc/cpuinfo
Description:
56
Command:
cat /proc/meminfo
Description:
Command:
lspci -tv
Description:
Command:
lsusb -tv
Description:
57
Command:
free -h
Description:
Display free and used memory (-h for human readable, -m for MB, -g for GB)
Command:
mpstat 1
Description:
Command:
vmstat 1
Description:
58
Display virtual memory statistics
Command:
iostat 1
Description:
Command:
watch df -h
Description:
Command:
ps -ef
Description:
59
Display all the currently running processes on the system
Command:
ip a
Description:
Command:
dig wikipedia.org
Description:
Command:
host wikipedia.org
Description:
60
Display the IP address details of the specified domain (wikipedia.org)
Command:
netstat -nutlp
Description:
Display listening Transmission Control Protocol (TCP) and the User Datagram
Protocol (UDP) ports and corresponding programs
Command:
rpm -qa
Description:
Command:
Description:
Command:
61
yum info httpd
Description:
Command:
du -ah
Description:
Display disk usage for all files and directories in human readable format
Command:
du -sh
Description:
Command:
62
cd /etc
Description:
Command:
ps -A
Description:
List the status of all the processes along with process id and PID
Command:
#include <stdio.h>
int main()
{
printf("Hello world\n"); Hello.c
return 0;
}
gcc Hello.c
63
Description:
Command:
#include <iostream>
int main()
{
std::cout << "Hello world!"; Hello.cpp
return 0;
}
g++ Hello.cpp
Description:
Command:
tty
Description:
64
Command:
javac MyClass.java
Description:
Compile the Java program saved in MyClass.java file using javac compiler
Command:
od -b myfiles.txt
Description:
Command:
od -c myfiles.txt
65
Description:
Command:
od -An -c myfiles.txt
Description:
Displays the contents of myfiles.txt file in character format but with no offset
information
Command:
Description:
If the file myfiles.txt has 123 lines, the csplit command would create four files: the xx00 file
would contain lines 1−12, the xx01 file would contain lines 13−61, the xx02 file would contain
Command:
66
md5sum myfiles.txt
Description:
Prints a 32-character (128-bit) checksum of myfiles.txt file using the MD5 algorithm
Command:
more myfiles.txt
Description:
Command:
sha1sum myfiles.txt
Description:
Command:
67
shred myfiles.txt
Description:
Overwrites the myfiles.txt file repeatedly − in order to make it harder for even very
expensive hardware probing to recover the data
Command:
cat myfile.txt
01. Einstein
02. Newton
03. Maxwell
04. Tesla
05. Edison
tac myfile.txt
05. Edison
04. Tesla
03. Maxwell
02. Newton
01. Einstein
Description:
68
Command:
uniq myfiles.txt
Description:
Command:
chkconfig --list
Description:
Displays a list of system services and whether they are started (on) or stopped
(off) in run levels 0−6
Command:
halt -p
Command:
Description:
xdg-open myfiles.txt
442
69
Command:
lastlog
Description:
Prints the details of the last login (login-name, port and last login time)
Command:
lastlog -t 1
Description:
Command:
lastlog -u manju
Description:
70
Command:
cat /etc/passwd
more /etc/passwd
less /etc/passwd
getent passwd
Description:
Command:
tail -5 /etc/passwd
head -5 /etc/passwd
71
Description:
Command:
Description:
Command:
chage -l manju
Description:
List the password and its related details for a user (manju)
72
Command:
chage -M 10 manju
Description:
Command:
Description:
Command:
chage -I 10 manju
Description:
73
cat /etc/hostname
→ localhost.localdomain
hostname
→ localhost.localdomain
nmtui
yum check-update
# Check whether any updates are available for your installed packages
ls /etc
ls /bin /sbin
ls -al ~
# List all the files (including hidden files) in the home directory
ls -lh /boot
74
mkdir ~/mydir
rm -i file.txt
If we type "yes"
file.txt is removed
If we type "no"
ls
ls
75
Command:
ftp 192.168.42.77
Description:
Command:
arp -a
Description:
Lists all the peers connected at various interfaces along with their MAC
Command:
dnsdomainname
Description:
76
Display the system's DNS domain name
Command:
domainname
Description:
Command:
Output: SGVsbG8gV29ybGQhCg==
Description:
Command:
Description:
77
Decode (SGVsbG8gV29ybGQhCg==) to text (Hello World!)
Command:
fc-cache -f -v
Description:
Command:
cat 1.txt
Einstein
Newton
Albert
fmt 1.txt
Description:
78
df -h | sort -rnk 5 | head -3 | \
awk '{ print "Partition " $6 "\t: " $5 " full!" }'
ls *.xml
1.xml 2.xml
1.xml
2.xml
[manju@localhost ~]$ ls
12.txt 2.xml.md Documents file34.txt Music Pictures tree.cpio
79
[manju@localhost ~]$ df -h /
Check the actual
Filesystem Size Used Avail Use% Mounted on used space on the
/dev/sda3 18G 5.2G 13G 29% / current root device
less /proc/modules
totals in megabytes
Mon Jul 18 23:17:47 PDT 2022 Print the date 3 months and 1 day ago from the current date
Fri Apr 22 23:20:01 PDT 2022 Print the date 3 days in the future from now
Hello World
Aello World
80
[manju@localhost ~]$ fgrep 'He' myfiles.txt
Hello World Look for the string "He" in the file "myfiles.txt"
Command:
lsattr
Description:
Command:
cp {*.txt,*.md} ~
Description:
Copy the files ending with .txt or .md to the user's home directory
Hello World
Hello World
ls file*
ls *file
81
cat phy.txt
fmt -w 1 phy.txt
Albert
Einstein
was
a
German-born
theoretical
physicist,
widely
acknowledged
to
be
one
of
the
greatest
physicists
of
all
time.
Einstein
is
known
for
developing
82
the
theory
of
relativity,
but
he
also
made
important
contributions
to
the
development
of
the
theory
of
quantum
mechanics.
cat phy.txt
fold -w 20 phy.txt
83
a German-born theor
etical physicist, wi
dely acknowledged to
be one of the great
est physicists of al
l time. Einstein is
known for developing
the theory of relat
ivity, but he also m
ade important contri
butions to the devel
opment of the theory
of quantum mechanic
s.
Command:
traceroute google.com
Description:
Prints the route that a packet takes to reach the Google (172.217.26.206) host
from the local machine
Command:
cat 1.txt
84
Einstein
Newton
Albert
gzip 1.txt
zcat 1.txt.gz
Einstein
Newton
Albert
Description:
Command:
Description:
85
Command:
ss | less
Description:
Command:
ss -aA tcp
Description:
Command:
ss -aA udp
Description:
86
Command:
ss -lnt
Description:
Command:
ss -ltp
Description:
Command:
ss -s
Description:
87
Command:
ss -tl6
Description:
Command:
ss -tl -f inet
Description:
Command:
Description:
88
Command:
pmap 3244
Description:
Command:
Description:
Command:
apropos editor
Description:
Display information about the editing programs that are available on a system
89
Command:
apropos pstree
Description:
Provide information about the pstree command (which displays the names of the
processes currently on the system in the form of a tree diagram)
The apropos command is useful when you know what you want to do, but you have no idea what command
you should be using to do it. If you were wondering how to locate files, for example, the commands
apropos find
and
apropos locate
basename /etc/passwd
Output: passwd
basename /usr/local/apache2/conf/httpd.conf
90
Output: httpd.conf
echo a b c d e f| xargs
Output: a b c d e f
echo a b c d e f| xargs -n 3
a b c
d e f
Command:
env
Description:
Command:
91
printenv HOME
Description:
cat score.txt
Albert-30
John-50
William-80
Stephen-20
Justin-40
30
50
80
20
40
Albert
John
William
Stephen
Justin
92
cat 1.txt
Hello World
cat 2.txt
Computer Program
cat 1.txt
Hello World
cat 2.txt
Computer Program
93
Command:
rev 1.txt
Description:
cat 3.txt
22
33
11
77
55
sort 3.txt
11
22 sorts numeric values in 3.txt file and displays sorted output
33
55
77
94
cat 1.txt
Hello World
cat 5.txt
zz
zz
yy
yy
yy
xx
uniq 5.txt
95
cat 6.txt
Einstein
Newton
Tesla
nl 6.txt
Command:
ls -l *.txt
Description:
The thing with Linux is that the developers themselves are actually customers too: that has
always been an important part of Linux.
Linus Torvalds
96
ls /proc/bus/
[ 2.269581] ata1: PATA max UDMA/33 cmd 0x1f0 ctl 0x3f6 bmdma 0x1060 irq 14
[ 2.269585] ata2: PATA max UDMA/33 cmd 0x170 ctl 0x376 bmdma 0x1068 irq 15
cat /proc/ioports
cat 1.txt
[manju@localhost home]$ echo $-
Albert
himBH
cat 2.txt
Einstein
7890abcdefgh
/home/manju
/home
97
[manju@localhost home]$ w | cut -d " " -f 1 - | grep -v USER | sort -u
Einstein
25
[manju@localhost ~]$ ls
98
ls -ldh * | grep -v total | \
awk '{ print "Size is " $5 " bytes for " $9 }'
99
Linux Unix
Source code is accessible to the general public Source code is not accessible to anyone
Uses Graphical User Interface with an optional Uses Command Line Interface
Command Line Interface
Command:
echo $SHELL
Description:
Command:
echo $0
Description:
Display the name of the currently running process ($0 is the name of the running process).
If you use it inside of a shell then it will return the name of the shell. If you use it inside of a
script, it will return the name of the script
100
Command:
echo *
Description:
Command:
ps -p $$
Output:
Description:
Print the process ID of the current shell ($$ is the process ID of the current shell)
Command:
101
466
cat /etc/shells
Description:
List shells
Command:
echo m*
Description:
Display the files in the current folder that start with the letter "m".
Command:
last
Description:
List last logins of users and what happened such as "shutdown" or "crash" etc.
Command:
echo ~
Command:
Description:
102
bzip2 -k phy.txt
Description:
phy.txt → phy.txt.bz2
Command:
bzip2 -d phy.txt.bz2
Description:
phy.txt.bz2 → phy.txt
Command:
bzcat phy.txt.bz2
103
Description:
Command:
bunzip2 phy.txt.bz2
Description:
Command:
crontab –l
Description:
104
cp /dev/null phy.txt
Description:
Command:
Description:
Command:
105
nohup ping google.com > log.txt &
Description:
pgrep -a ping
Output:
kill 3858
pgrep -a ping
Output:
Command:
ls -la /home
106
Description:
Command:
sudo shutdown 2
Description:
Command:
shutdown -c
Description:
Command:
pr 36.txt
107
Description:
Display the contents of the file (36.txt) one page after the other
Command:
stty -a
Description:
Command:
ls -1
Description:
Command:
108
yes John
Description:
Command:
vdir
Description:
List files and directories in the current directory (one per line) with details
Command:
who -b
Description:
109
Command:
ls -al *.txt
nano phy.txt
Description:
# Open phy.txt with vim Display all .txt files, including its individual permission.
vim phy.txt
Command:
uname -i
Description:
Command:
uname -p
Description:
Command:
cat /proc/interrupts
Description:
w --ip-addr
110
# Displays information regarding the users currently on the machine, login time, IDLE time,
TTY and CPU time
Output:
w –short
# Omits CPU time and login information
Output:
Command:
findmnt
Description:
Command:
111
ip addr show
Description:
Command:
netstat -pnltu
Description:
Command:
journalctl
Description:
Command:
112
sudo systemctl status network
Description:
Command:
Description:
Command:
Description:
Command:
113
sestatus -b
Description:
Command:
getenforce
Description:
Security-Enhanced Linux (SELinux) is a security architecture for Linux systems that allows
administrators to have more control over who can access the system
setenforce 0
114
getenforce
Output:
Permissive
setenforce 1
getenforce
Output:
Enforcing
115
[manju@localhost ~]$ let a="36 + 5" ; echo $a
41
25
15
100
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
116
Command:
Description:
Command:
Description:
Command:
Description:
117
Command:
sestatus
Description:
Display the current status of the SELinux that is running on your system
Command:
ps -aef
Description:
Command:
sar
Description:
118
Display System Activity Report
Command:
ulimit
Description:
Output:
Unlimited The current user can consume all the resources the current system supports
Hard resource limit: The physical limit that the user can reach.
Soft resource limit: The limit that is manageable by the user (its value can go up to the
hard limit)
Command:
119
ulimit -a
Description:
Command:
ulimit -s
Description:
Command:
ulimit -e
Description:
120
Command:
ulimit -u
Description:
Command:
ulimit -v
Description:
Command:
ulimit -n
Description:
121
Command:
man limits.conf
Description:
Command:
sar -V
Description:
Command:
sar -u 2 5
Description:
122
Command:
Description:
Report about network interface, network speed, IPV4, TCPV4, ICMPV4 network traffic and errors
Command:
sar -v 1 3
Description:
Report details about the process, kernel thread, i-node, and the file tables
Command:
sar -S 1 3
Description:
123
Command:
sar -b 1 3
Description:
Report details about I/O operations like transaction per second, read per second, write per second
Command:
Description:
Command:
Description:
124
firewalld is a firewall management tool for Linux operating systems
Command:
firewall-config
Description:
firewall-cmd
Command:
firewall-cmd --list-all-zones
Description:
Command:
125
firewall-cmd --get-default-zone
Description:
Command:
firewall-cmd --list-services
Description:
Command:
firewall-cmd --list-ports
Description:
Command:
126
firewall-cmd --zone=work --list-services
Description:
Command:
Description:
Provides information about the route that Internet traffic takes between the local
system and a remote host (google.com)
Command:
Description:
127
Samba is client/server technology that implements network resource sharing across
operating systems. With Samba, files and printers can be shared across Windows,
Mac and Linux/UNIX clients.
Command:
Description:
Command:
Description:
Command:
128
unzip q.zip
Description:
zipcloak q.zip
-----------------------------------------------------------------------------
# zipcloak prompts you for a password, and then ask you to confirm it:
Enter password:
Verify password:
----------------------------------------------------------------------------
unzip q.zip
# When you try to unzip the q.zip file, it prompts you for the password before
allowing you to extract the file (q.txt) it contains
129
Command:
zgrep -l "Einstein" *
Description:
Display the names of the files with the word (Einstein) present in it
Command:
Description:
Split q.zip file to create a sequence of zipfiles (q1.zip, q2.zip…..) − each no larger
than 1048576 bytes (one megabyte)
You could concatenate (q1.zip, q2.zip…..) into a new file, w.zip, with the
command:
130
Command:
mtr google.com
Description:
Test the route and connection quality of traffic to the destination host google.com
Command:
route
Description:
Command:
131
Description:
Command:
Description:
Command:
ss -ta
Description:
Command:
132
ss -to
Description:
Command:
type -a alias
Description:
# Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year.
# Difference between %B and %b is, %B will print full month name while %b will print abbreviated month
name.
133
echo "We are in the month = $(date +%B)"
# Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday
name.
134
echo "tomorrow = $(date -d "tomorrow")"
# Find what is the date and time before 10 days from now.
echo "Before 10 days = $(date -d "tomorrow -10 days")"
Command:
ls -lai /
Description:
Command:
sudo du --inode /
Description:
135
Get the total number of inodes in the root directory
Command:
Description:
Get the list of all clients connected to HTTP (Port 80) or HTTPS (Port 443)
Command:
Description:
Command:
Description:
136
Install PuTTy on CentOS
Command:
Description:
Command:
Description:
Command:
137
Description:
Command:
Description:
Command:
ss -ua
Description:
Command:
138
ss -lu
Description:
Command:
ss -p
Description:
Command:
ss -4
Description:
139
Command:
ss -6
Description:
Command:
Description:
−Dennis Ritchie
140
[manju@localhost ~]$ echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
z y x w v u t s r q p o n m l k j i h g f e d c b a
[manju@localhost ~]$ echo {05..12} 005 006 007 008 009 010
05 06 07 08 09 10 11 12
mkdir 20{09..11}-{01..12}
12 11 10 9 8 7 6 5
12 11 10 09 08 07 06 05
x1 x2 x3 y1 y2 y3 z1 z2 z3
0 2 4 6 8 10
afkpuz
141
[manju@localhost ~]$ ls *.txt; echo $_
Albert,Bob
Bob
Bob,John
W X Y Z
W X Y Z
142
[manju@localhost ~]$ let x=20+7; echo "The value of \"x\" is $x."
x = 101
25 # 5 * 5
readelf -h /bin/bash
143
[manju@localhost ~]$ echo -e "\033[4mAlbert Einstein.\033[0m"
Albert Einstein.
Albert Einstein.
Albert Einstein
Albert Einstein
Albert Einstein
13
13
5 5
144
Command:
Description:
Command:
history -c
Description:
Command:
ping -c 5 www.google.com
Description:
145
# count number of lines in each .txt file
ls *.txt | xargs wc -l
ls *.txt | xargs wc -w
ls *.txt | xargs wc -c
ls *.txt | xargs wc
Command:
lslogins –u
Description:
146
Command:
Description:
List all loaded services on your system (whether active; running, exited or failed)
Command:
systemctl --type=service
Description:
List all loaded services on your system (whether active; running, exited or failed)
Command:
147
Description:
Command:
Description:
Command:
Description:
List all running services (i.e., all loaded and actively running services)
Command:
148
systemctl --type=service --state=running
Description:
List all running services (i.e., all loaded and actively running services)
nc -v -w 2 z 192.168.56.1 22
nc -v -w 2 z 192.168.56.1 22 80
nc -v -w 2 z 192.168.56.1 20-25
Command:
cat /etc/resolv.conf
Description:
149
Command:
less /etc/resolv.conf
Description:
Command:
Description:
Monitor mount, unmount, remount and move actions on a directory (i.e., on /mnt/test)
Command:
uptime -p
Description:
150
Command:
uptime –s
Description:
Command:
uptime –h
Description:
Command:
Description:
151
Command:
crontab -r
Description:
ADD=$(( 1 + 2 ))
echo $ADD
3
MUL=$(( $ADD * 5 ))
echo $MUL
15
SUB=$(( $MUL - 5 ))
echo $SUB
10
DIV=$(( $SUB / 2 ))
echo $DIV
5
MOD=$(( $DIV % 2 ))
echo $MOD
152
Command:
Description:
echo '3+5' | bc
8
(a + b) = 8
Command:
factor 10
Description:
153
Command:
ps -e
Description:
Command:
ps -x
Description:
Command:
ps -fU manju
Description:
154
Display a user's processes by user name (manju)
Command:
ps -fu 1000
Description:
Command:
ps -U root -u root
Description:
Display every process running with root user privileges (real and effective ID)
155
date +%d\-%m\-%Y
date +%m\/%d\/%Y
ls -a ~/
2350
10
23500 × = 2350
100
shuf -i 1-5 -n 5
156
[manju@localhost ~]$ shuf -i 1-5 -n 5 | awk '{ sum+=$1;print $1} END {print "Sum";print sum}'
Sum
15
./1.zip
Find File with .zip extension
./––encrypt.zip
./my.zip
157
find -type f -newermt 2021-03-01
Shell Scripting
if [ 15 -gt 25 ]
then
else False
echo "False"
fi
for i in 1 2 3 4 5 # Output:
do Albert
done Albert
Albert
158
if test 5 -eq 6
then
False
else
echo "False"
fi
help cd
159
help -s cd
Create the myfiles directory, and set its file mode (-m) so that
all users (a) may read (r), write (w), and execute (x) it.
whatis -w make*
who -d -H
finger -s manju
last -F
# Search for all .mp3 and .txt files on your system and ignore case
160
systemctl -l -t service | less
locate "*.txt" -n 20
locate -c [.txt]*
ls -l . | egrep -c '^-'
# Check the top 10 files that are eating out your space
161
mpstat
mpstat -P ALL
mpstat 1 5
Albert Einstein
fdisk -s /dev/sda
162
Command:
Description:
Command:
locale
Description:
Command:
locale -a
Description:
163
Display a list of all available locales
cat score.txt
Justin-40
JUSTIN-40
JUSTIN-40
cat domainnames.txt
164
cat domainnames.txt
www.google.....com
www.fb.com
www.mactech.Com
My UID is 0
My
UID
is
0
myw3schools.com:=>Linux-Books,Src,Tutorials
Command:
165
!sud
Description:
Command:
!sudo
Description:
Command:
Description:
166
Generate a compact list of all Linux user accounts on the system
Command:
Description:
Command:
Description:
mkdir /tmp/DOCUMENTS
Command:
167
find . -type f -perm 0777 -print
Description:
Command:
Description:
Command:
Description:
Command:
168
find / -perm /u=r
Description:
Command:
Description:
albert
Convert text from upper case to lower case
Command:
169
find . -type f -name "phy.txt" -exec rm -f {} \;
Description:
Description:
Command:
Description:
170
To find and remove multiple .mp3 files
Command:
Description:
Command:
Description:
Phone number:
Remove all digits from string
Command:
171
find / -mtime 50
Description:
Command:
find / -atime 50
Description:
Command:
Description:
172
Find Changed Files in Last 1 Hour
Command:
Description:
Command:
Description:
Command:
type cat
Description:
Command: Identifies whether the "cat" command is a shell built-in command, subroutine, alias, or keyword.
173
find / -size 50M
Description:
Command:
Description:
Command:
Description:
Find all .mp3 files with more than 10MB and delete them
174
ls -l --color
info df
ls /usr/include
ls /usr/local
ls /usr/bin/d*
# List all files whose names begin with the letter "d" in the /usr/bin directory
hello.cpp hello.f99
175
ls /usr
ls ~ /usr
176
Command:
cat /proc/sys/fs/file-max
Description:
Command:
ulimit -Hn
Description:
Command:
ulimit -Sn
Description:
177
Command:
timedatectl status
Description:
Command:
timedatectl list-timezones
Description:
Command:
178
Description:
Command:
Description:
Command:
swapon --summary
Description:
Command:
179
cat /proc/swaps
Description:
script history_log.txt
exit
Command:
dir -shl
Description:
180
List files and their allocated sizes in blocks
Command:
less /proc/sys/dev/cdrom/info
Description:
cat date.txt
"Don't write better error messages, write code that doesn't need them."
− Jason C. McDonald
181
[manju@localhost ~]$ echo hello > 1.txt
hello
world
program
hello
world
program
hello
world
program
strings /usr/bin/passwd
ls -lrS /etc
182
cat /etc/passwd >> myfiles.txt
# Create a file named myfiles.txt that contains the contents of myfiles.txt followed by the contents of /etc/passwd
/etc/idmapd.conf /etc/pbm2ppa.conf
/etc/ipsec.conf /etc/pnm2ppa.conf
ls /dev/sd*
183
echo \$USER
# $USER
2+2 =4
echo Hello && echo World
12+12 =24
Hello
World
echo Hello ; echo World
Hello
World
Hello
World
It worked!
It failed!
pwd ; pwd
/home/manju
184
a=$(pwd)
echo "Current working directory is : $a"
/home/manju
Command:
echo *.jpeg
Description:
Command:
Description:
185
l
i
n
u
x
Command:
Description:
Output the files with respect of the user (root) owned files in the current directory
Command:
strace pwd
Description:
186
Command:
top -u manju
Description:
534
187
[manju@localhost ~]$ cat myfiles.txt
Hello World
Hello
World
# Find files that end in .txt in the current directory and all subdirectories
Tuesday 19-04-2022
# Print the number of .txt files in /etc and all its subdirectories
Hello World
Hello World
Hello World
188
[manju@localhost ~]$ echo Albert Einstein | sed 's/Albert/&&/'
AlbertAlbert Einstein
Albert EinsteinEinstein
Albertert
Albert Albert
Albert is Scientist
Albert is Scientist
Hello World
HeAo World
189
[manju@localhost ~]$ cat myfiles.txt
Hello World
HeAo World
Albert Einstein
0
True: 50 is greater than 15
1
False: 5 is not greater than 15
0
True: 5 is lesser than 15
true
false
190
[manju@localhost ~]$ [ 50 -gt 15 ] && echo true || echo false
true
false
[manju@localhost ~]$ [ 100 -gt 10 -a 100 -lt 150 ] && echo true || echo false
true
[manju@localhost ~]$ [ 100 -gt 10 -a 100 -lt 15 ] && echo true || echo false
false
191
Command:
uname –or
Description:
Command:
uname -a
Description:
Command:
cat /proc/version
Description:
Display some of your system information including the Linux kernel version
192
Command:
cat /etc/centos-release
Description:
Command:
fuser .
Description:
Displays the PIDs of processes currently accessing your current working directory
Command:
193
fuser -v -m .bashrc
Description:
Command:
Description:
Displays all the possible signals that can be used with the fuser tool
Command:
Description:
Sends the HUP signal to all processes that have your /boot directory open
194
Command:
ls -al
Description:
List all the files with the file permissions, the number of links to that file, the owner of the file, the group of the
file, the file size in bytes, the file's last modified datetime and the file name
Command:
195
Command:
Description:
Execute command "ls -al" and print the result to the standard output
Command:
Description:
Command:
Description:
196
Command:
Description:
Command:
Description:
Find all files in the current directory with .sh and .txt file extensions
Command:
Description:
Find all files in the current directory with .sh, .c and .txt file extensions
197
Description:
Command:
Description:
Command:
Description:
Find files that have more than 100 characters (bytes) in them.
Command:
198
Description:
Command:
Description:
Command:
Description:
Command:
199
ls -a
Description:
Command:
ls -F
Description:
Command:
ls -r
Description:
200
Command:
ls -lS
Description:
Command:
ls -i
Description:
Command:
ls --version
Description:
201
Command:
ls -l /tmp
Description:
Command:
ls -n
Description:
Command:
202
Description:
Command:
Description:
Command:
Description:
Command:
203
Description:
Command:
Description:
Command:
Description:
List all files modified between 6 and 15 days ago in the home directory.
Command:
204
find /home -type f -mtime +6 -mtime -15
Description:
Command:
Description:
Command:
Description:
205
Command:
Description:
Find and list files and directories together with their permissions.
Command:
Description:
Command:
ls -d */
Description:
206
Command:
ls --format=comma
Description:
Command:
ps -u manju
Description:
Command:
!c
207
Description:
Command:
dmidecode -t 0
Description:
Command:
dmidecode -t 4
Description:
Command:
gnome-system-log
208
Description:
Command:
ssh -V
Description:
Command:
ac –d
Description:
Command:
209
ac -p
Description:
Command:
ac -d manju
Description:
Command:
httpd -l
Description:
210
Command:
ps U $USER
Description:
Command:
df -Tha
Description:
Command:
netstat -tap
Description:
211
Command:
212
[manju@localhost ~]$ PS1="Please enter a command: "
April 2022
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
213
[manju@localhost ~]$ ls /etc/gdm List the contents of GDM configuration directory
ls /etc/gconf
ls /usr/share/gnome
ls /etc/rc.d
214
Important features of Linux Operating System
Linux Kernel
Manage access and use of the various peripherals that are connected to the computer.
215
[manju@localhost ~]$ cd /etc
/etc
[manju@localhost etc]$ cat /etc/hosts /etc/hosts contains hostnames with their ip address
216
ps -L 3315
[manju@localhost ~]$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24
29
Prints seven random numbers from zero to 100
85
15
ls -lg *.txt | awk '{ x += $5 } ; END {print "total bytes:" x }'
59
# Prints the total number of bytes used by all .txt files
19
81
217
Random-access memory Virtual memory
The internal memory of the CPU for storing A storage area that holds the files on your hard drive
data, program and program result. for retrieval when a computer runs out of RAM
Zombie: The process is terminated but information regarding the process still exists
Cron Anacron
A service that enables us to run scheduled jobs A service that only enables us to run scheduled jobs
in Linux/Unix systems every minute. in Linux/Unix systems on daily basis.
Command:
cat /etc/crontab
Description:
Command:
netstat --listen
218
Description:
A mirror copy of the original file A symbolic link to the original file
219
ls /bin
ls /boot
ls /dev
# List the device files − typically controlled by the operating system and the system administrators
ls /etc
mydir1 mydir4
ls /lib64
mydir2 mydir5
# List the System Libraries (64 bit)
mydir3
ls /proc
ls /sbin
ls /var/log
220
[manju@localhost ~]$ ls -l myfiles.txt
# Display files that are more than 1 day old − but less than 3 days old in the current directory
# Find files that start with the letter "s" and perform the command "ls" on them
eee
file1 file2
cc
b
[manju@localhost ~]$ NUMLOGINS=$(who | grep $USER | wc -l)
cc
[manju@localhost ~]$ echo You have $NUMLOGINS login sessions
eee
You have 2 login sessions
ffff
221
Command:
Description:
Remove read write and execute permissions on the file "myfiles.txt" for the group and others
Command:
Description:
Command:
!-3
Description:
linux-gnu
The current operating system you are using
222
Command:
df -i /dev/sda1
Description:
Command:
ls -il myfiles.txt
Description:
Command:
getfacl myfiles.txt
Description:
SSH (Secure Shell or Secure Socket Shell) is a network protocol that gives users and
system administrators a secure way to access a computer over an unsecured network.
223
3 standard streams in Linux:
Text terminal
Standard input
(stdin)
Keyboard Program
Standard output
(stdout)
Display
Standard error
(stderr)
Command:
du -sh /var/log/*
Description:
Command:
ldd /bin/cp
224
Description:
Command:
ldd -v /bin/cp
Description:
Command:
ldd -u /bin/cp
Description:
225
[manju@localhost ~]$ date; cal
April 2022
Su Mo Tu We Th Fr Sa
date command is executed
1 2 followed by a cal command
3 4 5 6 7 8 9
April 2022
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
226
[manju@localhost ~]$ a=`ls *.c`; echo $a
true
true
true
true
true
[manju@localhost ~]$ test 320 -eq 30 && echo true || echo false
false
false
[manju@localhost ~]$ test 320 -ne 30 && echo true || echo false
true
227
Command:
cat /proc/net/dev
Description:
Command:
cat /proc/mounts
Description:
Command:
telinit 0
Description:
cd /home
cd ..
228
iconv -l
ls -lSr | more
Command:
ls -lh
Description:
Display permissions
Command:
yum list
Description:
Command:
Description:
229
Command:
Description:
Command:
Description:
Command:
Description:
Clean Metadata
ip link show
ps -eafw
lsof -p $$
230
Command:
Description:
Find files in the /var directory that have not been accessed in the last 90 days
Command:
Description:
Search for core files in the entire directory tree and delete them as found without
prompting for confirmation
Command:
who -r
Description:
231
Bash script:
Description:
Delete all the files in the current directory that contains the word "linux"
Command:
Description:
sleep 5s
sleep 5h
sleep 5d
232
Command:
ln myfiles.txt hardF1
Description:
Command:
cat hardF1
Description:
Command:
ln myfiles.txt softF1
Description:
Command:
cat softF1
Description:
233
Foreground processes Background processes
Require a user to start them or to interact Run independently of a user.
with them.
Command:
ps -p 13
Description:
Command:
ulimit -f 100
Description:
Command:
lsmod
Description:
234
Find out what kernel modules are currently loaded
The path of a file or directory from the The path of a file or directory from the
root directory. present working directory.
Command:
Description:
Command:
Description:
Run a PHP statement from the command line without creating a file
Command:
php -a
Description:
235
Command:
du -h -d 1 /
Description:
Command:
Description:
Command:
man -f ls
Description:
man -a ls
man -k ls
# Allows users to search the short command descriptions and manual page names for ls command
man -w ls
236
cat /etc/redhat-release
ls ~
ls ../
Command:
ps -U root -u root
Description:
Command:
cal -1
Description:
Command:
cal -j
Description:
237
Command:
su
Description:
Command:
Description:
Command:
Description:
ps r
ps T
ps -f
# List processes along with the parent process ID associated with the current Terminal
238
ps -x
Command:
Description:
Command:
Description:
239
Command:
Description:
Command:
Description:
Command:
Description:
Command:
file /etc/passwd
Description:
240
Command:
wc /etc/passwd
Output:
46 91 2373 /etc/passwd
The /etc/passwd file has 46 lines, 91 words and 2373 letters present in it
Command:
Description:
Command:
Description:
Display all lines from /etc/passwd containing the string "root" with line numbers
Command:
Description:
241
Command:
Description:
Display all lines from /etc/passwd starting with the string "root" followed by colon
Command:
last | head
Description:
Displays information about the users who logged in and out of the system
lastb
du /etc/passwd
killall proc
wget https://repo.mysql.com/mysql80-community-release-el8-1.noarch.rpm
242
sudo yum localinstall https://repo.mysql.com/mysql80-community-release-el7-1.noarch.rpm
curl --version
curl -O http://website.com/myfiles.tar.gz
# Saved as myfiles.tar.gz
# Saved as files.tar.gz
exit 110
sudo -l
# know which commands are permitted and not permitted on the current host
243
Command:
echo -e "\thello\nworld"
hello
world
Difficulty to use
Disadvantages of Open Source Operating System:
Compatibility Issues
Command:
Description:
Command:
Description:
Find files in the /home directory which were modified more than 120 days ago
244
Samba enables Linux / UNIX machines to communicate with
date "+%s"
245
Command:
cd ../../..
Command:
Description:
List all the processes on the system containing the string 'xlogo'
abcdef
abc
def
246
Command:
Description:
List the files in /var larger than 1 megabyte but less than 1 gigabyte
Command:
ls -lhS
Description:
# Searches for all files in the /tmp directory named *.txt and deletes them
use of Linux
247
watch -n 5 tail -n 3 /etc/passwd
watch -t -n 1 date
# Search for files containing the string "hello computer" in the current directory
In Linux
(echo In Linux; exit 0) && echo OK || echo exit
OK
In Linux
(echo In Linux; exit 4) && echo OK || echo exit
exit
248
Command:
free -t -m
Command:
gnome-system-monitor
Description:
Displays what programs are running and how much processor time, memory and disk space are being used
lsblk -m
lsblk -S
249
Command:
ls -l ~
Description:
Command:
ls ./Documents
Description:
ls -R
compgen -c
# Displays the list of all commands which we can use in the command-line interface
hostnamectl
# Display system information including operating system, kernel and release version
250
Command:
find . -type f
Find files
Command:
find . -type d
Description:
Find directories
251
{ echo "Albert Einstein"; pwd; uptime; date; }
Albert Einstein
/home/manju
March 2022
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
/home/manju
shutdown -r
shutdown +0
shutdown -r +5
252
Command:
kill 12838
ss -t -r state established
Force the file system check during
Description: reboot
ss -t -r state listening
mtr google.com
253
ls -al --time-style=+%D | grep `date +%D`
mpstat -P 0
# Print processor statistics and helps to monitor CPU utilization on the system
# Assign full permission to the owner and read and write permission to group and others
chmod -x myfiles.txt
history 30
find ~ -empty
gzip -l *.gz
254
Command:
ps -efH | more
Command:
df -T
Description:
mkdir ~/temp
ls *py
chsh -l
ipcs -a
255
ipcs -q
Lists only message queues for which the current process has read access
ipcs -s
ipcs -m
quotastats
# Display the report of quota system statistics gathered from the kernel
rpcinfo
# Display all of the RPC (Remote Procedure Call) services of the local host
slabtop
tload
# Display a graph of the current system load average to the specified tty
256
cat /proc/devices
# Display the device drivers configured for the currently running kernel
cat /proc/dma
cat /proc/filesystems
cat /proc/kmsg
cat /proc/loadavg
ls /proc/net
ls /etc/udev
cat /proc/stat
cat /proc/uptime
257
Command:
poweroff -i -f
[2 = 2 ] ; echo $?
# 0 (logically TRUE)
[ 2 = 6 ] ; echo $?
# 1 (logically FALSE)
type echo
systemctl list-sockets
258
systemctl reboot
systemctl hibernate
loginctl user-status
# Display terse runtime status information of the user of the caller's session
loginctl session-status
ip route show
ip neigh
# Display the current content of the ARP (Address Resolution Protocol) cache tables
netstat -l --inet
259
Command:
atq
echo $$
echo $!
date --date="yesterday"
ls / | wc -w
260
sudo blkid
bin
etc
home
lib ls -l /etc/shadow
lib64 # Display the user password stored in an encrypted form and the password expiry data
media
root
run
sudo journalctl --since "2019-12-10 13:00:00"
sbin
# Display all the logs since 2019-12-10 13:00:00
srv
sys
tmp
journalctl -disk-usage
usr
261
Command:
ls -m
ls -Q
# List Unix Sockets # Lists all of the .desktop files in the current directory
ss --raw
tracepath www.google.com
# Traces a path to a network host (www.google.com) discovering MTU along the path
echo D*
# Lists all of the files and directories in the current directory whose name starts with letter D
262
echo $'I\'m a Linux Learner.'
echo $USER
echo -e "\033[0;32mGREEN"
GREEN
echo -e "\033[0;31mRED"
RED
Hello,
World!
echo "This is the list of directories and files on this system: $(ls)"
Documents
Downloads
Music
Pictures
Public
Templates
Videos
263
echo *s
echo [[:upper:]]*
# Print all files and folders that start by upper case character
→ 5
→ 12
echo Capital-{A,B,C}-Letter
echo {1..5}
→ 1 2 3 4 5
echo {A..Z}
→ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
echo x{P{1,2},Q{3,4}}y
264
echo The total price is $500.00
Su Mo Tu We Th Fr Sa → C:\WIK2N\LINUX_OS.EXE
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
March 2022 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
echo $(cal)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
265
sudo lsof -i -P -n | grep LISTEN
Check ports in use
sudo netstat -tulpn | grep LISTEN
sudo ss -tulw
266
[root@localhost manju]# ipcs -u
allocated queues = 0
segments allocated 4
pages swapped 0
used arrays = 0
allocated semaphores = 0
dmidecode -t 16
dmidecode -t baseboard
dmidecode -t bios
267
Command:
dmidecode -t system
Description:
Display the information about the manufacturer, model and serial number of the system
The Linux philosophy is 'Laugh in the face of danger'. Oops. Wrong One. 'Do it
yourself'. Yes, that's it.
Linus Torvalds
268
nmcli con show -a
netstat -r
nmap google.com
# Scan a hostname
nmap 193.169.1.1
# Scan a ip address
nmap --iflist
echo [![:digit:]]*
# Print all files and folders that are not beginning with a numeral
echo *[[:lower:]123]
# Print all files and folders ending with a lowercase letter or the numeral
echo g*
269
echo b*.txt
# Print all files and folders beginning with "b" followed by any characters and ending with ".txt"
echo [abc]*
# Print all files and folders beginning with either "a", "b" or "c"
netstat -t
netstat -x
# Display Information about all connections, listeners and shared endpoints for Network Direct
netstat -n
echo $LANG
→ AAA
270
echo "albert einstein" | tr a-z A-Z
→ ALBERT EINSTEIN
→ EEEEEE EEEEEEEE
Albert Eins
tein was a G
erman-born t
heoretical p
hysicist.
Albert
Einstein
was a
German-born
theoretical
physicist.
271
ls /usr/bin | pr -3 -w 65 | head
D Einstein
Hawking
Darwin
for i in {A..D}; do echo $i; done
file1.txt
file.txt
echo ${!BASH*}
# List all the variables in the environment with names that begin with BASH
bc <<< "6+6"
12
272
df -k
ls -alh
# Search for the files which were modified more than 90 days back
find / -size 0c
# Search all files and folders which are more than 1GB
df -a
df -i
273
du -ch *.png
ac
# Display the total amount of time users are connected to the system
ac --individual-totals
cancel
finger manju
chfn
finger -s manju
274
groups
id -nG
groupadd mygroup
groupdel mygroup
less /etc/group
getent group
userdel manju
# Change the owning group of the file test.txt to the group named "mygroup"
275
sudo depmod -a
# Generates a list of all kernel module dependences and associated map files
dirname /usr/bin
→ /usr
dirname /Desktop/root
→ /Desktop
# Count the number of lines in myfiles.txt which begin with the word 'Hello' or end with the word 'World'
ex myfiles.txt
expand myfiles.txt
# Expand the file myfiles.txt − changing tabs to spaces − and display on standard output
# Convert the tabs in the file myfiles.txt to 10 spaces each, and write the output to myfiles0.txt
276
expr 2 = 5
Returns 0 (false)
# 0
fc -l
!l
# Executes the most recently executed command that begins with the letter "l"
fc -e - l
# Executes the most recently executed command that begins with the letter "l"
fmt myfiles.txt
finger -p manju
# Wrap the lines of myfiles.txt to a width of 5 characters and writes the output to myfiles0.txt
# Performs a word count of all files in the current directory with the .txt extension
277
grep manju /etc/passwd
head myfiles.txt
# Display the first 10 lines of both myfiles.txt and myfiles0.txt − with a header before each that indicates the file name
head -n 5K myfiles.txt
head -n 4 *.txt
# Display the first 4 lines of every file in the working directory whose file name ends with the .txt extension
iostat
# Display listing of last logged in users and system last reboot time and date
278
last -x | less
last shutdown
ldd /bin/bash
less -N myfiles.txt
# View the file myfiles.txt − displaying a line number at the beginning of each line
ls *.{html,php,txt}
# List all files with .html, .php and .txt file extension
lsof -i 6
ls [aeiou]*
lsof -i -U
# List all open Internet, x.25 (HP-UX) and UNIX domain files
lsof -i 4 -a -p 555
# List all open IPv4 network files in use by the process whose Process ID is 555
279
xz myfiles.txt
xz -dk myfiles.txt.xz
# Create the directory "dir" and set its file mode so that all users may read, write and execute it
modinfo snd
# Display all available information about the "snd" Linux kernel module
more +3 myfiles.txt
# Display the contents of file "myfiles.txt" beginning at the first line containing the string "Hello"
netstat -g
# Display multicast group membership information for both IPv4 and IPv6
netstat -c
netstat -natp
280
netstat -rn
# Display the routing table for all IP addresses bound to the server
netstat -an
od -b myfiles.txt
od -Ax -c myfiles.txt
# Display the contents of "myfiles.txt" in ASCII character format − with byte offsets displayed as hexadecimal
trap -l
trap
yum grouplist
yum repolist
281
yum repolist all
cat dc.txt
1 .
2 ..
3 1.txt
4 2.txt
5 .bash_history
6 .bash_logout
7 .bash_profile
8 .bashrc
9 bio.txt
10 .cache
11 .config
12 Data.txt
13 Desktop
14 dir
15 Documents
282
printf "Hi, I'm %s.\n" $LOGNAME
→ abcdef
ps -eLf
ps axms
ps -eo euser,ruser,suser,fuser,f,comm,label
Get security information
ps axZ
ps -eM
Command:
pstree -h
Description:
Display all processes as a tree, with the current process and its ancestors highlighted
rm -- 1.txt
rm ./1.txt
# Delete "1.txt" file in the current directory
rm /home/manju/2.txt
283
ip route list
route -n
Hello, World!
cat hello.txt
Hello, World!
sfdisk -s
ls -d ~/.ssh
sha224sum myfiles.txt
# Display the SHA224 checksum of the "myfiles.txt" file in the current directory
284
sha256sum myfiles.txt
# Display the SHA256 checksum of the "myfiles.txt" file in the current directory
sha384sum myfiles.txt
# Display the SHA384 checksum of the "myfiles.txt" file in the current directory
sha512sum myfiles.txt
# Display the SHA512 checksum of the "myfiles.txt" file in the current directory
shutdown 8:00
shutdown 20:00
# Schedule the system to shut down in 15 minutes with the normal message alerting users that the system is shutting down
shutdown -P now
sleep 10
startx -- -depth 16
285
time cal
Hello World # Lists all fonts available to the default X server and display
xset q
Hello
World
yes | rm -i *.txt
w manju
286
What is Linux and why is it so popular?
Whether you know it or not you are already using Linux (the best-known and most-used open
source operating system) every day. From supercomputers to smartphones, the Linux operating
system is everywhere. As an operating system, Linux is a family of open source Unix-like
software based on the Linux kernel - that sits underneath all of the other software on a computer,
receiving requests from those programs and relaying these requests to the computer's hardware.
With regard to careers, it is becoming increasingly valuable to have Linux skills rather than just
knowing how to use Windows. In general, Linux is harder to manage than Windows, but offers
more flexibility and configuration options.
Every desktop computer uses an operating system. The most popular operating systems in use
today are: Windows, Mac OS, and LINUX. Linux is the best-known notoriously reliable and
highly secure open source portable operating system -- very much like UNIX -- that has become
very popular over the last several years -- created as a task done for pleasure by Linus Torvalds -
- computer science student at the University of Helsinki in Finland -- in the early 1990s and later
developed by more than a thousand people around the world.
Linux is fast, free and easy to use, that sits underneath all the other software on a computer −
runs your computer -- handling all interactions between you and the hardware i.e., whether
you're typing a letter, calculating a money budget, or managing your food recipes on your
computer, the Linux operating system (similar to other Operating Systems, such as Windows XP,
Windows 7, Windows 8, and Mac OS X) provides the essential air that your computer breathes.
Linux is the most important technology advancement of the twenty-first century and Licensed
under the General Public License (GPL) that Linux uses ensures that the software will always be
open to anyone and whose source code is open and available for any user to check, which makes
it easier to find and repair vulnerabilities and it power the laptops, development machines and
287
servers at Google, Facebook, Twitter, NASA, and New York Stock Exchange, just to name a
few. Linux has many more features to amaze its users such as: Live CD/USB, Graphical user
interface (X Window System) etc.
Why LINUX?
Although Microsoft Windows (which is the most likely the victim of viruses and malware) has
made great improvements in reliability in recent years, it considered less reliable than Linux.
Linux is notoriously reliable and secure and it is free from constant battling viruses and malware
(which may affect your desktops, laptops, and servers by corrupting files, causing slow downs,
crashes, costly repairs and taking over basic functions of your operating system) – and it keep
yourself free from licensing fees i.e., zero cost of entry ... as in free. You can install Linux on as
many reliable computer ecosystems on the planet as you like without paying a cent for software
or server licensing. While Microsoft Windows usually costs between $99.00 and $199.00 USD
for each licensed copy and fear of losing data.
288
Kernel
Kernel is the core part of Linux Operating System and interacts directly with hardware. It is
responsible for all major activities of the Linux operating system.
System Library
System libraries are special programs using which application programs accesses Kernel's
features.
System Utility
Portable
Open Source
Multi-User
Multiprogramming
Hierarchical File System
Security
Now Linux (successfully being used by several millions of users worldwide) has grown passed
the stage where it was almost exclusively an academic system, useful only to a handful of people
with a technical background. It provides more than the operating system: there is an entire
infrastructure supporting the chain of effort of creating an operating system, of making and
testing programs for it, of bringing everything to the users, of supplying maintenance, updates
and support and customizations, runs on different platforms including the Intel and Alpha
platform. Today, Linux is ready to accept the challenge of a fast-changing world to do various
289
types of operations, call application programs etc. Since the hiring focus is shifting more
and more toward DevOps type skills, a Linux skill set will be the types of things that will
make you very deployable.
[manju@localhost ~]$ ls
cat /etc/profile
cat /etc/bashrc
cat .bash_profile
290
[manju@localhost ~]$ date
[manju@localhost ~]$ x
290 Display the number of the current command in the history list
1000
Display the Effective user ID
291
[manju@localhost ~]$ PS1="\d"
Hello
World
Hello \ World
292
Directory Function
/ The top-level directory of a Linux system that holds all files, device
/usr Contains the commands and files that the system uses
/var/spool Contains spooled files, such as those produced for network transfers and
printing operations
/sbin Contains commands for system administration used to boot the system
/dev Holds file interfaces for devices like printers and terminals
293
find / -user manju -print
ls /usr/share/X11
ls /etc/X11
ls /etc/gdm
ls /usr/share/gdm
# Display the contents of GDM configuration directory for default settings and themes
ls /etc/gconf
ls /usr/share/gnome
ls /usr/share/doc/gnome*
# Display the contents of Documentation for various GNOME packages, including libraries
294
ls /usr/share/icons
ls /etc/cron.d
# List the directory with numerous crontab files that is only accessible to the root user
ls /etc/cron.hourly
ls /etc/cron.daily
ls /etc/cron.weekly
ls /etc/cron.monthly
ls /etc/mtab
ls /etc/services
# List the services run on the system and the ports they use
295
ls /etc/cups
ls /proc/net
free -s 3
# Display the current usage status of Memory continuously after regular interval
whereis -b ls
whereis -m ls
whereis -s ls
296
watch -t -n 1 date
Albert
du -sh * --time
# Check each file's size and the date and time it was last edited
dmidecode -s system-serial-number
ls -aril
du -sch *
# Display the sum of size of all files and folders in present directory
297
cat /proc/cpuinfo | grep processor | wc -l
dirs
blkid -i /dev/sda
# Display information about available block devices
crontab -e
298
[manju@localhost ~]$ hostname -I
192.168.6.131 192.168.122.1
badblocks -s /dev/sda
lsof -u manju
sudo shutdown -r 2
albert
ALBERT
299
nmcli d
# Search for a line which will start with alphanumeric characters in "myfiles.txt"
# Search for a line which will start with alpha characters in "myfiles.txt"
# Search for a line which will start with blank characters in "myfiles.txt"
# Search for a line which will start with digit characters in "myfiles.txt"
# Search for a line which will start with lowercase letters in "myfiles.txt"
# Search for a line which will start with punctuation characters in "myfiles.txt"
# Search for a line which will start with graphical characters in "myfiles.txt"
# Search for a line which will start with printable characters in "myfiles.txt"
300
grep "^[[:space:]]" myfiles.txt
# Search for a line which will start with space characters in "myfiles.txt"
# Search for a line which will start with uppercase letters in "myfiles.txt"
# Search for a line which will start with hexadecimal digits in "myfiles.txt"
vmstat -a
vmstat -s
vmstat -f
vmstat -D
vmstat -d
301
[manju@localhost ~]$ free -h --total
hostname -s
Display the short version of the hostname
hostname --short
hostname --all-ip-addresses
date -r /etc/hosts
Albert Einstein
Elsa Einstein
Albert Einstein
302
[manju@localhost ~]$ cat 12.txt
Albert Einstein
Elsa Einstein
1 Albert Einstein
2 Elsa Einstein
Albert Einstein
Albert Einstein$
# Search for the words "but" and "is" in the phy.txt file
# Search for the words "but", "is" and "of" in the phy.txt file
303
echo "The system will be shutdown in 10 minutes." | wall
Albert Einstein
ss --all
ss --listen
ss -t state listening
192.168.6.131
System's IP address
304
yum erase httpd
# Uninstall apache
4 = 4 + 0 + 0 (read)
305
cat /var/log/boot.log
cat /var/log/maillog
cat /var/log/yum.log
ps -AlFH
306
ps -auxf | sort -nr -k 3 | head -10
grep -r "is" *
307
chkconfig --list | grep network
shutdown -r 18:30
netstat -ain
ls -ld /home
308
chmod go=+r 1.txt
du -sh *
du -sh .[!.]* *
# Display the disk usages of the files (including hidden files) in the current directory
du -sch .[!.]* *
309
iostat -kx
netstat -nulp
sudo yum install parted
# Display open UDP sockets
# Install parted
netstat -nxlp
parted -v
# Display open Unix sockets
# Check Parted version
dmidecode -q | less
parted -l
# Display BIOS information
# Lists partition layout on all block devices
systemctl --failed
parted -m
# List failed services
# Displays machine parseable output
quit
losetup
# Exit the parted shell
# Display information about all loop devices
310
# Display the file access
getfacl --access 1.txt
control list of a file "1.txt"
getfacl -a 1.txt
getfacl -n 1.txt
List the numeric user and
getfacl --numeric 1.txt group IDs w.r.t file "1.txt"
sudo tcpdump -D
myfiles.txt.xz
61.852
61.852
311
[manju@localhost ~]$ free -t | awk 'NR == 3 {print $3/$2*100}'
2.54155
2.54155
Display Swap Utilization
61.86%
61.86%
Display Memory Utilization with Percent Symbol and two decimal places
2.65%
2.65%
Display Swap Utilization with Percent Symbol and two decimal places
312
[manju@localhost ~]$ top -b -n1 | grep ^%Cpu | awk '{cpu+=$9}END{print 100-cpu/NR}'
100
Display CPU Utilization
[manju@localhost ~]$ top -b -n1 | grep ^%Cpu | awk '{cpu+=$9}END{printf("%.2f% \n"), 100-cpu/NR}'
100.00%
Display CPU Utilization with Percent Symbol and two decimal places
swapon -s
alias -p
313
sudo netstat -anp | grep tcp | grep LISTEN
printf "%s\n" *
# Prints the files and directories that are in the current directory
printf "%s\n" */
[manju@localhost ~]$ x
314
[manju@localhost ~]$ x="alan"; printf '%s\n' "${x^}"
Alan
ALAN
ALAN
Find directories and files with names starting with "xyz" and
ending with an alpha character after a one-digit
# Search for files that haven't been updated in the past two hours
find . -mtime -3
# Find files that have been modified within the last 3 days
find . -mtime +3
# Find files that have not been modified within the last 3 days
315
[manju@localhost ~]$ names="Albert Alan John Mary"; x=(${names// / }); echo ${x[0]}
Albert
[manju@localhost ~]$ names="Albert Alan John Mary"; x=(${names// / }); echo ${x[3]}
Mary
names="Albert+Alan+John+Mary";
x=(${names//+/ });
echo ${x[0]}
x=(hello world); echo "${x[@]/#/A}"
# Output: Albert
# Output: Ahello Aworld
names="Albert+Alan+John+Mary";
x=(${names//+/ });
echo ${x[3]}
# Output: Mary
Mathison
Alan
# prints 4 * 2
316
x='4 * 2'; echo "$(($x))"
# prints 8
aLAN
alan
aLAN
alan
317
[manju@localhost ~]$ x='You are a genius'; echo "${x#*a}"
re a genius
enius
foo
25
You are
You
Bob
Bob-Dev
Fox
Dev-Fox
318
find . -type f -path '*/Documents/*'
# Find all files except the ones contained in a folder called Documents
# Find all files except the ones contained in a folder called Documents or log files
0000
319
[manju@localhost ~]$ echo "$(printf "%05d" "${x}")"
00000
"'"
15
15
n Tu
1 (True)
0 (False)
320
[manju@localhost ~]$ expr PQRSTUVWXYZ : PQRS
ls -ral
ls -tl
ls -trl
# List the files such that the one that was most recently edited is at the top of the list
./bc.pdf
find . -type f -print
./1.PDF
# List only regular files
./data.sh
./1.sh
[manju@localhost ~]$ echo "alan+alan+alan+alan" | xargs -d +
./2.SH
alan alan alan alan
./1.pdf
[manju@localhost ~]$ echo "alan+alan+alan+alan" | xargs -d + -n 2
./2.sh
alan alan
alan alan
321
[manju@localhost ~]$ echo -e "2\nalbert\n" > 1.txt
albert
Albert
Tesla
John
1 Albert
2 Tesla
3 John
322
[manju@localhost ~]$ echo -e "Albert\nTesla\nJohn" | nl -s ": " -w 1
1: Albert
2: Tesla
3: John
du -h -d1
find / - manju
locate "*.png"
323
find . -type f -printf "\"%p\" " | xargs chmod 664
# Find all files in the current directory, including subfolders and assign rights 664
# Find all files in the current directory, including subfolders and assign rights 775
ll
ls -l
# List the files in current directory
date +%j
date +%Y%m%d
date +%d\/%m\/%Y
324
C Exercises
Dennis Ritchie, known as the "Father of C Low-Level Programming Language," created the
general-purpose, procedural, imperative computer programming language "C" in 1972 at the
Bell Telephone Laboratories to be used with the UNIX operating system. It now ranks among the
most popular programming languages after spreading to numerous different operating systems.
Many other well-known languages, including C++, which was initially created as an
improvement to C, have also been strongly inspired by C. Though it is also widely used for
creating applications, it is the most frequently used programming language for creating system
software. It is one of the programming languages that is most frequently used today. Since 1989,
C has been standardized by both the International Organization for Standardization and the
American National Standards Institute. Don't worry if you are a beginner; we have exercises for
you. We'll concentrate on beginner-level programming problems in this chapter to help you learn
C and develop your programming abilities.
325
Question 1
Question:
#include<stdio.h>
Solution:
int main() {
#include<stdio.h> int a = 6;
int main() {
{
printf("Hello, World!");
int a = 2;
return 0;
printf("%d\n", a);
} Output:
}
2
printf("%d\n", a);
6
}
Question 2
Question:
Solution:
#include<stdio.h>
int main() {
int height = 8;
int width = 5;
326
int perimeter = 2*(height + width);
printf("Perimeter of the rectangle is: %d cm\n", perimeter);
int area = height * width;
printf("Area of the rectangle is: %d square cm\n", area);
return 0;
}
Question 3
Question:
Solution:
#include<stdio.h>
int main() {
int radius = 4;
float perimeter = 2*3.14*radius;
printf("Perimeter of the circle is: %f cm\n", perimeter);
float area = 3.14*radius*radius;
printf("Area of the circle is: %f square cm\n", area);
return 0;
}
327
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
#include<stdio.h>
Question 5
Question:
Write a program that accepts two numbers from the user and calculate the product of the
two numbers.
328
#include<stdio.h>
int Message() {
printf("Hello, World!");
Solution:
return 0;
#include<stdio.h>
}
int main() {
int a, b, mult;
int main() { Output:
Question 6
Question:
Write a program that accepts three numbers and find the largest of three.
Solution:
#include<stdio.h>
int main() {
int x, y, z;
printf("\nEnter the first number: ");
scanf("%d", &x);
329
printf("\nEnter the second number: ");
scanf("%d", &y);
printf("\nEnter the third number: ");
scanf("%d", &z);
return 0;
}
Question 7
Question:
Write a program that reads three floating values and check if it is possible to make a
triangle with them. Also calculate the perimeter of the triangle if the entered values are
valid.
330
Solution: /* Hello World /* Program in C*/ */
#include<stdio.h> #include<stdio.h>
Question 8
Question:
Write a program that reads an integer between 1 and 7 and print the day of the week in
English.
Solution:
331
#include<stdio.h>
int main() {
int day;
printf("\nEnter a number between 1 to 7 to get the day name: ");
scanf("%d", &day);
switch(day) {
case 1 : printf("Monday\n"); break;
case 2 : printf("Tuesday\n"); break;
case 3 : printf("Wednesday\n"); break;
case 4 : printf("Thursday\n"); break;
case 5 : printf("Friday\n"); break;
case 6 : printf("Saturday\n"); break;
case 7 : printf("Sunday\n"); break;
default : printf("Enter a number between 1 to 7.");
}
return 0;
}
Question 9
Question:
332
a=1;
b=2;
sum = a + b;
printf("The sum of a and b = %d", sum);
return 0;
}
Question 10
Question:
Solution:
#include<stdio.h>
#include<stdio.h>
#include<math.h> extern int a;
}
Output:
a=1
333
Question 11
Question:
Solution: #include<stdio.h>
Question 12
Question:
334
Game theory is a mathematical framework used to study decision-
making in situations where the outcomes of one person's choices
Solution: depend on the choices made by others. It is the study of mathematical
representations of rational decision-makers interacting strategically.
The goal of game theory is to identify the optimal strategies that
#include<stdio.h>
players can use to achieve their objectives in situations where the
int main() { choices of one player affect the outcomes for all players involved.
Game theory is used in various fields such as economics, political
int i, avg, sum = 0;
science, psychology, and biology.
int num [5] = {16, 18, 20, 25, 36};
for(i=0; i<5; i++) {
sum = sum + num [i];
avg = sum/5;
}
printf("Sum of the Elements in the array is: %d\n", sum);
printf("Average of the elements in the array is: %d\n", avg);
return 0;
}
Question 13
Question:
Write a program that prints all even numbers between 1 and 25.
Solution:
#include<stdio.h>
int main() {
printf("Even numbers between 1 to 25:\n");
for(int i = 1; i <= 25; i++) {
if(i%2 == 0) {
printf("%d ", i);
335
}
}
return 0;
}
Question:
Write a program that prints all odd numbers between 1 and 50.
Solution:
#include<stdio.h>
int main() {
printf("Odd numbers between 1 to 50:\n");
for(int i = 1; i <= 50; i++) {
if(i%2 != 0) {
printf("%d ", i);
#include<stdio.h>
}
int main() {
}
return 0; char c = 'a';
} putchar(c);
return 0;
}
Output:
336
Question 15
Question:
Write a program to print the first 10 numbers starting from one together with their
squares and cubes.
Solution:
#include<stdio.h>
int main() {
for(int i=1; i<=10; i++) {
printf("Number = %d its square = %d its cube = %d\n", i , i*i, i*i*i);
}
return 0;
#include<stdio.h>
}
int main() {
int a, b;
printf("%d", b);
Output:
Question:
printf("\n");
1
Write a program: }
12
If you enter a character M return 0;
1234
12345
Solution:
337
#include<stdio.h> #include<stdio.h>
return 0; Output:
Question 17 } 15 28
Question:
Write a program to print the multiplication table of a number entered by the user.
#include<stdio.h>
Solution:
int main () {
#include<stdio.h> float a;
int main() {
a = (float) 51/4;
int n, i;
printf("%f", a);
printf("Enter any number: ");
scanf("%d", &n); return 0;
338
Question 18
Question:
Question 19
Question:
Solution:
#include<stdio.h>
339
int main() {
int a; #include<stdio.h>
a = -35;
int main() {
if(a>0) {
char name[] = "Einstein";
printf("Number is positive");
} printf("%c", name[0]);
else { return 0;
printf("Number is negative");
}
}
return 0;
Output:
}
E
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the first number: ");
scanf ("%d", &x);
printf("\nEnter the second number: ");
scanf ("%d", &y);
if(x-y==0) {
printf("\nThe two numbers are equivalent");
340
}
else {
printf("\nThe two numbers are not equivalent");
}
return 0;
}
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
341
Question 22
Question:
Solution:
#include<stdio.h>
#include<stdio.h> int main() {
int main() {
char name[] = "Einstein";
char i;
name[0] = 'H';
for(i='A'; i<='Z'; i++) {
printf("%c\n", i); printf("%s", name);
} return 0;
return 0;
}
}
Output:
Hinstein
Question 23
Question:
Solution:
#include<stdio.h>
#include<string.h>
342
int main() {
char str[1000];
printf("Enter a string to calculate its length: ");
scanf("%s", str);
printf("The length of the entered string is: %ld", strlen(str));
return 0;
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
formatted.
#include<stdio.h>
#include <ctype.h>
int main() {
char ch = 'a';
if(islower(ch)) {
printf("The given character is a lower case letter");
}
else {
printf("The given character is a upper case letter");
}
return 0;
}
343
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
Question 26
Question:
Write a program to convert the lower case letter to upper case letter.
344
Solution:
In a C program, any number of functions can be written.
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches. #include<stdio.h>
int main() {
int i = 6;
Solution: while(i == 3) {
Output:
i = i - 3;
#include<stdio.h>
?
printf ("%d\n", i);
#define x 2.54
int main() { --i;
345
inch = cm / x;
printf("\nDistance of %0.2lf cms is equal to %0.2lf inches", cm, inch);
return 0;
}
#include<stdio.h>
Question 28
int main() {
printf("%d", i);
Write a program to print the output:
return 0;
Einstein [0] = E
}
Einstein [1] = I
Einstein [2] = N
Output:
Einstein [3] = S
54
Einstein [4] = T
Einstein [5] = E
Einstein [6] = I
Einstein [7] = N
Solution:
#include<stdio.h>
int main() {
char name [8] = {'E' , 'I', 'N', 'S', 'T', 'E', 'I', 'N'};
for(int i=0; i<8; i++) {
printf("\nEinstein [%d] = %c", i, name[i]);
}
return 0;
346
}
Question 29
Question:
#include<stdio.h>
int main() {
Solution:
int num[] = {5, 7, 9, 42};
Question 30
Question:
Solution:
347
#include<stdio.h>
#include<stdio.h>
int main() { int main () {
int i =1; char name[9] = {'C', 'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
do { printf("%s\n", name);
printf("%d\n", i++);
return 0; Output:
} while(i<=5);
return 0;
} CProgram
Question 31
Question:
#include<stdio.h>
#define SIZE 3
int main() {
Solution:
char names[SIZE][8] = {
#include<stdio.h>
"Mary",
#include<ctype.h>
"Albert",
int main() {
int a =2; "John"
Output:
if(isalpha(a)) { };
printf("The character a is an alphabet");
int i;
Mary
}
for(i=0; i<SIZE; i++) Albert
else {
printf("The character a is not an alphabet"); puts(names[i]); John
} return 0;
return 0; }
}
348
Question 32
Question:
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int main() { int num[] = {5, 7, 9, 42};
int a; num[0] = 3;
printf("Enter any number: ");
printf("%d", num[0]);
scanf ("%d", &a);
return 0;
if(a%2 == 0) {
printf("The entered number is even"); }
} Output:
else {
3
printf("The entered number is odd");
}
return 0;
}
Question 33
Question:
349
Solution:
#include<stdio.h>
int main() {
char ch ='A';
printf("The ASCII value of %c is: %d", ch, ch);
return 0;
}
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder will be 2.
#include<stdio.h>
Solution:
int main() {
#include<stdio.h>
int i = 25; Program to get the memory
int main() {
printf("%p", &i); address of a variable "i"
int x, i;
printf("Enter a number: "); return 0;
scanf("%d", &x); }
for(i=1; i<=50; i++) {
if((i%x)==2) {
printf("%d\n", i);
}
350
}
return 0;
}
Question 35
Question:
descending order.
Solution:
#include<stdio.h>
int main() {
int a, b;
printf("\nEnter a pair of numbers (for example 22,12 | 12,22): ");
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
scanf("%d", &b);
if (a>b) {
printf("\nThe two numbers in a pair are in descending order.");
}
else {
printf("\nThe two numbers in a pair are in ascending order.");
}
return 0;
}
351
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
not possible" if that is not possible.
#include<stdio.h>
int main() {
int a = 6;
Solution:
float b = 6.0;
#include<stdio.h> if(a == b) {
int main() { printf("\na and b are equal");
int a, b;
}
float c;
else {
printf("\nEnter the first number: ");
scanf("%d", &a); printf("\na and b are not equal");
352
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int a = 15, b, c;
int main() {
int x, i; b = a = 25;
Question 38
Question:
Write a program that adds up all numbers between 1 and 100 that are not divisible by 12.
353
Solution:
#include<stdio.h>
#include<stdio.h> int main() {
int main() {
int x = 67;
int x =12, i, sum = 0;
char y = 'C';
for(i=1; i<=100; i++) {
if((i%x)!= 0) { if(x == y) {
return 0; Output:
} Albert Einstein
Question 39
Question:
Solution:
#include<stdio.h>
int main() {
float x = 0;
for(int i=1; i<=50; i++) {
x += (float)1/i;
}
printf("Value of x: %.2f\n", x);
354
return 0;
}
Question 40
Question:
Write a program that reads a number and find all its divisor.
Solution:
#include<stdio.h>
int main() {
int x, i;
printf("\nEnter a number: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
for(i = 1; i <= x; i++) {
if((x%i) == 0) { #include<stdio.h>
printf("\n%d", i);
int main() {
}
int a = 20, b = 25;
}
if(a % 2 == b % 5) {
return 0;
} printf("\nPeru");
return 0; Output:
} Peru
355
Question 41
Question:
Write a program to find the incremented and decremented values of two numbers.
c=a+1;
d=b+1;
e=a-1;
f=b-1;
printf("\nThe incremented value of a =%d", c);
printf("\nThe incremented value of b =%d", d);
printf("\nThe decremented value of a =%d", e);
printf("\nThe decremented value of b =%d", f);
return 0;
}
Question 42
Question:
356
Solution:
#include<stdio.h>
int square();
int main() {
int answer;
answer = square();
printf("The square of the entered number is: %d", answer);
return(0);
} #include<stdio.h>
return 0;
} Output:
Question 43 877
Question:
Write a program that accepts principal amount, rate of interest, time and compute the
simple interest.
Solution:
#include<stdio.h>
357
int main() { Mathematical logic and Boolean logic are two
int p,r,t,SI; different branches of logic, although they share some
similarities.
printf("\nEnter the principal amount: ");
scanf("%d",&p); The formal study of mathematical reasoning and proof
is what mathematical logic is all about. It includes
printf("\nEnter the rate of interest: "); propositional logic, predicate logic, set theory, and
scanf("%d",&r); other related areas. Mathematical logic is used to
develop rigorous mathematical proofs and to study the
printf("\nEnter the time: ");
foundations of mathematics.
scanf("%d",&t);
Boolean logic, on the other hand, is a type of algebraic
SI=(p*r*t)/100;
logic that deals with the manipulation and evaluation of
printf("\nSimple interest is: %d", SI); logical statements. It is based on the binary values of
return 0; true and false, or 1 and 0, and uses logical operators
such as AND, OR, and NOT to combine and
} manipulate logical statements. Boolean logic is widely
used in computer science, digital electronics, and other
areas where logical reasoning is important.
Write a program that swaps two numbers without using third variable.
Solution:
#include<stdio.h>
int main() {
int a, b;
printf("\nEnter the value for a: ");
scanf("%d",&a);
printf("\nEnter the value for b: ");
scanf("%d",&b);
printf("\nBefore swapping: %d %d",a,b);
358
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swapping: %d %d",a,b);
return 0;
}
Question 45
Question:
Write a program to find the greatest of two entered numbers using pointers.
#include<stdio.h>
int main() {
Solution: int a = 15, b = 30;
#include<stdio.h> if(a == b) {
359
}
return 0;
}
Question 46
#include<stdio.h>
int main() {
Question:
int i = 60;
Write a program to print the output:
if(i > 70 && i < 100) {
body [b] = b
printf("i is greater than 70 and less than 100");
body [o] = o
}
body [d] = d
else {
body [y] = y
printf("%d", i);
}
Output:
return 0;
Solution: } 60
#include <stdio.h>
int main() {
char i;
char body [4] = {'b', 'o', 'd', 'y'};
for(i=0; i<4; i++)
printf("\n body[%c] = %c", body[i] , body[i]);
return 0;
}
360
Question 47
Question:
Write a program to calculate the discounted price and the total price after discount
Given:
#include<stdio.h>
int main() {
Solution:
printf("%%15s = %15s\n", "albert");
?
return(0);
printf("\n Discount = %lf", PV* 0.3);
}
printf("\n Total = %lf", PV - PV* 0.3);
}
return 0;
361
}
Question 48
Question:
Write a program to print the first ten natural numbers using while loop statement.
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int i = 12;
int main() {
int i = 1; if(i == 12 && i != 0) {
} Hi
return 0;
Question 49 Einstein
}
Question:
362
An algorithm is a set of precise, step-by-
Solution: step instructions or procedures for solving
a problem or achieving a specific goal.
Algorithms are used in many areas of
#include<stdio.h>
science, engineering, and computing,
int main() { where they help to automate processes
int x; and enable efficient computation.
printf("Enter the integer from keyboard: "); An algorithm takes some input and
scanf("%d",&x); produces some output, often involving
some form of data manipulation or
printf("\nEntered value: %d ",x); transformation. Algorithms are designed
printf("\nThe left shifted data is: %d ", x<<=2); to be efficient and accurate, and they can
be expressed in various forms, such as
return 0;
Pseudocode, flowcharts, or programming
} languages. Algorithms can range in
complexity from simple calculations to
complex machine learning models. Some
examples of algorithms include sorting
algorithms, search algorithms, encryption
algorithms, and optimization algorithms.
Question 50 The development and analysis of
algorithms are central to the fields of
computer science and mathematics.
Question:
Solution:
#include<stdio.h>
int main() {
int x;
printf("Enter the integer from keyboard: ");
scanf("%d",&x);
printf("\nEntered value: %d ",x);
printf("\nThe right shifted data is: %d ", x>>=2);
return 0;
}
363
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
the absolute difference if x is greater than 21.
} Output:
25 25
364
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the first number: ");
scanf("%d", &x);
printf("\nEnter the second number: ");
scanf("%d", &y);
if(x % y == 0) {
printf("\n%d is a multiple of %d.\n", x, y);
}
else {
printf("\n%d is not a multiple of %d.\n", x, y);
}
return 0; #include<stdio.h>
} int main() {
int x = 10;
return 0;
Output:
}
True
365
Question 53
Question:
int main() {
Output:
int num, x, y, z;
Solution:
#include<stdio.h>
printf("Enter a three digit number: ");
scanf("%d", &num);
?
int main() {
x=num%10;
struct book {
y=(num/10)%10;
char name;
float price; z=(num/100)%10;
int pages; printf("%d is the sum of the digits of the number %d.", x+y+z, num);
int edition;
return 0;
};
}
struct book b1;
b1.name = 'B';
b1.price = 135.00;
b1.pages = 300;
b1.edition = 8;
printf("\n Name of the book = %c", b1.name);
printf("\n Price of the book = %f", b1.price);
printf("\n Number of pages = %d", b1.pages);
printf("\n Edition of the book = %d", b1.edition);
366
return 0;
}
Question 54
Question:
Solution:
#include<stdio.h>
int main() {
float fahrenheit, celsius;
celsius = 36;
fahrenheit = ((celsius*9)/5)+32;
printf("\nTemperature in fahrenheit is: %f", fahrenheit);
return 0;
}
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
367
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if(x == 50 || y == 50 || (x + y == 50)) {
printf("\nTrue");
} #include<stdio.h>
else {
int main() {
printf("\nFalse");
} while(!printf("Albert Einstein")){}
return 0; return 0;
}
}
Output:
Albert Einstein
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
368
#include<stdio.h>
int main () {
int x, even = 0, odd = 0, positive = 0, negative = 0;
printf("\nPlease enter 18 numbers:\n");
#include<stdio.h>
for(int i = 0; i < 18; i++) {
scanf("%d", &x); int main() {
if (x > 0) { int x = 0, y = 1 ;
positive++;
if(x == 0) {
}
(y > 1 ? printf("\nHi") : printf ("\nAlbert"));
if(x < 0) {
negative++; }
} else {
int main() {
switch(printf("Albert Einstein")){}
return 0;
Output:
}
Albert Einstein
369
Question 57
Question:
#include<stdio.h>
int main() {
Solution:
int x;
} }
return 0; Output:
} David
Question 58
Question:
Write a program that reads a student's three subject scores (0-100) and computes the
average of those scores.
370
Solution:
#include<stdio.h>
int main() {
float score, total_score = 0;
int subject = 0;
printf("Enter three subject scores (0-100):\n");
while (subject != 3) {
scanf("%f", &score);
if(score < 0 || score > 100) {
printf("Please enter a valid score.\n");
}
else {
total_score += score;
subject++;
}
}
printf("Average score = %.2f\n", total_score/3);
return 0;
}
Question 59
Question:
371
#include<stdio.h>
#include<stdio.h>
int main() {
for(int i=1; i<=5; i++) { int main() {
return 0; }
} Output:
15/4 = 3.75
Solution:
1
#include<stdio.h>
2
int main() {
int a = 6, b = 4, c;
c = a++ +b;
#include<stdio.h>
printf ("\n%d %d %d", a, b, c);
int main() {
for(int i=1;i<=5;i++) { return 0;
if(i==3) { }
goto HAI;
Output:
}
printf("\n %d ",i); 7 4 10
}
HAI : printf("\n Linux");
}
372
Solution:
1
2
Linux
#include<stdio.h>
int main() {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0; #include<stdio.h>
}
int main() {
float i = 5.5;
while(i == 5.5) {
Solution: i = i - 0.8;
printf("\n%f", i);
This loop will run forever.
}
This loop will run forever.
This loop will run forever. return 0;
#include<stdio.h>
int main() {
printf("Hello,world!");
return 0;
373
printf("Hello,world!");
}
Solution:
Hello,world!
#include<stdio.h>
int main() {
float i = 5.5;
#include<stdio.h>
while(i == 5.5) {
#include<stdlib.h>
printf("\n%f", i);
int main () {
printf("linux\n"); i = i - 0.8;
exit (0); }
printf("php\n");
return 0;
return 0;
}
}
Output:
5.500000
Solution:
linux
#include<stdio.h>
int main() {
for(int i=1; i<=5; i++) {
if(i==3) {
continue;
374
}
printf("%d\n ", i);
}
return 0;
}
Solution:
1
2 #include<stdio.h>
4 int main() {
5
int a = 6, b = 2;
while(a >= 0) {
a--;
#include<stdio.h> b++;
int main() {
if(a == b) {
int a = 10, b = 20, c;
continue;
c = (a < b) ? a : b;
printf("%d", c); }
return 0; else {
} printf("\n%d %d", a, b);
}
Output:
}
35
return 0;
Solution: }
26
17
10
08
-1 9
375
#include<stdio.h>
#include<stdio.h>
#define A 15 int main() {
?
} }
Solution:
15
#include<stdio.h>
#include<stdlib.h>
int main() {
int i;
for(i=1; i <= 3; i++) {
printf((i&1) ? "odd\n" : "even\n");
}
exit(EXIT_SUCCESS);
}
376
Solution:
odd
even
odd
#include<stdio.h>
#include<math.h>
#include<stdio.h>
int main() {
int main() {
double a, b;
a = -2.5; int x;
break;
default:
printf("\nElsa");
Solution:
}
Output:
#include<stdio.h>
#include<stdlib.h> Albert
int main() {
int x=12, y =3;
377
printf("%d\n", abs(-x-y));
return 0;
}
#include<stdio.h>
Solution:
int main() {
15
int x = 5;
switch (x - 6) {
case -1 :
printf("\nAlbert");
#include<stdio.h>
case 0 :
#include<stdlib.h>
printf("\nJohn");
int main() {
int x=12, y =3; case 1 :
return 0;
Solution: }
Output:
15
Albert
John
Mary
#include<stdio.h>
James
#include<stdlib.h>
378
int main() {
int x=12, y =3; #include<stdio.h>
printf("%d\n", x-(-y)); int main() {
return 0;
int y[] = {20, 40, 60, 80, 100};
}
for(int x = 0; x <= 4; x++) {
}
Solution: Output:
return 0;
15 } 20
40
60
80
Question 60
100
Question:
Solution:
#include<stdio.h>
int main() {
int num [] = {11, 22, 33, 44, 55, 66};
int n = sizeof(num) / sizeof(num [0]);
printf("Size of the array is: %d\n", n);
return 0;
}
379
Question 61
Question:
Write a program that prints a sequence from 1 to a given integer, inserts a plus sign
between these numbers, and then removes the plus sign at the end of the sequence.
Solution:
#include<stdio.h>
int main () {
int x, i;
printf("\nEnter a integer: \n");
scanf("%d", &x);
#include<stdio.h>
if(x>0) {
printf("Sequence from 1 to %d:\n", x); int main() {
return 0; }
}
Output:
380
Question 62
Question:
Write a program to verify whether a triangle's three sides form a right angled triangle or
not.
Solution:
#include<stdio.h>
int main() {
int a,b,c;
printf("Enter the three sides of a triangle: \n");
scanf("%d %d %d",&a,&b,&c);
if((a*a)+(b*b)==(c*c) || (a*a)+(c*c)==(b*b) || (b*b)+(c*c)==(a*a)) {
printf("Triangle's three sides form a right angled triangle.\n");
}
else {
printf("Triangle's three sides does not form a right angled triangle.\n");
}
return 0;
}
#include<stdio.h>
int main() {
Output:
printf("%c", "einstein"[4]);
t
return 0;
381
Question 63
Question:
Write a program that will find the second-largest number among the user's input of three
numbers.
Solution:
#include<stdio.h>
int main() {
int a, b, c;
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
scanf("%d", &b);
printf("\nEnter the third number: ");
scanf("%d", &c);
if(a>b && a>c) {
if(b>c)
printf("\n%d is second largest number among three numbers", b);
else
printf("\n%d is second largest number among three numbers", c);
}
else if(b>c && b>a) {
if(c>a)
printf("\n%d is second largest number among three numbers", c);
else
printf("\n%d is second largest number among three numbers", a);
}
else if(a>b)
382
printf("\n%d is second largest number among three numbers", a);
else
printf("\n%d is second largest number among three numbers", b);
return 0;
}
Question 64
Question:
Write a program to calculate the sum of the two given integer values. Return three times
the sum of the two values if they are equal.
#include<stdio.h>
int main() {
#include<stdio.h> i=x%10;
} return 0;
int myfunc(int a, int b) { }
return a == b ? (a + b)*3 : a + b;
Output:
}
68235
383
Question 65
Question:
Write a program that accepts minutes as input, and display the total number of hours and
minutes.
#include<stdio.h>
int main() {
Question 66
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five.
384
Solution:
#include<stdio.h>
#include<stdio.h>
#define MULT(i) (i*i)
int main() {
int main() {
int x;
printf("\nEnter a number: "); int x = 6;
printf("False"); }
Output:
}
return 0; 42 100
}
Question 67
Question:
Write a program to verify whether one of the two entered integers falls within the range
Solution:
#include<stdio.h>
int main() {
int x, y;
385
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if((x >= 100 && x <= 200) || (y >= 100 && y <= 200)) {
printf("True");
#include<stdio.h>
}
else { int main() {
?
while(x[i]) {
}
printf("%c at %p\n", x[i], &x[i]);
i++;
return 0;
Question 68
}
Question:
Write a program to determine which of the two given integers is closest to the value 100.
If the two numbers are equal, return 0.
Solution:
#include<stdio.h>
#include<stdlib.h>
int myfunc();
int main() {
printf("%d", myfunc(86, 99));
printf("\n%d", myfunc(55, 55));
386
printf("\n%d", myfunc(65, 80));
return 0;
}
int myfunc(int a, int b) {
int x = abs(a - 100);
int y = abs(b - 100);
return x == y ? 0 : (x < y ? a : b);
}
Question 69
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five, but not both.
#include<stdio.h>
int main() {
?
if(x % 3 == 0 ^ x % 5 == 0) { return 0;
printf("True"); }
}
else {
printf("False");
}
387
return 0;
}
Question 70
Question:
Write a program to determine whether two entered non-negative numbers have the same
last digit.
Solution: #include<stdio.h>
#include<ctype.h>
#include<stdio.h>
int main() {
#include<stdlib.h>
int main() { char x;
int x, y; x = getchar();
printf("\nEnter the value for x: ");
if(islower(x)) {
scanf("%d", &x);
putchar(toupper(x));
printf("\nEnter the value for y: ");
scanf("%d", &y); }
?
putchar(tolower(x));
}
}
else {
return 0;
printf("False");
} }
return 0;
}
388
Question 71
Question:
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int x = 43;
if(x % 12 == 0 || x % 12 == 1) {
printf("True");
}
else {
printf("False");
#include<stdio.h>
}
int main() {
return 0;
} printf(6 + "Albert Einstein");
return 0;
Output:
Einstein
389
Question 72
Question:
Write a program that accepts two integers and returns true when one of them equals 6, or
when their sum or difference equals 6.
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int x, y;
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if(x == 6 || y == 6 || x + y == 6 || abs(x - y) == 6) {
printf("True");
}
#include<stdio.h>
else {
printf("False"); int main() {
Output:
2.500000
390
Question 73
Question:
Write a program to check whether it is possible to add two integers to get the third
integer from three entered integers.
Solution:
#include<stdio.h>
int main() {
int x, y, z;
printf("\nEnter the value for x: ");
scanf("%d", &x); #include<stdio.h>
printf("\nEnter the value for y: ");
int myfunc();
scanf("%d", &y);
int main() {
printf("\nEnter the value for z: ");
scanf("%d", &z); printf("\nAlbert Einstein");
if(x == y + z || y == x + z || z == x + y) { myfunc();
printf("True"); return 0;
}
}
else {
int myfunc() {
printf("False");
} printf("\nElsa Einstein");
return 0; main();
}
?
}
391
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
#include<stdio.h>
int main() {
float kmph;
printf("Enter kilometers per hour: ");
scanf("%f", &kmph);
printf("\n%f miles per hour", (kmph * 0.6213712));
return 0;
} #include<stdio.h>
int main() {
printf("Albert Einstein\n");
main();
Question 75
return 0;
?
Question:
Solution:
#include<stdio.h>
#define PI 3.141592
392
int main() {
float major, minor;
printf("\nEnter length of major axis: ");
scanf("%f", &major);
printf("\nEnter length of minor axis: ");
scanf("%f", &minor);
printf("\nArea of an ellipse = %0.4f", (PI * major * minor));
return 0;
}
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
393
if (a == b) return c;
if (a == c) return b;
if (b == c) return a;
else return a + b + c;
}
Question 77
#include<stdio.h>
Question:
#include<stdlib.h>
int x = 1;
x++;
if(x <= 6) {
Solution:
printf("\nC language");
#include<stdio.h> exit(0);
int main() {
main();
double bytes;
}
printf("\nEnter number of bytes: ");
scanf("%lf",&bytes); return 0;
Output:
C language
394
Question 78
Question:
Solution:
#include<stdio.h>
int main() {
double megabytes, kilobytes;
printf("\nInput the amount of megabytes to convert: ");
scanf("%lf",&megabytes);
kilobytes = megabytes * 1024;
printf("\nThere are %lf kilobytes in %lf megabytes.", kilobytes, megabytes);
return 0;
}
Question 79
Question:
Solution:
#include<stdio.h>
395
int main() {
int array[1000], i, arr_size, even=0;
printf("Input the size of the array: ");
scanf("%d", &arr_size);
printf("Enter the elements in array: \n");
for(i=0; i<arr_size; i++) {
scanf("%d",&array[i]);
}
Question 80
Question:
Solution:
#include<stdio.h>
int main() {
396
int array[1000], i, arr_size, odd=0;
printf("Input the size of the array: ");
scanf("%d", &arr_size); The ability of machines to carry out
printf("Enter the elements in array: \n"); operations that ordinarily require human
intelligence, such as speech recognition,
for(i=0; i<arr_size; i++) { decision-making, and language translation, is
scanf("%d",&array[i]); known as artificial intelligence (AI). AI
involves the development of computer
}
programs and algorithms that can learn from
data and experience to make predictions,
identify patterns, and solve problems. This
for(i=0; i<arr_size; i++) {
includes techniques such as machine
if(array[i]%2!=0) { learning, deep learning, natural language
processing, and robotics. AI is a rapidly
odd++;
evolving field that has the potential to
} transform many industries and aspects of
} everyday life.
Question 81
Question:
Write a program that will accept two integers and determine whether or not they are
equal.
Solution:
#include<stdio.h>
int main() {
int x, y;
397
Automated reasoning refers to the use of computer
programs and algorithms to automatically derive
printf("Input the values for x and y: \n");
logical conclusions from given premises. The goal of
scanf("%d %d", &x, &y); automated reasoning is to develop techniques that
can automate the process of reasoning and problem-
if(x == y) {
solving, enabling computers to perform tasks that
printf("x and y are equal\n"); would otherwise require human intelligence.
}
Automated reasoning systems typically use symbolic
else { logic and formal reasoning methods to analyze the
printf("x and y are not equal\n"); logical structure of a problem, identify potential
solutions, and generate a proof or a refutation. These
} systems can be used in a variety of applications, such
return 0; as software verification, theorem proving, expert
systems, and artificial intelligence.
}
Automated reasoning is a critical component of
many AI systems, particularly in domains that
require advanced logical reasoning and decision-
making, such as medicine, law, and finance. It is also
Question 82 an active area of research in computer science,
mathematics, and philosophy.
Question:
Write a program to find the third angle of a triangle if two angles are given.
Solution:
#include<stdio.h>
int main() {
int angle1, angle2;
printf("\nEnter the first angle of the triangle: ");
scanf("%d", &angle1);
printf("\nEnter the second angle of the triangle: ");
scanf("%d", &angle2);
printf("\nThird angle of the triangle is: %d", (180 - (angle1 + angle2)));
return 0;
}
398
Question 83
Question:
else {
printf("\n%d is not a leap year.", year);
}
return 0;
}
399
Question 84
Question:
Write a program that reads the candidate's age and determine a candidate's eligibility to
cast his own vote.
Solution:
#include<stdio.h>
int main() {
int age;
printf("\nEnter the age of the candidate: ");
scanf("%d",&age);
if(age<18) {
printf("\nWe apologize, but the candidate is not able to cast his vote.");
printf("\nAfter %d year, the candidate would be able to cast his vote.", (18-
age));
}
else {
printf("Congratulation! the candidate is qualified to cast his vote.\n");
}
return 0; #include<stdio.h>
}
int main() {
while(putchar(*x++));
Output:
return 0;
Albert Einstein
}
400
Question 85
Question:
Question 86
Question:
Solution:
#include<stdio.h>
int main() {
401
double gigabytes, megabytes;
printf("\nInput the amount of gigabytes to convert: ");
scanf("%lf", &gigabytes);
megabytes = gigabytes*1024;
printf("\nThere are %lf megabytes in %lf gigabytes.", megabytes, gigabytes);
return 0;
}
Question 87
Question:
Solution:
#include<stdio.h>
int main() {
float kg, lbs;
printf("\nEnter Weight in Kilogram: ");
scanf("%f", &kg);
lbs = kg*2.20462;
printf("\n%f Kg = %f Pounds", kg, lbs);
return 0;
}
402
Question 88
Question:
Solution:
403
#include<stdio.h>
int main() {
float pound, gram;
printf("\nEnter Weight in Pounds: ");
scanf("%f", £);
gram = pound*453.592;
printf("\n%f Pound = %f Grams", pound, gram);
return 0;
}
Question 90
Question:
Solution:
#include<stdio.h>
int main() {
int angle1, angle2, angle3, sum;
printf("\nEnter the first angle of the triangle: ");
scanf("%d", &angle1);
printf("\nEnter the second angle of the triangle: ");
scanf("%d", &angle2);
printf("\nEnter the third angle of the triangle: ");
scanf("%d", &angle3);
sum = angle1 + angle2 + angle3;
if(sum == 180) {
404
printf("\nThe triangle is valid.");
}
else {
printf("\nThe triangle is not valid.");
}
return 0;
}
Question 91
Question:
Write a program to add the digits of a two-digit number that is entered by the user.
Solution:
#include<stdio.h>
int main() {
int x, y, sum = 0;
printf("\nEnter a two-digit number: ");
scanf("%d", &x);
y = x;
while(y != 0) {
sum = sum + y % 10;
y = y / 10;
}
printf("\nSum of digits of %d is: %d", x, sum);
return 0;
}
405
Question 92
Question:
Solution:
#include<stdio.h>
int main() {
char ch;
printf("\nEnter a character: ");
scanf("%c", &ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
406
Question 93
Question:
#include<stdio.h>
int main() {
int i;
scanf("%d",&num); Output:
for(i=1; i<=num; i++) {
24 % 2 = 0
fact=fact*i;
} 25 % 2 = 1
Question 94
Question:
Solution:
407
#include<stdio.h>
int main() {
int x[12]={31,28,31,30,31,30,31,31,30,31,30,31}, m;
printf("\nEnter the month number: ");
scanf("%d",&m);
if(m>12 || m<1) {
printf("Invalid input");
}
else if(m==2) {
printf("\nNumber of days in month 2 is either 29 or 28");
}
else {
printf("\nNumber of days in month %d is %d", m, x[m-1]);
}
return 0; #include<stdio.h>
} int main() {
char *names[] = {
"Albert",
Question 95 "Alan",
"John",
"Mary" Albert
Write a program to concatenate two strings.
};
Alan
int i;
John
for(i=0;i<5;i++)
Solution: James
puts(*(names+i));
return(0); Mary
#include<stdio.h>
#include<string.h> }
int main() {
char a[1000], b[1000];
408
printf("\nEnter the first string: ");
scanf("%s", a);
printf("\nEnter the second string: ");
scanf("%s", b);
strcat(a, b);
printf("\nString produced by concatenation is: %s", a);
return 0;
}
Question 96
Question:
#include<stdio.h>
int main() {
Solution:
for(int x=2; x<=25; x=x+2) {
?
printf("Enter two numbers: \n");
return 0;
scanf("%d%d", &a, &b);
if(a>b) { }
409
return 0;
}
Question 97 #include<stdio.h>
int main() {
printf("*");
Solution:
}
#include<stdio.h>
return 0;
#include<string.h>
}
int main() {
char a[100], b[100];
Output:
printf("Enter the first string: \n");
scanf("%s", a); 1 2 3 *1 2 *1 *
printf("Enter the second string: \n");
scanf("%s", b);
if (strcmp(a,b) == 0) { #include<stdio.h>
printf("The 2 strings are equal.\n");
int main() {
}
puts("Albert Einstein");
else {
printf("The 2 strings are not equal.\n"); return 0;
} }
return 0;
} Output:
Albert Einstein
410
Question 98
Question:
Write a program to convert the upper case letter to lower case letter.
Solution:
#include<ctype.h>
#include<stdio.h>
int main() {
char ch;
ch = 'G';
printf("%c in lowercase is represented as %c", ch, tolower(ch));
return 0;
}
Question 99
Question:
Write a program to find the quotient and remainder of a entered dividend and divisor.
Solution:
#include<stdio.h>
411
int main() {
int dividend, divisor;
printf("\nEnter dividend: ");
scanf("%d", ÷nd);
printf("\nEnter divisor: ");
scanf("%d", &divisor);
printf("\nQuotient = %d\n", (dividend / divisor));
printf("\nRemainder = %d", (dividend % divisor));
return 0;
}
Question 100
Question:
Write a program to determine the Size of int, float, double and char.
Solution:
#include<stdio.h>
int main() {
printf("Size of char is: %ld byte\n",sizeof(char));
printf("Size of int is: %ld bytes\n",sizeof(int));
printf("Size of float is: %ld bytes\n",sizeof(float));
printf("Size of double is: %ld bytes", sizeof(double));
return 0;
}
412
Question 101
#include<stdio.h>
Question:
int main() {
Write a program to verify the password until it is correct.
int i;
?
printf("\n");
int main() {
} Output:
int x, y;
return 0;
} printf("\nEnter the value for x: ");
scanf("%d", &x);
scanf("%d", &y);
return 0;
413
Question 102
Question:
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int num;
printf("Input a positive or negative number: \n");
scanf("%d", &num);
printf("\nAbsolute value of |%d| is %d\n", num, abs(num));
return 0;
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
414
#include<stdio.h>
int main() {
float ht;
printf("\nEnter the height (in cm): ");
scanf("%f", &ht);
if(ht < 150.0) {
printf("Dwarf.\n");
}
else if((ht >= 150.0) && (ht < 165.0)) {
printf("Average Height.\n");
}
else if((ht >= 165.0) && (ht <= 195.0)) {
printf("Taller.\n");
} #include<stdio.h>
Output:
Question 104
6
Question:
Write a program to calculate the area of different geometric shapes using switch
statements.
Solution:
415
Robotics is a branch of engineering and computer science
that deals with the design, construction, operation, and use
of robots. Robots are programmable machines that can
#include<stdio.h>
carry out tasks autonomously, or with minimal human
int main() { intervention.
416
Question 105
Question:
Write a program to accept a character from the keyboard and print "Yes" if it is equal to y.
Otherwise print "No".
Solution:
#include<stdio.h>
int main() {
char ch;
printf ("Enter a character: "); #include<stdio.h>
24
25
The garbage values will be
printed after i = 5 26
-759135232
-1723617269
417
Question 106
Question:
Write a program that uses bitwise operators to multiply an entered value by four.
#include<stdio.h>
int main() {
Solution: for(int x=5; x>=1; x--) {
y = x; }
Output:
x = x << 2;
return 0;
printf("%ld x 4 = %ld\n", y, x); *****
}
return 0;
****
}
***
**
Question 107 *
Question:
Write a program to check whether a number entered by the user is power of 2 or not.
Solution:
418
#include<stdio.h>
#include<stdio.h>
int main() {
int x; #define A 16
} } Output:
A+B: 20
A-B: 12
A×B: 64
Question 108
A/B: 4
Question:
Solution:
#include<stdio.h>
int main() {
int side1, side2, side3;
printf("\nEnter the first side of the triangle: ");
scanf("%d",&side1);
printf("\nEnter the second side of the triangle: ");
419
scanf("%d",&side2);
printf("\nEnter the third side of the triangle: ");
scanf("%d",&side3);
if(side1 == side2 && side2 == side3) {
printf("\nThe given Triangle is equilateral.");
}
else if(side1 == side2 || side2 == side3 || side3 == side1) {
printf("\nThe given Triangle is isosceles.");
}
else {
printf("\nThe given Triangle is scalene.");
}
return 0;
}
Question 109
Question:
Write a program to print ASCII values of all the letters of the English alphabet from A to Z.
Solution:
#include<stdio.h>
int main() {
int i;
for(i='A'; i<='Z'; i++) {
420
printf("ASCII value of %c = %d\n", i, i);
}
return 0;
}
Question 110
Question:
Solution:
#include<stdio.h>
int main() {
int i, num, sum=0;
printf("Enter a number: ");
scanf("%d", &num);
for(i=2; i<=num; i=i+2) {
sum = sum + i;
}
printf("\nSum of all even number between 1 to %d is: %d", num, sum);
return 0;
}
421
Networking refers to the process of connecting different
Question 111 devices, systems, and networks together in order to
facilitate communication and information exchange. It
involves the use of various hardware and software
technologies, protocols, and standards to enable devices
Question: to communicate with each other and access shared
resources.
}
printf("\nSum of all odd number between 1 to %d is: %d", num, sum);
return 0;
}
Question 112
Question:
Solution:
422
#include<stdio.h>
int main() {
int x, y; #include<stdio.h>
1
Question 113
0
Question:
Write a program that allows you to enter the cost price and the selling price of a product
and calculate profit or loss.
Solution:
#include<stdio.h>
int main() {
int cp, sp;
printf("\nInput Cost Price: ");
scanf("%d", &cp);
423
printf("\nInput Selling Price: ");
scanf("%d", &sp);
if(sp > cp) { #include<stdio.h>
printf("Profit = %d", (sp - cp)); int main() {
}
int x[25], a;
else if(cp > sp) {
for(a = 0; a <= 24; a++);
printf("Loss = %d", (cp - sp));
} {
else { x[a] = a;
printf("No Profit No Loss.");
printf("\n%d", x[a]);
}
}
return 0;
} return 0;
Output:
25
Question 114
Question:
Write a program that display the pattern like a right angle triangle using an asterisk.
Solution:
#include<stdio.h>
int main() {
int rows;
printf("Input the number of rows: ");
scanf("%d", &rows);
for(int x=1; x<=rows; x++) {
424
for(int y=1; y<=x; y++)
printf("*");
printf("\n");
}
return 0;
}
Question 115
Question:
Write a program that display the pattern like a right angle triangle using a number.
Solution:
#include<stdio.h>
int main() {
int rows;
printf("Input the number of rows: ");
scanf("%d",&rows);
for(int x=1; x<=rows; x++) {
#include<stdio.h>
for(int y=1; y<=x; y++)
static int b;
printf("%d", y);
printf("\n"); int main() {
} static int c;
return 0; printf("%d %d", b, c); Output:
}
return 0;
00
}
425
Question 116
Question:
Write a program to determine the number and sum of all integers between 50 and 100
which are divisible by 2.
Solution:
#include<stdio.h>
int main() {
int x, sum=0;
printf("Numbers between 50 and 100, divisible by 2: \n");
for(x=51; x<100; x++) {
if(x%2==0) { #include<stdio.h>
return 0; 1
} 80
426
Question 117
Question:
Write a program that uses the function to determine whether a entered number is even or
odd.
#include<stdio.h>
int main() {
?
return (x & 1); }
}
int main() {
int x;
printf("Enter any number: ");
scanf("%d", &x);
if(myfunc(x)) {
printf("\nThe number you entered is odd.");
}
else {
printf("\nThe number you entered is even.");
}
return 0; #include<stdio.h>
} #include<math.h>
int main() {
Output:
printf("%f\n", log(50.0));
return 0; 3.912023
427
Question 118
Question:
Solution:
#include<stdio.h>
#include<math.h>
int main() {
int x;
printf("Enter any number: ");
scanf("%d",&x);
printf("Square root of %d is %.2lf", x, sqrt(x));
return 0;
}
Question 119
Question:
Solution:
#include<stdio.h>
428
Evolutionary computing is a subfield of artificial
#include<math.h> intelligence and computational intelligence that uses
evolutionary algorithms to solve complex optimization
int main() {
problems. It is inspired by the process of natural
int x, y; selection and evolution in biological organisms, and it
aims to mimic these processes in order to find optimal
printf("\nEnter the value for x: "); solutions to a wide range of problems.
scanf("%d", &x);
Evolutionary computing typically involves the use of
printf("\nEnter the value for y: "); genetic algorithms, which are a type of optimization
algorithm that uses principles of natural selection and
scanf("%d", &y);
genetics to evolve a population of potential solutions to
printf("\n%d^%d = %ld", x, y, (long)pow(x,y)); a problem. The algorithm generates a population of
candidate solutions, which are then evaluated and
return 0; selected for reproduction based on their fitness or
quality. Through a process of mutation, crossover, and
}
selection, the algorithm evolves the population towards
better solutions over successive generations.
#include<stdio.h>
int main() {
return 0;
#include<stdio.h>
#include<ctype.h> }
int main() {
char ch;
Output:
printf("Enter a character: ");
scanf("%c", &ch); "Hi," Albert, "Elsa!"
if(isdigit(ch)) {
printf("\n%c is a Digit", ch);
}
429
else if(isalpha(ch)) {
printf("\n%c is an Alphabet", ch);
}
else {
printf("\n%c is not an Alphabet, or a Digit", ch);
}
return 0;
}
Question 121
Question:
int main() {
#include<stdio.h> }
#include<ctype.h>
int main() { Output:
char a;
The Sum is: 33.000000
printf("Enter a character: ");
scanf("%c", &a);
if(isalnum(a)) {
printf("\n%c is an alphanumeric character.", a);
}
else {
430
printf("\n%c is NOT an alphanumeric character.", a);
}
return 0;
}
Question 122
Question:
?
#define SIZE 6
int main() {
431
Question 123
Question:
Write a program to check whether the entered character is a graphic character or not.
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
char a;
printf("Enter a character: ");
scanf("%c", &a);
if(isgraph(a)) {
printf("\n%c is a graphic character.", a);
}
Output:
else {
printf("\n%c is NOT a graphic character.", a); 0
}
0
return 0; #include<stdio.h>
0
}
int main() {
0
static int x[8];
0
for(int i = 0; i <= 7; i++)
0
printf("\n%d", x[i]);
return 0; 0
} 0
432
Question 124
Question:
#include<stdio.h>
In the switch condition,
int main() {
"i" is not an integer. We
Solution: float i = 6.1 ; cannot test floats in
switch statements.
switch (i) {
#include<stdio.h>
#include<ctype.h> case 0.1 :
} case 6.1 :
printf("\nAlbert");
return 0;
Error
Question 125 }
Question:
Write a program to check whether the entered character is a hexadecimal digit character
or not.
Solution:
433
Computer security refers to the
#include<stdio.h> protection of computer systems and
#include<ctype.h> networks from unauthorized access,
theft, damage, or other malicious
int main() { attacks. It involves implementing
char a; various measures such as firewalls,
encryption, antivirus software, access
printf("Enter a character: "); controls, and intrusion detection
scanf("%c", &a); systems to safeguard computers and
networks from security threats. The
if(isxdigit(a)) {
goal of computer security is to ensure
printf("\n%c is a hexadecimal digit character.", a); the confidentiality, integrity, and
availability of information stored on
}
or transmitted through computer
else { systems and networks. Computer
security is important for individuals,
printf("\n%c is NOT a hexadecimal digit character.", a);
businesses, governments, and other
} organizations that rely on computers
return 0; to store and process sensitive data.
Question 126
Question:
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
int i;
printf("The ASCII value of all control characters are: \n");
434
for(i=0; i<=127; i++) {
if(iscntrl(i)!=0) #include<stdio.h>
printf("\n %d ", i);
int main() {
}
if(printf("Albert Einstein")){}
return 0;
} return 0;
Output:
Albert Einstein
Question 127
Question:
Write a program to check whether the entered character is a white-space character or not.
Solution:
#include<stdio.h>
#include<stdio.h>
typedef int var;
#include<ctype.h>
int main() { var main() {
char c; var i = 6;
printf("Enter a character: ");
printf("%d + %d = %d\n", i, i, i+i);
scanf("%c", &c);
return 0;
if(isspace(c) == 0) {
printf("Not a white-space character."); }
}
else { Output:
printf("White-space character.");
6 + 6 = 12
}
return 0;
435
}
Question 128
Question:
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
char ch = 'a';
if(isprint(ch)) {
printf("\n%c is printable character.", ch);
}
else {
printf("\n%c is not printable character.", ch);
}
if(iscntrl(ch)) {
printf("\n%c is control character.", ch);
}
else {
printf("\n%c is not control character.", ch);
}
return (0);
436
}
int main() {
Question:
char name[10];
Write a program to calculate surface area of cube. printf("Enter your name: ");
fgets(name,10,stdin);
return 0;
Solution:
?
}
#include<stdio.h>
int main() {
int side;
long area;
printf("\nEnter the side of cube: ");
scanf("%d", &side);
area = 6*side*side;
printf("\nThe surface area of cube is: %ld", area);
return 0;
}
Question 130
Question:
437
#include<stdio.h>
Solution:
int main() {
#include<stdio.h> for(int i=12; i<=15; i=i+1) {
#include<stdlib.h>
printf("%d\t", i);
int main() {
int x =6, y=3; }
Output:
Question 131 12 13 14 15
Question:
#include<stdio.h>
int main() {
Solution: int i;
438
Question 132
Question:
#include<stdio.h>
int main() {
Solution:
printf("%d\n", 49);
#include<stdio.h>
printf("%1.2f\n",3.15698222);
int main() {
printf("%d\n", 496596);
int x=2;
printf("%d", x<<1); printf("%1.1f\n",0.00056);
return 0; return 0;
Output:
}
}
49
3.16
0.0
Question:
Solution:
#include<stdio.h>
int main() {
int x=12;
printf("%d", x>>1);
439
return 0;
}
Question 135
Question:
Solution:
#include<stdio.h>
int main() {
int radius;
float PI = 3.141592;
printf("\nEnter the radius of sphere: ");
scanf("%d", &radius);
float volume = (4/3)*(PI*radius*radius*radius);
?
printf("\nThe volume of sphere is: %f", volume);
return 0;
#include<stdio.h>
}
int main() {
int c = getc(stdin);
Question 136
printf("You have entered the character '%c'.\n",c);
return 0;
Question:
}
440
Solution:
#include<stdio.h>
int main() {
int r1, r2, r3;
float PI = 3.141592;
printf("\nEnter the radius of the ellipsoid of axis 1: ");
scanf("%d", &r1);
printf("\nEnter the radius of the ellipsoid of axis 2: ");
scanf("%d", &r2);
printf("\nEnter the radius of the ellipsoid of axis 3: ");
scanf("%d", &r3);
float volume = (4/3)*(PI*r1*r2*r3);
printf("\nThe volume of ellipsoid is: %f", volume);
return 0;
}
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
#include<stdio.h>
441
int main() {
int x, y; #include<stdio.h>
Output:
14 is greater than 17
Question 138
Question:
Solution:
#include<stdio.h>
int main() {
int a,b,c;
float avg;
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
442
scanf("%d",&b);
printf("\nEnter the third number: ");
scanf("%d",&c);
avg=(a+b+c)/3.0;
printf("\nAverage of three numbers is: %f", avg);
return 0;
}
Question 139
Question:
Write a program to read integer "n" and print first three powers (n1, n2, n3).
443
static memory allocation dynamic memory allocation
allocation of memory done at allocation of memory done at the time of
compilation time and it stays the same running the program and it increases or
throughout the entire run of the decreases throughout the entire run of the
program program and it is released or freed when
not required or used
C Program:
#include<stdio.h>
int main()
{ create a file named myfiles.txt
FILE *fp;
fp = fopen("myfiles.txt","w");
return 0;
}
The w means that the file is being opened for writing − and if the file
C Program:
#include<stdio.h>
int main()
{
The fprintf function writes the text C
FILE *fp;
fp = fopen("myfiles.txt","w"); Programming to the file myfiles.txt.
fprintf(fp, "%s", "C Programming");
return 0;
}
444
#include<bits/stdc++.h>
int main() {
swap(a, b);
return 0;
Output:
Value of a: 15
Value of b: 25
Computer architecture refers to the design of computer systems, including their organization, components, and how they
operate together to perform tasks. It encompasses the hardware and software components of a computer system and their
interactions. Computer architecture defines the structure and behavior of a computer system, including the processing units,
memory, input or output devices, and communication protocols between the components.
The architecture of a computer system is critical in determining its performance, power consumption, and overall efficiency.
It is also important for determining the compatibility and interoperability of different hardware and software components.
Computer architecture plays a crucial role in the design and development of computer systems, including desktops, laptops,
servers, and mobile devices. Understanding computer architecture is essential for computer engineers, software developers, and
system administrators who are involved in designing, developing, and maintaining computer systems.
445
C++ Exercises
In the 1970s, Bjarne Stroustrup, a Danish computer scientist, created the C++ programming
language. The initial name of C++ was "C with classes." By practicing C++ programs, you can
learn the C++ programming language most effectively. An all-purpose programming language is
C++. It offers facilities for low-level memory manipulation together with imperative, object-
oriented, and generic programming features. It is used to create machine learning tools, web
browsers, video games, and operating systems. Examples on fundamental C++ ideas can be
found on this chapter. It is encouraged that you use the programs as references and test the
concepts on your own. Exercises in C++ are a great way to practise programming, develop your
446
Question 1
Question:
Solution: #include<iostream>
Albert Einstein
Question 2
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
447
int height = 8;
int width = 5;
int perimeter = 2*(height + width);
cout<<"Perimeter of the rectangle is: " << perimeter << " cm\n";
int area = height * width;
cout<<"Area of the rectangle is: "<< area << " square cm\n";
return 0;
}
Question 3
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int radius = 4;
float perimeter = 2*3.14*radius;
cout<<"Perimeter of the circle is: " << perimeter << " cm\n";
float area = 3.14*radius*radius;
cout<<"Area of the circle is: "<< area << " square cm\n";
return 0;
}
448
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
#include<iostream>
int main() {
Solution:
int x= 26; // Now x is 15
x = 56; // Now x is 10
#include<iostream>
using namespace std; cout << x;
449
Question
450
Question:
Write a program that accepts two numbers from the user and calculate the product of the
two numbers.
A relational database is a type of database management
system (DBMS) that stores and organizes data in tables with
rows and columns. In a relational database, data is stored in
multiple related tables, and the relationships between these
Solution: tables are defined by their shared columns or keys. The most
common type of relational database is a Structured Query
Language (SQL) database, which allows users to manipulate
#include<iostream> and query the data stored within it using SQL commands.
using namespace std;
Relational databases are widely used in business and other
int main() { applications to manage large amounts of structured data,
int a, b, mult; such as customer information, sales records, and inventory
data. They offer several advantages over other types of
cout<<"\nEnter the first number: ";
databases, including their ability to support complex
cin>>a; relationships between data, their scalability, and their ability
to ensure data consistency and accuracy through the use of
cout<<"\nEnter the second number: ";
constraints and transaction processing.
cin>>b;
mult = a * b;
cout<<"\nProduct of the above two numbers is: " << mult;
return 0;
}
Question 6
Question:
Write a program that accepts three numbers and find the largest of three.
450
Structured storage refers to a type of file system that is designed to
store and manage structured data in a hierarchical and organized manner.
It is commonly used for storing and managing complex data types such
as multimedia files, large text documents, and database files.
Solution:
Structured storage systems typically use a hierarchical directory
#include<iostream> structure to organize data into folders and subfolders, with each folder
containing files that are related to a particular aspect of the data being
using namespace std; stored. These files can be of different sizes, types, and formats, and are
typically stored as binary data. One of the key features of structured
int main() { storage is that it allows applications to access data within files without
int x, y, z; having to read or write the entire file. This is accomplished by using a
mechanism called "streaming", which allows applications to access
cout<<"\nEnter the first number: "; specific sections of a file without loading the entire file into memory.
cin>>x;
Structured storage is commonly used in enterprise applications, such as
cout<<"\nEnter the second number: "; document management systems, content management systems, and
multimedia applications. It is also used in relational database systems,
cin>>y; where large amounts of structured data are stored in a hierarchical
cout<<"\nEnter the third number: "; manner for efficient retrieval and manipulation.
cin>>z;
return 0;
}
451
Question
452
Question:
Write a program that reads three floating values and check if it is possible to make a
triangle with them. Also calculate the perimeter of the triangle if the entered values are
valid.
Data mining is the process of discovering hidden
patterns, correlations, and trends within large sets of
data using statistical and computational methods. It
involves extracting meaningful insights from complex
data sets by using automated or semi-automated
Solution: techniques to identify patterns and relationships that
may not be immediately apparent.
return 0;
}
452
Question 8
Question:
Write a program that reads an integer between 1 and 7 and print the day of the week in
English.
Solution:
#include<iostream>
using namespace std;
int main() {
int day;
cout<<"\nEnter a number between 1 to 7 to get the day name: ";
cin>>day; Compiler theory refers to the study of how programming
languages are translated into machine-readable code by a
switch(day) { compiler. It encompasses a range of topics, including syntax
analysis, semantic analysis, code generation, optimization, and
case 1 : cout<<"Monday\n"; break; debugging. There are various steps involved in the compilation
of a program. First, the source code of the program is analyzed
case 2 : cout<<"Tuesday\n"; break;
to check for syntax errors and to create a syntax tree that
case 3 : cout<<"Wednesday\n"; break; represents the structure of the program. Next, semantic analysis
is performed to check for semantic errors and to determine the
case 4 : cout<<"Thursday\n"; break; meaning of the program's constructs. After this, the code is
generated, which involves translating the high-level code into
case 5 : cout<<"Friday\n"; break; low-level code that can be executed by the computer. Finally,
the generated code is optimized to improve its performance.
case 6 : cout<<"Saturday\n"; break;
Compiler theory is an important area of study for computer
case 7 : cout<<"Sunday\n"; break; science and programming, as it is essential for developing
efficient and effective software. It also plays a critical role in
default : cout<<"Enter a number between 1 to 7.";
the development of new programming languages, as it provides
} insights into the design and implementation of language
constructs and the trade-offs between expressiveness, ease of
return 0; use, and performance. Some of the key topics within compiler
theory include parsing algorithms, language design and syntax,
} type systems, memory management, optimization techniques,
and debugging and error handling. Advances in compiler theory
have led to significant improvements in the performance and
reliability of software, and have helped to make programming
more accessible and easier to learn for beginners.
453
Question 9
Question:
Solution: #include<iostream>
return 0;
Question 10
Question:
Solution:
454
#include<iostream>
#include<cmath>
using namespace std;
int main() { #include<iostream>
int a, b;
#include<cstring>
a=2;
using namespace std;
b = pow((a), 2);
cout<<"The square of a is: "<< b; int main() {
return 0; string x = "Albert";
}
cout << x[0];
// Output: A
return 0;
Question 11
}
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
a = 2;
b = 3;
if(a>b) {
cout<<"a is greater than b";
}
else {
455
cout<<"b is greater than a";
}
return 0;
}
Question 12
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, avg, sum = 0;
int num [5] = {16, 18, 20, 25, 36};
for(i=0; i<5; i++) {
sum = sum + num [i];
avg = sum/5;
}
cout<<"\nSum of the Elements in the array is: "<< sum;
cout<<"\nAverage of the elements in the array is: " << avg;
return 0;
}
456
Question 13
Question:
Write a program that prints all even numbers between 1 and 25.
Solution:
#include<iostream>
using namespace std;
int main() {
cout<<"Even numbers between 1 to 25:\n"; #include<iostream>
for(int i = 1; i <= 25; i++) {
#include<cstring>
if(i%2 == 0) {
using namespace std;
cout<< i << endl;
} int main() {
} string x = "Albert";
return 0;
x[0] = 'E';
}
cout << x;
// Output: Elbert
return 0;
Question 14
}
Question:
Write a program that prints all odd numbers between 1 and 50.
Solution:
457
Quantum computing theory has many potential applications in
computer science, including the ability to solve certain
#include <iostream> computational problems exponentially faster than classical
using namespace std; computers. This has significant implications for areas such as
cryptography, optimization, and algorithm design. One of the
int main() { most famous quantum algorithms is Shor's algorithm, which
cout<<"Odd numbers between 1 to 50:\n"; can factor large numbers exponentially faster than the best
known classical algorithm. This has important implications for
for(int i = 1; i <= 50; i++) { cryptography, as many encryption schemes rely on the fact that
if(i%2 != 0) { factoring large numbers is computationally infeasible. Another
quantum algorithm with significant potential applications is
cout<<i<<endl; Grover's algorithm, which provides a quadratic speedup for
} searching an unsorted database. This has implications for
database searching, optimization, and machine learning.
}
return 0; Quantum computing theory is also important in the
development of quantum machine learning, which seeks to
}
develop machine learning algorithms that can take advantage of
the properties of quantum computers. This includes the
development of quantum neural networks, which can learn and
recognize patterns in quantum data. However, quantum
computing theory also poses significant challenges in computer
Question 15 science, including the issue of error correction and the
development of efficient algorithms that can take advantage of
the unique properties of quantum computers. Many researchers
Question: are working to overcome these challenges and develop practical
applications for quantum computing in computer science.
Write a program to print the first 10 numbers starting from one together with their
Solution:
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=10; i++) {
cout<<"Number = " << i << " its square = " << i*i << " its cube = " << i*i*i
<<endl;
}
return 0;
458
}
Question 16
#include<iostream>
// Output: 60
return 0;
Solution:
}
#include<iostream>
using namespace std;
int main() {
char M;
cout<<"Enter any character: ";
cin>>M;
cout<<"ch = "<< M;
return 0;
}
Question 17
Question:
Write a program to print the multiplication table of a number entered by the user.
459
Computability theory is a branch of computer science and
mathematics that deals with the study of what can be
computed and how effectively it can be computed. It
Solution: investigates the limitations of computing machines, the scope
of what can be computed, and the extent to which problems
can be solved algorithmically. One of the main concepts in
#include<iostream> computability theory is the notion of computable functions.
using namespace std; A function is said to be computable if there exists an
algorithm that can compute its values for any input. The study
int main() { of computable functions leads to the concept of Turing
machines, which are abstract models of computation that can
int n, i;
perform any computation that can be done by any algorithm.
cout<<"Enter any number: "; Another important concept in computability theory is the
halting problem. The halting problem asks whether it is
cin>>n; possible to determine, for a given input and program, whether
for( i=1; i<=5; i++) the program will halt or run indefinitely. The answer to this
problem is no, and it has important implications for the limits
cout<< n <<" * "<< i <<" = "<< n*i <<endl; of computability.
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, product = 1;
for(i=1; i<=10; i++) {
product = product * i;
460
}
cout<<"The product of the first 10 digits is: " << product;
return 0;
}
Question 19
Question:
Solution:
#include<iostream>
using namespace std;
#include<iostream>
int main() {
int a; #include<cmath>
// Output: 1.38629
return 0;
461
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"Enter the first number: ";
cin>>x;
cout<<"Enter the second number: ";
cin>>y;
if(x-y==0) {
cout<<"The two numbers are equivalent";
}
else {
cout<<"The two numbers are not equivalent"; #include<iostream>
} using namespace std;
return 0;
int main() {
}
cout << (20 > 19);
// Output: 1
return 0;
462
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b, c;
cout<<"Enter the first number: ";
cin>>a;
cout<<"Enter the second number: ";
cin>>b;
c = a % b;
cout<<"The remainder of " << a << " and " << b << " = " << c;
return 0;
}
Question 22
Question:
463
Solution: #include<iostream>
#include<cstring>
#include<iostream>
using namespace std;
using namespace std;
int main() {
char i; void myfunc(string name, int age) {
for(i='A'; i<='Z'; i++) {
cout << name << " John. " << age << " years old. \n";
cout << i << endl;
}
}
return 0;
?
} int main() {
myfunc("Albert", 73);
myfunc("Elsa", 14);
myfunc("David", 30);
Question 23
return 0;
Question: }
Solution:
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char str[1000];
cout<<"Enter a string to calculate its length: ";
cin>>str;
cout<<"The length of the entered string is: "<< strlen(str);
return 0;
464
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
if(islower(ch))
cout<<"The given character is a lower case letter";
else
cout<<"The given character is a upper case letter";
return 0;
}
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
465
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'A';
if(isupper(ch))
cout<<"The given character is a upper case letter";
else
cout<<"The given character is a lower case letter";
return 0;
}
Question 26
Question:
Write a program to convert the lower case letter to upper case letter.
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
char b = toupper(ch);
466
cout<<"Lower case letter "<<ch<<" is converted to Upper case letter "<<b;
return 0;
}
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches.
Solution:
#include<iostream>
using namespace std;
#define x 2.54
int main() {
double inch, cm;
cout<<"Enter the distance in cm: ";
cin>>cm;
inch = cm / x;
cout<<"\nDistance of "<< cm << " cms is equal to " << inch << " inches";
return 0;
}
467
Question 28 Procedural programming is a programming paradigm that is
based on the concept of procedures, also known as subroutines
or functions. A procedure is a group of instructions that
performs a specific task, and can be called or executed from
Question:
different parts of a program. In procedural programming, a
program is composed of one or more procedures, which can be
Write a program to print the output: organized into modules or libraries. The procedures are
typically organized in a step-by-step manner, with each
Einstein [0] = E procedure calling other procedures as needed to perform its
task.
Einstein [1] = I
Einstein [2] = N The primary focus of procedural programming is on the
procedures themselves, and how they interact with each other
Einstein [3] = S and with the data in a program. Data in a procedural program
is typically organized into data structures, such as arrays,
Einstein [4] = T
records, or linked lists. One of the main advantages of
Einstein [5] = E procedural programming is its simplicity and ease of use. It
is often used for small to medium-sized programs, and is
Einstein [6] = I particularly well-suited for applications that involve simple
data processing, such as mathematical calculations or file
Einstein [7] = N
manipulation.
468
Question 29
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=10; i++) {
cout<< "Hello World"<< endl;
}
return 0;
}
Question 30
Question:
Solution:
#include<iostream>
using namespace std;
469
Formal semantics is a branch of theoretical linguistics that aims to provide a precise mathematical
framework for describing the meaning of natural language expressions. It is concerned with
int main() { developing formal models of the structure and interpretation of language, using tools from logic,
mathematics, and computer science. Formal semantics is based on the idea that the meaning of a
int i =1; sentence can be determined by a set of rules that specify how its component parts combine to form a
complete expression. These rules can be formalized using mathematical notation and logical symbols,
do {
and can be used to generate a precise semantic representation of the sentence. There are several
cout<<" \ni = "<< i++; different approaches to formal semantics, including:
} while(i<=5); • Model-theoretic semantics: This approach uses mathematical models to represent the meaning
return 0; of sentences. The models consist of sets of objects and relations between them, and the meaning
of a sentence is determined by whether it is true or false in the model.
} • Type-theoretic semantics: This approach uses type theory to provide a formal description of the
structure of language expressions. Each expression is assigned a type, which describes its
properties and how it can be combined with other expressions.
• Situation semantics: This approach is based on the idea that the meaning of a sentence depends
on the situation in which it is used. The situation is represented as a set of facts, and the meaning
of the sentence is determined by how it relates to these facts.
Question 31
Formal semantics is used in a range of applications, including natural language processing, machine
translation, and computational linguistics. It provides a rigorous framework for analyzing and
understanding the meaning of language, and has contributed to the development of new theories of
Question: syntax and semantics in linguistics.
Solution:
#include<iostream>
using namespace std;
int main() {
int a = 2;
if(isalpha(a)) {
cout<<"The character a is an alphabet";
}
else {
cout<<"The character a is not an alphabet";
}
return 0;
}
470
Question 32
Question:
471
Question 33
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char c;
cout << "Enter a character: ";
cin >> c;
cout << "The ASCII Value of " << c << " is " << int(c);
return 0;
}
Question 34
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder will be 2.
Solution:
472
#include<iostream> Programming language theory is the study of the fundamental concepts and
using namespace std; principles that underlie the design and implementation of programming languages. It
is concerned with understanding how programming languages work, how they are
int main() { structured, and how they can be used to express different kinds of computations.
int x, i; Programming language theory encompasses a wide range of topics, including:
descending order.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
cout<<"\nEnter a pair of numbers (for example 22,12 | 12,22): ";
cout<<"\nEnter the first number: ";
473
cin>>a;
cout<<"\nEnter the second number: ";
cin>>b;
if (a>b) {
cout<<"\nThe two numbers in a pair are in descending order.";
}
else {
cout<<"\nThe two numbers in a pair are in ascending order.";
}
return 0;
}
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
float c;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
474
cin>>b;
if(b != 0) {
c = (float)a/(float)b;
cout<<a<<"/"<<b<<" = "<< c;
}
else {
cout<<"\nDivision not possible.\n";
}
return 0;
}
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, i;
cout<<"Enter a number: ";
cin>>x;
for(i=1; i<=50; i++) {
if((i%x)==2 || (i%x) == 3) {
cout<<i<<endl;
475
}
}
return 0;
}
Question 38
Question:
Write a program that adds up all numbers between 1 and 100 that are not divisible by 12.
Solution:
Software engineering is the systematic process of designing,
#include<iostream> developing, testing, and maintaining software. It is a discipline that
applies engineering principles to the creation of software products and
using namespace std;
systems, with the goal of developing high-quality, reliable, and efficient
int main() { software that meets the needs of users and stakeholders.
int x =12, i, sum = 0;
Software engineering involves a range of activities, including
for(i=1; i<=100; i++) { requirements analysis, software design, coding, testing, and maintenance.
It also includes project management and quality assurance activities,
if((i%x)!= 0) {
such as software configuration management, software metrics, and
sum += i; software process improvement.
}
The software engineering process typically involves several phases,
} such as planning, requirements gathering, design, implementation,
cout<<"\nSum: "<<sum; testing, and deployment. Each of these phases is essential to ensuring
that the software is developed to meet the needs of users and
return 0; stakeholders, is of high quality, and can be maintained over time.
}
Software engineering is a complex and interdisciplinary field, with
many sub-disciplines, such as software architecture, software testing,
software maintenance, and software project management. It requires
expertise in areas such as computer science, mathematics, and
engineering, as well as an understanding of business and user needs.
476
Question 39
Question:
Question 40 Designing an algorithm can be a complex process, and it often requires a deep
understanding of the problem domain and the programming language being used.
However, with practice and experience, anyone can become proficient in algorithm design
and develop efficient and effective solutions to complex problems.
Question:
Write a program that reads a number and find all its divisor.
Solution:
477
Automata theory is a branch of computer science that deals
#include<iostream>
with the study of abstract machines or computational models
using namespace std; that can perform various operations on strings or symbols.
int main() { These machines are used to model and describe the behavior
of systems that exhibit complex behavior, such as natural
int x, i; language processing, computer languages, and artificial
cout<<"\nEnter a number: "; intelligence.
cout<<i<<endl;
The theory behind automata is to design computational
} models that can process and recognize patterns in strings
or symbols, and make decisions based on the input. The
}
different models of automata are used to study the different
return 0; levels of complexity in computation, and to design
algorithms that can efficiently solve complex problems.
}
Automata theory has many practical applications, including
in compiler design, natural language processing, artificial
intelligence, and database systems. By understanding the
computational power and limitations of different automata
Question 41 models, computer scientists can design efficient and
effective algorithms for solving complex problems in
various fields.
Question:
Write a program to find the incremented and decremented values of two numbers.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b, c, d, e, f;
a = 10;
b=12;
478
c=a+1;
d=b+1;
e=a-1;
f=b-1;
cout<<"The incremented value of a = "<< c << endl;
cout<<"The incremented value of b = "<< d << endl;
cout<<"The decremented value of a = "<< e << endl;
cout<<"The decremented value of b = "<< f << endl;
return 0;
}
Question 42
Question:
Solution:
#include<iostream>
using namespace std;
int square();
int main() {
int answer;
answer = square();
cout<<"The square of the entered number is: "<< answer;
return 0;
}
int square() {
479
int x;
cout<<"Enter any number: ";
cin>>x;
return x*x;
}
Question 43
Question:
Write a program that accepts principal amount, rate of interest, time and compute the
simple interest.
Solution:
#include<iostream>
using namespace std;
int main() {
int P,T, R, SI;
cout<<"Enter the principal amount: ";
cin>>P;
cout<<"Enter the time: ";
cin>>T;
cout<<"Enter the rate of interest: ";
cin>>R;
SI = P*T*R/100;
cout<<"The simple interest is: "<<SI;
return 0;
}
480
Question 44
Question:
Write a program that swaps two numbers without using third variable.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
cout<<"\nEnter the value for a: ";
cin>>a; Git is a distributed version control system that is
cout<<"\nEnter the value for b: "; open-source, free, and made to manage projects of
cin>>b; all sizes quickly and effectively. It was created by
cout<<"\nBefore swapping: " <<a <<" "<<b; Linus Torvalds in 2005 for development of the
a=a+b; Linux kernel, and since then has become one of the
b=a-b; most widely used version control systems in the
a=a-b;
software development industry. Git allows multiple
cout<<"\nAfter swapping: " <<a<<" "<<b;
users to work on the same project simultaneously,
return 0;
while keeping track of changes made to the
}
codebase and providing features for managing and
merging these changes. Git is used not only for
software development but also for managing
changes to any type of file, such as documentation,
configuration files, and even images.
481
Question 45
Question:
Write a program to find the greatest of two entered numbers using pointers.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y, *p, *q;
cout<<"Enter the value for x: ";
cin>> x;
cout<<"Enter the value for y: ";
cin>> y;
Docker is a popular open-source platform for building,
p = &x;
deploying, and managing applications in containers. A
q = &y;
container is a lightweight and standalone executable package
if(*p>*q) {
that includes everything needed to run an application, such as
cout<<"x is greater than y";
code, libraries, and dependencies. Docker allows developers to
}
package their applications and dependencies into a container
else {
image, which can be easily shared and run across different
cout<<"y is greater than x";
environments, such as development, testing, and production.
}
Docker containers provide a consistent environment for
return 0;
applications, reducing compatibility issues and making it easier
}
to deploy and scale applications. Docker is widely used in
software development and deployment, particularly in modern
cloud-based and microservices architectures. With Docker,
developers can build, test, and deploy applications quickly and
efficiently, while operations teams can manage and scale these
applications with ease.
482
A computer's operating system, sometimes known as
Question 46 an OS, is a piece of software that controls the hardware
and software resources of the system and offers standard
services to applications running on the system. The
Question: primary function of an operating system is to act as an
intermediary between the computer hardware and the
applications that run on it. It provides a user interface,
***Write a program to print the output: manages the computer's memory and processing
body [b] = b resources, and controls input or output devices such as
keyboards, screens, and printers.
body [o] = o
The main functions of an operating system include
body [d] = d managing the allocation of resources, scheduling
body [y] = y processes, providing security and protection, managing
file systems, and providing a user interface. Operating
*** systems are essential for the functioning of modern
computer systems, including desktop computers,
servers, and mobile devices. Windows, macOS, Linux,
and Android are some common operating systems.
Operating systems play a crucial role in the performance
and reliability of computer systems and are a
Solution: fundamental component of computer science and
computer engineering.
#include<iostream>
using namespace std;
int main() {
char i;
char body [4] = {'b', 'o', 'd', 'y'};
for(i=0; i<4; i++)
cout<<"\n body ["<<body[i] <<" ] = "<< body[i] << endl;
return 0;
}
Computer graphics refers to the creation, manipulation, and display of visual content using computer
software and hardware. It involves the use of mathematical algorithms, digital tools, and techniques to
create images, animations, and visual effects. Computer graphics is used in a wide range of applications,
including digital art, video games, film and television, product design, scientific visualization, and more.
Computer graphics can be divided into two categories: raster graphics and vector graphics. Raster
graphics are composed of pixels and are used for creating images and photographs, while vector graphics
use mathematical formulas to create geometric shapes and are used for creating logos and illustrations.
The field of computer graphics encompasses various subfields, including computer-aided design (CAD),
3D modeling, computer animation, virtual reality, and augmented reality. Computer graphics is a rapidly
evolving field that is constantly advancing due to advancements in computer technology and software
development. It plays a crucial role in many industries and is an essential part of modern design and
communication.
483
Question 47
Question:
Write a program to calculate the discounted price and the total price after discount
Given:
484
return 0;
}
Question 48
Question:
Write a program to print the first ten natural numbers using while loop statement.
#include<iostream>
Solution:
#include<cstring>
#include<iostream>
using namespace std;
using namespace std;
void myfunc(string x) {
int main() {
int i = 1; cout << x << " Einstein\n";
while(i<=10) { }
cout<<"\n" << i++;
}
?
return 0; int main() {
} myfunc("David");
myfunc("Elsa");
myfunc("John");
Question 49 return 0;
}
Question:
485
Solution:
#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter the integer from keyboard: ";
cin>>x;
cout<<"\nEntered value: "<< x;
cout<<"\nThe left shifted data is: " << (x<<=2);
return 0;
}
Question 50
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter the integer from keyboard: ";
cin>>x;
486
cout<<"\nEntered value: "<< x;
cout<<"\nThe right shifted data is: " << (x>>=2);
return 0;
}
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
the absolute difference if x is greater than 21.
#include<iostream>
487
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
Computational complexity theory is a branch of computer science
and mathematics that focuses on classifying computational problems
according to their level of difficulty, and studying the resources
required to solve them. It aims to understand the limitations and
capabilities of algorithms and computing systems in solving problems
Solution: efficiently.
488
Question 53
Question:
return 15 + x;
}
Solution:
?
#include<iostream>
int main() {
using namespace std;
int main() { cout << myfunc(13);
489
Question 54
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float fahrenheit, celsius;
celsius = 36;
fahrenheit = ((celsius*9)/5)+32;
cout<<"\nTemperature in fahrenheit is: "<<fahrenheit;
return 0;
}
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
is 50 or if their sum is 50.
490
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
if(x == 50 || y == 50 || (x + y == 50)) {
cout<<"\nTrue";
}
else {
cout<<"\nFalse";
}
return 0;
}
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
#include<iostream>
491
using namespace std;
int main () {
int x, even = 0, odd = 0, positive = 0, negative = 0;
cout<<"\nPlease enter 18 numbers: \n";
for(int i = 0; i < 18; i++) {
cin>>x;
if (x > 0) {
positive++;
}
if(x < 0) {
negative++;
}
if(x % 2 == 0) {
even++;
}
if(x % 2 != 0) {
odd++;
}
}
cout<<"\nNumber of even values: "<<even;
cout<<"\nNumber of odd values: "<<odd;
cout<<"\nNumber of positive values: "<<positive;
cout<<"\nNumber of negative values: "<<negative;
return 0;
}
492
Question 57
Question:
Solution:
#include<iostream>
using namespace std;
int main() { Visual Studio Code, commonly known as VS Code, is
Question:
Write a program that reads a student's three subject scores (0-100) and computes the
average of those scores.
493
Solution:
Google Cloud Platform, also known as GCP, is a
#include<iostream> cloud computing platform and service provided by
using namespace std; Google. It provides a wide range of services and
solutions, including infrastructure as a service (IaaS),
int main() { platform as a service (PaaS), and software as a service
float score, total_score = 0; (SaaS). GCP enables developers to build, deploy, and
manage applications and services on Google's global
int subject = 0; network of data centers.
cout<<"Enter three subject scores (0-100):\n";
GCP provides a wide range of services and solutions,
while (subject != 3) { including virtual machines, container services,
cin>>score; serverless computing, data storage, database services,
analytics, and artificial intelligence. It also offers a
if(score < 0 || score > 100) {
variety of developer tools and services, including
cout<<"Please enter a valid score.\n"; Google Cloud SDK, Google Cloud Build, and Google
Cloud Functions.
}
else { GCP is designed to be flexible and scalable, making it
suitable for businesses of all sizes. It provides various
total_score += score;
pricing options, including pay-as-you-go, subscription-
subject++; based, and free plans, allowing businesses to choose the
} best pricing plan that meets their needs and budget.
Question:
494
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=5; i++) {
if(i==3) { JIRA is a software development tool developed by Atlassian.
495
Solution:
Azure, also known as Microsoft Azure, is a cloud
1 computing platform and service provided by Microsoft. It
2 provides a wide range of services and solutions, including
Linux infrastructure as a service (IaaS), platform as a service
(PaaS), and software as a service (SaaS). Azure enables
developers to build, deploy, and manage applications and
services on Microsoft's global network of data centers.
#include<iostream>
using namespace std; Azure provides a wide range of services and solutions,
int main() { including virtual machines, container services, serverless
for( ; ; ) { computing, data storage, database services, analytics, and
cout<<"This loop will run forever.\n"; artificial intelligence. It also offers a variety of developer
} tools and services, including Azure DevOps, Visual
return 0; Studio, and GitHub integration.
}
#include<iostream>
496
using namespace std;
int main() {
cout<<"Hello,world!";
return 0;
cout<<"Hello,world!";
}
Apache Maven is a build automation tool and a powerful
project management tool developed by the Apache
Software Foundation. It is widely used for Java projects,
Solution: but can also be used for other programming languages like
C#, Ruby, and Scala. Maven simplifies the process of
Hello,world! building, testing, and deploying Java-based applications by
providing a standardized way to manage project
dependencies, versioning, and packaging.
#include<iostream>
Maven uses an XML-based project object model (POM) to
using namespace std;
define a project, its dependencies, and its build
int main () {
configuration. This makes it easier to manage complex
cout<<"linux\n";
projects and ensures that all developers are using the same
exit (0);
build processes and configurations. Maven manages
cout<<"php\n";
dependencies by automatically downloading and
return 0;
integrating them into the project build, reducing the need
} for manual management.
497
using namespace std;
int main() {
for(int i=1; i<=5; i++) { Jenkins is an open-source automation server that is used to
498
Solution:
Kubernetes, commonly referred to as K8s, is an open-source container
10
orchestration platform developed by Google. It automates the deployment,
scaling, and management of containerized applications. Kubernetes provides
a platform-agnostic way to manage containerized applications and services,
enabling developers to deploy and manage their applications across multiple
cloud providers and on-premise data centers.
#include<iostream>
using namespace std;
Kubernetes enables developers to deploy containerized applications and
#define A 15
services by defining a set of desired states in a Kubernetes manifest file.
int main() {
Kubernetes then automatically schedules and manages the containers,
int x;
ensuring that the desired state is maintained. It provides features such as
x=A;
automatic scaling, rolling updates, self-healing, and load balancing, making it
cout<<x;
easier to manage and scale containerized applications.
return 0;
}
Kubernetes is designed to be highly available, scalable, and fault-tolerant. It
can run on a cluster of machines, making it possible to manage large-scale
applications with ease. Kubernetes also provides an API that enables
developers to automate the management of their containerized applications,
making it a popular choice for DevOps teams.
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x = 20;
cout<<"Inverse of tan x = "<< atan(x);
499
return 0;
}
Solution:
|-2.5| = 2.5
500
#include<iostream>
using namespace std;
int main() { Logic programming is a programming paradigm that is based on the use
of mathematical logic for problem-solving. In logic programming,
int x=12, y =3;
programs are written in terms of a set of rules and facts, and the execution
cout<<abs(-x-y); of the program involves deriving logical conclusions from these rules and
return 0; facts.
Solution:
15
501
#include <iostream> A programming paradigm called "object-oriented programming"
(OOP) is founded on the idea that "objects" can hold both data and
using namespace std; the code needed to manipulate that data. In OOP, programs are
int main() { designed by creating classes, which are templates or blueprints for
creating objects. Each object created from a class has its own unique
int x=12, y =3; data and behavior, but shares the same structure and behavior
cout<< x-(-y); defined in the class.
Question:
Solution:
#include<iostream>
using namespace std;
502
int main() {
int num [] = {11, 22, 33, 44, 55, 66};
int n = sizeof(num) / sizeof(num [0]);
cout<<"Size of the array is: " << n;
return 0;
}
Question 61
Question:
Write a program that prints a sequence from 1 to a given integer, inserts a plus sign
between these numbers, and then removes the plus sign at the end of the sequence.
Solution:
#include<iostream>
using namespace std;
int main () {
int x, i;
cout<<"\nEnter a integer: \n";
cin>>x;
if(x>0) {
cout<<"Sequence from 1 to "<< x << ":\n";
for(i=1; i<x; i++) {
cout<<i<<"+";
}
cout<<i<<"\n";
}
503
return 0;
}
Question 62
Question:
Write a program to verify whether a triangle's three sides form a right angled triangle or
not.
Solution:
#include<iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter the three sides of a triangle: \n";
cin>>a;
cin>>b;
cin>>c;
if((a*a)+(b*b)==(c*c) || (a*a)+(c*c)==(b*b) || (b*b)+(c*c)==(a*a)) {
cout<<"Triangle's three sides form a right angled triangle.\n";
}
else {
cout<<"Triangle's three sides does not form a right angled triangle.\n";
}
return 0;
}
504
Question 63
Question:
Write a program that will find the second-largest number among the user's input of three
numbers.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b, c;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
cin>>b;
cout<<"\nEnter the third number: ";
cin>>c;
if(a>b && a>c) {
if(b>c)
cout<<b<<" is second largest number among three numbers";
else
cout<<c<<" is second largest number among three numbers";
}
else if(b>c && b>a) {
if(c>a)
cout<<c<<" is second largest number among three numbers";
else
505
cout<<a<<" is second largest number among three numbers";
}
else if(a>b)
cout<<a<<" is second largest number among three numbers";
else
cout<<b<<" is second largest number among three numbers";
return 0;
}
Question 64
Question:
Write a program to calculate the sum of the two given integer values. Return three times
the sum of the two values if they are equal.
Solution:
#include<iostream>
using namespace std;
int myfunc();
int myfunc(int a, int b) {
return a == b ? (a + b)*3 : a + b;
}
int main() {
cout<<""<<myfunc(3, 5);
cout<<"\n"<<myfunc(6, 6);
return 0;
}
506
Question 65
Question:
Write a program that accepts minutes as input, and display the total number of hours and
minutes.
Solution:
#include<iostream>
using namespace std;
int main() {
int mins, hrs;
cout<<"Input minutes: ";
cin>>mins;
hrs=mins/60;
mins=mins%60;
cout<<hrs<<" Hours,"<<mins<< " Minutes.\n";
return 0;
}
AWS stands for Amazon Web Services, which is a cloud computing platform offered by
Amazon. AWS provides a wide range of cloud-based services, including computing power,
storage, and databases, as well as machine learning, security, and analytics tools. These
services are available on-demand, allowing businesses and individuals to quickly and easily
access the resources they need without having to invest in and maintain their own physical
infrastructure. AWS is one of the leading cloud computing platforms in the world, used by
millions of customers in over 190 countries.
507
Question
508
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five.
cin>>x; testing. It can interact with web elements, simulate user actions, and
capture results, making it easier to automate web application testing.
if(x % 3 == 0 || x % 5 == 0) {
cout<<"True";
Selenium also provides a set of tools for testing web applications
}
across multiple browsers and platforms. It supports various web
else { browsers, including Google Chrome, Mozilla Firefox, and Microsoft
cout<<"False"; Edge, and can be used to test web applications on different operating
} systems, including Windows, macOS, and Linux.
return 0;
} Selenium is widely used in software development teams of all sizes
and is considered a critical tool for implementing agile and DevOps
practices. It enables developers to automate web application testing,
making it easier to ensure that web applications are tested thoroughly
and released with high quality. Overall, Selenium is a powerful and
flexible testing framework that helps developers and testers automate
web application testing and ensure the quality of their web
applications.
508
Question
509
Question:
Write a program to verify whether one of the two entered integers falls within the range
of 100 to 200 included.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
if((x >= 100 && x <= 200) || (y >= 100 && y <= 200)) {
cout<<"True";
Ansible is an open-source IT automation tool that simplifies the management and orchestration
}
of complex IT infrastructure. It allows users to automate repetitive tasks, manage configuration
else { files, and deploy applications across multiple servers and environments. Ansible is designed to
cout<<"False"; be simple and easy to use, with a YAML-based scripting language that is human-readable and
} easily understood by both developers and non-developers. It uses a push-based model, meaning
that configuration changes are pushed out to the target hosts in a controlled and predictable
return 0;
manner.
}
Ansible uses SSH (Secure Shell) protocol to connect to remote hosts, making it easy to manage
and automate servers across a network. It also supports a wide range of modules, which are pre-
built pieces of code that perform specific tasks such as installing software packages, configuring
services, and creating users. Ansible can be used for a wide range of IT automation tasks,
including configuration management, application deployment, and orchestration of infrastructure
components such as cloud services, storage systems, and networking devices. Overall, Ansible is
a powerful and flexible IT automation tool that simplifies the management and orchestration of
complex IT infrastructure, allowing organizations to streamline their operations and reduce the
time and effort required to manage their IT resources.
509
Question
510
Question:
Write a program to determine which of the two given integers is closest to the value 100.
If the two numbers are equal, return 0.
int x = abs(a - 100); by running Terraform, which compares the desired state to
the current state and makes any necessary changes to bring
int y = abs(b - 100);
the infrastructure into compliance with the desired state.
return x == y ? 0 : (x < y ? a : b);
}
Terraform supports a wide range of cloud providers and
int main() {
services, including Amazon Web Services, Microsoft Azure,
cout<<" "<< myfunc(86, 99); Google Cloud Platform, and many others. It also supports on-
cout<<"\n "<<myfunc(55, 55); premises infrastructure, allowing teams to manage
cout<<"\n "<<myfunc(65, 80); infrastructure across multiple cloud and on-premises
return 0; environments. Terraform provides a range of benefits for
510
Question
511
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five, but not both.
Solution: Nagios is an open-source monitoring system that is used for monitoring the
health and performance of IT infrastructure. It provides a range of tools and
#include<iostream>
features for monitoring servers, network devices, applications, and services,
using namespace std; and can be used to detect and diagnose problems before they affect end-
int main() { users.
int x;
cout<<"\nEnter a number: "; Nagios works by monitoring various metrics and alerts, such as CPU usage,
cin>>x; memory usage, disk space, network traffic, and application availability. It
if(x % 3 == 0 ^ x % 5 == 0) { uses a web interface to display the status of monitored objects and provides
alerts and notifications when there are issues or failures.
cout<<"True";
}
Nagios is highly customizable and extensible, allowing users to create
else {
custom plugins and add-ons to monitor a wide range of systems and
cout<<"False"; services. It also supports various third-party plugins and integrations,
} making it a versatile and flexible monitoring system.
return 0;
} Nagios is widely used in IT operations teams of all sizes and is considered a
critical tool for monitoring and maintaining IT infrastructure. It provides a
range of benefits, including increased visibility and control, improved
uptime and reliability, and reduced mean time to repair (MTTR) in the event
of failures or incidents.
511
Question
512
Question:
Write a program to determine whether two entered non-negative numbers have the same
last digit.
Gradle is an open-source build automation tool that is used for
building, testing, and deploying software projects. It provides a
flexible and powerful build system that can be used to automate
various tasks in the software development process.
Solution:
Gradle uses a build script that is written in a Groovy or Kotlin-based
#include<iostream>
domain-specific language (DSL). The build script describes the
using namespace std; dependencies and tasks required to build the software project, and
int main() { Gradle uses this information to generate the build output.
int x, y;
cout<<"\nEnter the value for x: "; Gradle supports a wide range of programming languages and
return 0;
Gradle is widely used in software development teams of all sizes and
}
is considered a critical tool for implementing modern software
development practices such as DevOps and continuous delivery. It
provides a range of benefits, including improved automation,
increased efficiency, and reduced build times.
512
Question 71
Question:
Question:
Write a program that accepts two integers and returns true when one of them equals 6, or
when their sum or difference equals 6.
513
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
if(x == 6 || y == 6 || x + y == 6 || abs(x - y) == 6) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}
Question 73
Question:
Write a program to check whether it is possible to add two integers to get the third
Solution:
514
#include<iostream>
using namespace std;
int main() {
int x, y, z;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
cout<<"\nEnter the value for z: ";
cin>>z;
if(x == y + z || y == x + z || z == x + y) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
#include<iostream>
515
using namespace std;
int main() {
float kmph;
cout<<"Enter kilometers per hour: ";
cin>>kmph;
cout<<(kmph * 0.6213712)<<" miles per hour";
return 0;
}
Question 75
Question:
Solution:
#include<iostream>
using namespace std;
#define PI 3.141592
int main() {
float major, minor;
cout<<"\nEnter length of major axis: ";
cin>>major;
cout<<"\nEnter length of minor axis: ";
cin>>minor;
cout<<"\nArea of an ellipse = "<< (PI * major * minor);
return 0;
}
516
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
first two values are equal.
Solution:
#include<iostream>
using namespace std;
int myfunc();
int myfunc(int a, int b, int c) {
#include<iostream>
if (a == b && b == c) return 0;
#include<cstring>
if (a == b) return c;
if (a == c) return b; using namespace std;
if (b == c) return a;
else return a + b + c;
void myfunc(string x= "John") {
}
int main() { cout << x;
?
cout<<"\n"<<myfunc(11, 11, 16);
cout<<"\n"<<myfunc(18, 15, 10);
int main() {
return 0;
} myfunc();
return 0;
517
Question 77
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int bytes;
cout<<"\nEnter number of bytes: ";
cin>>bytes;
cout<<"\nKilobytes: "<<(bytes/1024);
return 0;
}
Question 78
Question:
Solution:
518
#include<iostream>
using namespace std;
int main() {
double megabytes, kilobytes;
cout<<"\nInput the amount of megabytes to convert: ";
cin>>megabytes;
kilobytes = megabytes * 1024;
cout<<"\nThere are "<<kilobytes<< " kilobytes in " <<megabytes<< "
megabytes.";
return 0;
}
Question 79
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int array[1000], i, arr_size, even=0;
cout<<"Input the size of the array: ";
cin>>arr_size;
cout<<"Enter the elements in array: \n";
for(i=0; i<arr_size; i++) {
cin>>array[i];
519
}
Question 80
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int array[1000], i, arr_size, odd=0;
cout<<"Input the size of the array: ";
cin>>arr_size;
cout<<"Enter the elements in array: \n";
for(i=0; i<arr_size; i++) {
cin>>array[i];
520
}
Question 81
Question:
Write a program that will accept two integers and determine whether or not they are
equal.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"Input the values for x and y: \n";
cin>>x;
cin>>y;
if(x == y) {
cout<<"x and y are equal\n";
521
}
else {
cout<<"x and y are not equal\n";
}
return 0;
}
Question 82
Question:
Write a program to find the third angle of a triangle if two angles are given.
Solution:
#include<iostream>
using namespace std;
int main() {
int angle1, angle2;
cout<<"\nEnter the first angle of the triangle: ";
cin>>angle1;
cout<<"\nEnter the second angle of the triangle: ";
cin>>angle2;
cout<<"\nThird angle of the triangle is: "<< (180 - (angle1 + angle2));
return 0;
}
522
Question 83
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int year;
cout<<"Enter the year: ";
cin>>year;
if((year % 400) == 0) {
cout<<year<<" is a leap year.";
}
else if((year % 100) == 0) {
cout<<year<<" is a not leap year.";
}
else if((year % 4) == 0) {
cout<<year<<" is a leap year.";
}
else {
cout<<year<<" is not a leap year.";
}
return 0;
}
523
Question 84
Question:
Write a program that reads the candidate's age and determine a candidate's eligibility to
cast his own vote.
Solution:
#include <iostream>
using namespace std;
int main() {
int age;
cout<<"\nEnter the age of the candidate: ";
cin>>age;
if(age<18) {
cout<<"\nWe apologize, but the candidate is not able to cast his vote.";
cout<<"\nAfter "<< (18-age) <<" year, the candidate would be able to cast his
vote.";
}
else {
cout<<"Congratulation! the candidate is qualified to cast his vote.\n";
}
return 0;
}
524
Question 85
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float yard;
cout<<"\nEnter the Length in Yard: ";
cin>>yard;
cout<<yard<<" Yard in Foot is: "<<(3*yard);
return 0;
}
Question 86
Question:
Solution:
525
#include<iostream>
using namespace std;
int main() {
double gigabytes, megabytes;
cout<<"\nInput the amount of gigabytes to convert: ";
cin>>gigabytes;
megabytes = gigabytes*1024;
cout<<"\nThere are "<<megabytes<<" megabytes in "<<gigabytes<<" gigabytes.";
return 0;
}
Question 87
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float kg, lbs;
cout<<"\nEnter Weight in Kilogram: ";
cin>>kg;
lbs = kg*2.20462;
cout<<kg<<" Kg = "<<lbs<<" Pounds";
return 0;
526
}
Question 88
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float kg, ounce;
cout<<"\nEnter Weight in Kilogram: ";
cin>>kg;
ounce = kg*35.274;
cout<<kg<<" Kg = "<<ounce<< " Ounce";
return 0;
}
Question 89
Question:
527
Solution:
#include<iostream>
using namespace std;
int main() {
float pound, gram;
cout<<"\nEnter Weight in Pounds: ";
cin>>pound;
gram = pound*453.592;
cout<<pound<<" Pound = "<<gram<<" Grams";
return 0;
}
Question 90
Question:
Solution:
#include <iostream>
using namespace std;
int main() {
int angle1, angle2, angle3, sum;
cout<<"\nEnter the first angle of the triangle: ";
cin>>angle1;
528
cout<<"\nEnter the second angle of the triangle: ";
cin>>angle2;
cout<<"\nEnter the third angle of the triangle: ";
cin>>angle3;
sum = angle1 + angle2 + angle3;
if(sum == 180) {
cout<<"\nThe triangle is valid.";
}
else {
cout<<"\nThe triangle is not valid.";
}
return 0;
}
Question 91
Question:
Write a program to add the digits of a two-digit number that is entered by the user.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y, sum = 0;
cout<<"\nEnter a two-digit number: ";
cin>>x;
y = x;
529
while(y != 0) {
sum = sum + y % 10;
y = y / 10;
}
cout<<"\nSum of digits of "<<x<<" is: "<<sum;
return 0;
}
Question 92
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char ch;
cout<<"\nEnter a character: ";
cin>>ch;
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
cout<<ch<<" is a vowel";
}
else {
530
cout<<ch<<" is a consonant";
}
return 0;
}
Question 93
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, fact=1, num;
cout<<"\nEnter a number: ";
cin>>num;
for(i=1; i<=num; i++) {
fact=fact*i;
}
cout<<"\nFactorial of "<<num<<" is: "<<fact;
return 0;
}
531
Question 94
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x[12]={31,28,31,30,31,30,31,31,30,31,30,31}, m;
cout<<"\nEnter the month number: ";
cin>>m;
if(m>12 || m<1) {
cout<<"Invalid input";
}
else if(m==2) {
cout<<"\nNumber of days in month 2 is either 29 or 28";
}
else {
cout<<"\nNumber of days in month "<<m<< " is: "<<x[m-1];
}
return 0;
}
532
Question 95
Question:
Solution:
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char a[1000], b[1000];
cout<<"\nEnter the first string: ";
cin>>a;
cout<<"\nEnter the second string: ";
cin>>b;
strcat(a, b);
cout<<"\nString produced by concatenation is: "<< a;
return 0;
}
Question 96
Question:
533
Solution:
Type theory is a branch of mathematical logic and
#include<iostream> computer science that studies the behavior of types,
which are categories of data that share certain
using namespace std; properties or operations. The goal of type theory is to
int main() { formalize the structure and behavior of types, and to
use this formalism to reason about programs, systems,
int a,b; and mathematical objects.
cout<<"Enter two numbers: \n";
In type theory, types are used to classify data and to
cin>>a; ensure that operations are applied to the right kind of
cin>>b; data. For example, in a programming language that
supports type checking, a function that is defined to
if(a>b) {
accept integers will not accept strings, because they are
cout<<a<<" is a maximum number"; of a different type. This type checking ensures that the
function is applied only to the appropriate types of
}
data, which can help prevent errors and improve
else { program correctness.
cout<<b<<" is a maximum number";
Type theory has many applications in computer
} science, including programming language design,
return 0; software verification, and formal methods. It is also
used in the study of mathematics, where it provides a
} way to reason about the behavior of mathematical
objects and to prove theorems using formal logic.
Question 97
Question:
Solution:
#include<iostream>
534
#include<cstring>
using namespace std; Numerical analysis is a branch of mathematics that
deals with the development and implementation of
int main() { algorithms for solving mathematical problems using
char a[100], b[100]; numerical methods. It involves the study of numerical
algorithms, their implementation, and their analysis in
cout<<"Enter the first string: \n"; terms of accuracy, stability, and efficiency.
cin>>a;
Numerical analysis is used in many fields, including
cout<<"Enter the second string: \n"; engineering, science, finance, and computer science. It
cin>>b; is used to solve problems that cannot be solved
analytically or with closed-form solutions, such as
if (strcmp(a,b) == 0) {
differential equations, optimization problems, and
cout<<"The 2 strings are equal.\n"; systems of linear equations. Numerical analysis also
plays an important role in scientific computing, where
}
it is used to simulate and model complex systems.
else {
Some of the most common techniques used in
cout<<"The 2 strings are not equal.\n";
numerical analysis include numerical integration,
} numerical differentiation, root-finding algorithms,
return 0; linear and nonlinear systems of equations, and
optimization algorithms. These techniques rely on a
} combination of mathematical theory, computational
algorithms, and numerical experimentation to develop
and refine numerical methods for solving complex
problems.
Write a program to convert the upper case letter to lower case letter.
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'G';
535
char b = tolower(ch);
cout<<ch<<" in lowercase is represented as "<< b;
return 0;
}
Question 99
Question:
Write a program to find the quotient and remainder of an entered dividend and divisor.
536
Question 100
Question:
Write a program to determine the Size of int, float, double and char.
Solution:
#include<iostream>
using namespace std;
int main() {
cout<<"Size of char is: "<<sizeof(char)<<" byte\n";
cout<<"Size of int is: "<<sizeof(int)<<" bytes\n";
cout<<"Size of float is: "<<sizeof(float)<<" bytes\n";
cout<<"Size of double is: "<<sizeof(double)<<" bytes\n";
return 0;
}
Question 101
Question:
Solution:
#include<iostream>
537
using namespace std;
int main() {
int pwd, i;
while (i!=0) {
cout<<"\nEnter the password: ";
cin>>pwd;
if(pwd==1988) {
cout<<"The password you entered is correct";
i=0;
}
else {
cout<<"Incorrect password, try again";
}
cout<<"\n";
}
return 0;
}
Question 102
Question:
Solution:
#include<iostream>
using namespace std;
538
int main() {
int num;
cout<<"Input a positive or negative number: \n";
cin>>num;
cout<<"\nAbsolute value of "<<"|"<<num<<"|"<<" is: "<<abs(num);
return 0;
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
#include<iostream>
using namespace std;
int main() {
float ht;
cout<<"\nEnter the height (in cm): ";
cin>>ht;
if(ht < 150.0) {
cout<<"Dwarf.\n";
}
else if((ht >= 150.0) && (ht < 165.0)) {
cout<<"Average Height.\n";
539
}
else if((ht >= 165.0) && (ht <= 195.0)) {
cout<<"Taller.\n";
}
else {
cout<<"Abnormal height.\n";
}
return 0;
}
Question 104
Question:
Write a program to calculate the area of different geometric shapes using switch
statements.
Solution:
#include<iostream>
using namespace std;
int main() {
int choice;
float r, l, w, b, h;
cout<<"\nEnter 1 for area of circle: ";
cout<<"\nEnter 2 for area of rectangle: ";
cout<<"\nEnter 3 for area of triangle: ";
cout<<"\nEnter your choice : ";
cin>>choice;
540
switch(choice) {
case 1:
cout<<"Enter the radius of the circle: ";
cin>>r;
cout<<"\nArea of a circle is: " << (3.14*r*r);
break;
case 2:
cout<<"Enter the length and width of the rectangle: \n";
cin>>l;
cin>>w;
cout<<"\nArea of a rectangle is: "<<(l*w);
break;
case 3:
cout<<"Enter the base and height of the triangle: \n";
cin>>b;
cin>>h;
cout<<"\nArea of a triangle is: "<<(0.5*b*h);
break;
default:
cout<<"\nPlease enter a number from 1 to 3.";
break;
Bitbucket is a web-based version control repository hosting service that is used to store and manage code
}
repositories. It is developed by Atlassian and provides Git and Mercurial-based distributed version control systems
return 0;
(DVCS) for source code management. With Bitbucket, teams can collaborate on software projects, manage code
} repositories, track changes, and perform code reviews. It offers a range of features, such as pull requests, code
branching, and commit history tracking, which allow developers to work together efficiently and effectively.
Bitbucket is integrated with other Atlassian products, such as Jira and Confluence, making it easy to manage issues
and track progress across the entire software development process. It also provides tools for continuous integration
and deployment (CI/CD), allowing teams to automate their build and deployment pipelines. Bitbucket is available
in both cloud-based and self-hosted versions. The cloud-based version offers a range of pricing plans, depending on
the number of users and repositories required. The self-hosted version can be installed on-premise or on a cloud-
based infrastructure, giving organizations greater control over their source code management. Overall, Bitbucket is
a powerful and flexible source code management tool that allows teams to collaborate on software development
projects, manage code repositories, and automate their build and deployment pipelines. It is a popular choice for
teams of all sizes and offers a range of features to support the entire software development process.
541
Question 105
Question:
Write a program to accept a character from the keyboard and print "Yes" if it is equal to y.
Otherwise print "No".
Question:
Write a program that uses bitwise operators to multiply an entered value by four.
542
Puppet is a configuration management tool that is widely used in the DevOps culture
Solution: to automate the management of IT infrastructure. DevOps is a software development
approach that emphasizes collaboration and communication between development
#include<iostream> and operations teams to streamline the software delivery process. In the context of
using namespace std; DevOps, Puppet allows teams to automate the management of infrastructure and
int main() { applications, ensuring that all systems are configured and deployed consistently and
reliably. It provides a centralized platform for managing configurations, deployments,
long x, y;
and updates across multiple environments, reducing the time and effort required to
cout<<"Enter a integer: "; manage complex IT infrastructure.
cin>>x;
Puppet works by defining infrastructure as code, which means that configurations
y = x;
and deployments are defined using code that can be version-controlled, tested, and
x = x << 2; audited. This approach helps to eliminate configuration drift and reduces the risk of
cout<< y<<" x 4 = "<< x; errors or inconsistencies in the infrastructure. Using Puppet as part of a DevOps
Question 107 collaboration and communication between development and operations teams,
enabling organizations to deliver software more quickly and efficiently.
Question:
Write a program to check whether a number entered by the user is power of 2 or not.
Solution:
#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter a number: ";
543
Chef is a configuration management tool that is widely used in the DevOps
cin>>x; culture to automate the management of IT infrastructure. DevOps is a
if((x != 0) && ((x &(x - 1)) == 0)) { software development approach that emphasizes collaboration and
communication between development and operations teams to streamline the
cout<<x<<" is a power of 2";
software delivery process. In the context of DevOps, Chef allows teams to
} automate the management of infrastructure and applications, ensuring that all
else { systems are configured and deployed consistently and reliably. It provides a
cout<<x<<" is not a power of 2"; centralized platform for managing configurations, deployments, and updates
across multiple environments, reducing the time and effort required to
}
manage complex IT infrastructure. Chef works by defining infrastructure as
return 0; code, which means that configurations and deployments are defined using
} code that can be version-controlled, tested, and audited. This approach helps
to eliminate configuration drift and reduces the risk of errors or
inconsistencies in the infrastructure. Using Chef as part of a DevOps
approach helps to promote collaboration and communication between
development and operations teams, enabling faster and more frequent
software releases. It also allows organizations to scale their infrastructure
more easily and respond quickly to changing business needs. Chef is highly
Question 108 extensible and can be used to manage a wide range of systems, including
servers, cloud infrastructure, and containers. It also integrates with a range of
other tools and technologies, such as Jenkins, Git, and Docker, allowing
Question: teams to build end-to-end software delivery pipelines.
Solution:
#include<iostream>
using namespace std;
int main() {
int side1, side2, side3;
cout<<"\nEnter the first side of the triangle: ";
cin>>side1;
cout<<"\nEnter the second side of the triangle: ";
cin>>side2;
cout<<"\nEnter the third side of the triangle: ";
544
cin>>side3;
if(side1 == side2 && side2 == side3) {
cout<<"\nThe given Triangle is equilateral.";
}
else if(side1 == side2 || side2 == side3 || side3 == side1) {
cout<<"\nThe given Triangle is isosceles.";
}
else {
cout<<"\nThe given Triangle is scalene.";
}
return 0;
}
Question 109
Question:
Write a program to print ASCII values of all the letters of the English alphabet from A to Z.
Solution:
#include<iostream>
using namespace std;
int main() {
int i;
for(i='A'; i<='Z'; i++) {
cout<<"ASCII value of "<<char(i)<<"="<<int(i)<<endl;
545
}
return 0;
}
Question 110
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, num, sum=0;
cout<<"Enter a number: ";
cin>>num;
for(i=2; i<=num; i=i+2) {
sum = sum + i;
}
cout<<"\nSum of all even number between 1 to " <<num<< " is: "<< sum;
return 0;
}
546
Question 111
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, num, sum=0;
cout<<"Enter a number: ";
cin>>num;
for(i=1; i<=num; i=i+2) {
sum = sum + i;
}
cout<<"\nSum of all odd number between 1 to " <<num<< " is: "<< sum;
return 0;
}
Question 112
Question:
547
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"Enter any two numbers: \n";
cin>>x;
cin>>y;
switch(x > y) {
case 0: cout<<y<<" is Maximum number";
break;
case 1: cout<<x<<" is Maximum number";
break;
}
return 0;
}
Question 113
Question:
Write a program that allows you to enter the cost price and the selling price of a product
Solution:
#include<iostream>
548
using namespace std; Apache NetBeans is a free and open-source integrated development
int main() { environment (IDE) used primarily for developing software
else if(cp > sp) { of frameworks and technologies, such as Spring, Hibernate, and
Maven. It also provides integrations with other tools, such as Git,
cout<<"Loss = "<< (cp - sp);
Subversion, and JUnit, allowing developers to streamline their
}
development workflows. NetBeans offers a highly customizable
else {
user interface and supports a range of plugins and extensions,
cout<<"No Profit No Loss."; making it possible to tailor the IDE to suit the specific needs of the
} developer. To sum up, Apache NetBeans is a powerful and feature-
return 0; rich IDE that offers a range of tools and technologies to support
} software development in the Java programming language and other
languages. It is highly customizable and provides integrations with a
range of tools and technologies, making it a popular choice among
developers.
Question 114
Question:
Write a program that display the pattern like a right angle triangle using an asterisk.
Solution:
#include<iostream>
549
using namespace std;
Red Hat is a software company that provides open source
int main() {
solutions to enterprises. The company was founded in 1993
int rows; and is headquartered in Raleigh, North Carolina, USA. Red
cout<<"Input the number of rows: "; Hat is best known for its distribution of the Linux operating
cout<<"\n"; flexible, scalable, and secure, and they are often used by
businesses to improve efficiency, reduce costs, and increase
}
agility. Red Hat is also known for its commitment to open
return 0; source software, which means that its products are based on
} freely available code that can be modified and distributed by
anyone. This approach has helped to create a vibrant
community of developers and users who collaborate to
improve the quality and functionality of the software.
Question 115
Question:
Write a program that display the pattern like a right angle triangle using a number.
Solution:
#include<iostream>
using namespace std;
int main() {
int rows;
cout<<"Input the number of rows: ";
cin>>rows;
for(int x=1; x<=rows; x++) {
for(int y=1; y<=x; y++)
550
cout<<""<<y;
cout<<"\n";
}
return 0;
}
Question 116
Question:
Write a program to determine the number and sum of all integers between 50 and 100
which are divisible by 2.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, sum=0;
cout<<"Numbers between 50 and 100, divisible by 2: \n";
for(x=51; x<100; x++) {
if(x%2==0) {
cout<<" "<<x;
sum+=x;
}
}
cout<<"\nThe sum: "<< sum;
return 0;
551
}
Question 117
Question:
Write a program that uses the function to determine whether a entered number is even or
odd.
Solution:
#include<iostream>
using namespace std;
int myfunc(int x) {
return (x & 1);
}
int main() {
int x;
cout<<"Enter any number: ";
cin>>x;
if(myfunc(x)) {
cout<<"\nThe number you entered is odd.";
}
else {
cout<<"\nThe number you entered is even.";
}
return 0;
}
552
Question 118
Question:
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x;
cout<<"Enter any number: ";
cin>>x;
cout<<"Square root of "<<x<< " is: "<<(double)sqrt(x);
return 0;
}
Question 119
Question:
553
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
cout<<x<<"^"<<y<<" = " << (long)pow(x,y);
return 0;
}
Question 120
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char ch;
cout<<"Enter a character: ";
554
cin>>ch;
if(isdigit(ch)) {
cout<<ch<<" is a Digit";
}
else if(isalpha(ch)) {
cout<<ch<<" is an Alphabet";
}
else {
cout<<ch<<" is not an Alphabet, or a Digit";
}
return 0;
}
Question 121
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char a;
cout<<"Enter a character: ";
cin>>a;
555
if(isalnum(a)) {
cout<<a<<" is an alphanumeric character.";
}
else {
cout<<a<<" is NOT an alphanumeric character.";
}
return 0;
}
Question 122
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char a;
cout<<"Enter a character: ";
cin>>a;
if(ispunct(a)) {
cout<<a<<" is an punctuation character.";
}
else {
556
cout<<a<<" is NOT an punctuation character.";
}
return 0;
}
Question 123
Question:
Write a program to check whether the entered character is a graphic character or not.
Solution:
#include<iostream>
using namespace std;
int main() {
char a;
cout<<"Enter a character: ";
cin>>a;
if(isgraph(a)) {
cout<<a<<" is a graphic character.";
}
else {
cout<<a<<" is NOT a graphic character.";
}
return 0;
}
557
Question 124
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i;
for(i = 1; i <= 127; i++)
if(isprint(i)!= 0)
cout<<" "<<char(i);
return 0;
}
Question 125
Question:
Write a program to check whether the entered character is a hexadecimal digit character
or not.
Solution:
558
#include<iostream>
using namespace std;
int main() {
char a;
cout<<"Enter a character: ";
cin>>a;
if(isxdigit(a)) {
cout<<a<<" is a hexadecimal digit character.";
}
else {
cout<<a<<" is NOT a hexadecimal digit character.";
}
return 0;
}
Question 126
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i;
cout<<"The ASCII value of all control characters are: \n";
559
for(i=0; i<=127; i++) {
if(iscntrl(i)!=0) #include<iostream>
cout<<"\n "<< i;
#include<cstring>
}
using namespace std;
return 0;
} int main() {
?
string x = "Joe";
}
Question:
Write a program to check whether the given character is a white-space character or not.
Solution:
#include <iostream>
using namespace std;
int main() {
char c;
char ch = ' ';
if(isspace(ch)) {
cout << "\nNot a white-space character.";
}
else {
cout << "\nWhite-space character.";
}
return 0;
560
}
Question 128
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
if(isprint(ch)) {
cout<<ch<<" is printable character."<<endl;
}
else {
cout<<ch<<" is not printable character."<<endl;
}
if(iscntrl(ch)) {
cout<<ch<<" is control character."<<endl;
}
else {
cout<<ch<<" is not control character."<<endl;
}
return (0);
561
}
Question 129
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int side;
long area;
cout<<"\nEnter the side of cube: ";
cin>>side;
area = 6*side*side;
cout<<"\nThe surface area of cube is: "<< area;
return 0;
}
Question 130
Question:
562
Solution:
#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x+(~y)+1;
return 0;
}
Question 131
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x-(~y)-1;
return 0;
}
563
Question 132
Question:
#include<iostream>
Solution:
#include<cstring>
#include<iostream>
using namespace std; using namespace std;
int main() {
int main() {
int x=2;
cout<< (x<<1); string x[5] = {"Albert", "John", "Mary", "James"};
return 0;
x[0] = "Joe";
}
cout << x[0]; // Output: Joe
return 0;
Question 134 }
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
564
int x=12;
cout<< (x>>1);
return 0;
}
Question 135
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int radius;
float PI = 3.141592;
cout<<"\nEnter the radius of sphere: ";
cin>>radius;
float volume = (4/3)*(PI*radius*radius*radius);
cout<<"\nThe volume of sphere is: "<< volume;
return 0;
}
565
Question 136
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int r1, r2, r3;
float PI = 3.141592;
cout<<"\nEnter the radius of the ellipsoid of axis 1: ";
cin>>r1;
cout<<"\nEnter the radius of the ellipsoid of axis 2: ";
cin>>r2;
cout<<"\nEnter the radius of the ellipsoid of axis 3: ";
cin>>r3;
float volume = (4/3)*(PI*r1*r2*r3);
?
cout<<"\nThe volume of ellipsoid is: "<< volume;
return 0;
} #include<iostream>
#include<cstring>
int main() {
return 0;
566
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
#include<iostream>
long power = 1;
cout<<"\nEnter the value for x: "; #include<cstring>
cin>>x; using namespace std;
cout<<"\nEnter the value for y: ";
cin>>y;
for(int i=1; i<=y; i++) { int main() {
// Output: Albert
return 0;
567
Question 138
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int a,b,c;
float avg;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
cin>>b;
cout<<"\nEnter the third number: ";
cin>>c;
avg=(a+b+c)/3.0;
cout<<"\nAverage of three numbers is: "<< avg;
return 0;
}
Question 139
Question:
Write a program to read integer "n" and print first three powers (n 1, n2, n3).
568
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int n;
cout<<"\nEnter a number: ";
cin>>n;
cout<<pow(n, 1)<<" "<< pow(n, 2)<<" "<< pow(n, 3);
return 0;
}
#include<iostream>
#include<cstring>
int main() {
using namespace std;
string i[2][4] = {
?
return 0;
cout << i[0][2];
}
// Output: B
return 0;
569
#include<iostream>
int main() {
string y="programming";
x.append(y);
cout<<" \n "<<x<<'\n';
return 0;
#include<iostream>
return 0; *x.begin()='J';
// Output: A cout<<x;
} return 0;
// Output: J language
570
#include<iostream>
int main() {
x.erase(8,1);
cout<<x;
return 0;
#include<iostream>
#include<cstring>
int main() {
cout << "The length of the text string is: " << txt.size();
return 0;
571
#include<iostream>
#include<cstring>
int main() {
cout << "The length of the text string is: " << txt.length();
return 0;
Information visualization refers to the visual representation of data
or information to facilitate the understanding of complex concepts,
}
patterns, and relationships. It involves using visual elements such as
charts, graphs, maps, and other visual representations to convey
information and insights.
#include<iostream>
The main goal of information visualization is to make data and
using namespace std; information more accessible, understandable, and usable for a wide
range of users. By presenting information in a visually compelling
int main() { and interactive way, information visualization can help users to
identify trends, patterns, and insights that may not be apparent in
traditional data formats.
string x="c++ programming";
Information visualization is used in a wide range of applications,
x.erase(x.begin()+0); including business intelligence, scientific research, healthcare,
education, and more. It plays an important role in helping individuals
cout<<x; and organizations make informed decisions based on data-driven
insights. With the increasing availability of big data and
// Output: ++ programming advancements in data visualization tools and techniques, information
visualization is becoming an increasingly important field for data
return 0; scientists, designers, and other professionals who work with data.
572
C++ Program:
#include<bits/stdc++.h>
using namespace std;
int main()
{ Output:
float a =2.33333;
2
cout << floor(a) << endl;
cout << ceil(a) << endl;
3
cout << trunc(a) << endl;
cout << round(a) << endl; 2
cout << setprecision(2) << a;
return 0; 2
}
2.3
C++ Program:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
Output:
{
float a = -43; 43
cout << abs(a) << endl;
cout << labs(a) << endl; 43
cout << llabs(a) << endl;
43
return 0;
}
573
JDK JRE JVM
It is the tool necessary to compile, It provides the class libraries and A virtual machine that enables a
document and package Java other resources that a specific Java computer to run Java programs
Inheritance Abstraction
acquires the properties of another implementation details from the user and
only providing the functionality to the
users.
Encapsulation
Polymorphism
574
Java Exercises
Java is the mainstream technology for creating and delivering embedded and mobile software,
games, Internet entertainment, and business software. It serves as the foundation for almost any
sort of networked application. With over 9 million developers across the globe, Java makes it
simple to quickly create, distribute, and use new apps and services. Around 1992, James
Gosling was employed by Sun Labs. A set-top box was being built by Gosling and his team,
who began by "cleaning up" C++ and ultimately came up with a new language and runtime. As a
result, Java or Oak was created. C continues to be the top option among developers when it
comes to programming languages. However, Java is more popular among developers than C. The
second most popular programming language is Java. The common reason for this is because it
facilitates the creation of sophisticated applications that operate well and satisfactorily. In
addition, Java may be installed and operated on any platform. Approximately 3 billion mobile
phones, 125 million TV sets, and every Blu-Ray player currently use Java. You can learn Java
programming and advance your skills by practicing and working through problems. If you learn
best "by example," this is the chapter for you.
575
Question 1
Question:
Solution:
Question 2
Question:
Solution:
576
int perimeter = 2 * (height + width);
System.out.println("Perimeter of the rectangle is: " + perimeter + " cm");
int area = height * width;
System.out.println("Area of the rectangle is: " + area + " square cm");
}
}
Question 3
Question:
Solution:
int x = 65;
x = 80;
System.out.println(x); // Output: 80
577
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
Solution:
import java.util.Scanner;
String x = "Einstein";
}
// Output: Albert Einstein
}
578
Question 5
Question:
Write a program that accepts two numbers from the user and calculate the product of the
two numbers.
Solution:
import java.util.Scanner;
Question 6
Question:
Write a program that accepts three numbers and find the largest of three.
579
Solution:
import java.util.Scanner;
580
Question 7
Question:
Write a program that reads three floating values and check if it is possible to make a
triangle with them. Also calculate the perimeter of the triangle if the entered values are
valid.
Solution:
import java.util.Scanner;
581
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 8
Question:
Write a program that reads an integer between 1 and 7 and print the day of the week in
English.
Solution:
import java.util.Scanner;
582
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.print("Enter a number between 1 to 7.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 9
Question:
583
Solution:
Question 10
Question:
Solution:
584
Question 11
Question:
Solution:
Question 12
Question:
585
Solution:
Question 13
Question:
Write a program that prints all even numbers between 1 and 25.
Solution:
586
if(i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
Question 14
Question:
Write a program that prints all odd numbers between 1 and 50.
Solution:
System.out.println(x);
}
// Output: 100
}
587
Question 15
Question:
Write a program to print the first 10 numbers starting from one together with their
squares and cubes.
Solution:
Question 16
Question:
Write a program:
If you enter a character M
588
Solution:
Question 17
Question:
Write a program to print the multiplication table of a number entered by the user.
Solution:
import java.util.Scanner;
589
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 18
Question:
Solution:
Question 19
Question:
590
Solution:
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
import java.util.Scanner;
591
System.out.print("\nEnter the first number: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
y = STDIN_SCANNER.nextInt();
if(x - y == 0) {
System.out.print("\nThe two numbers are equivalent");
} else {
System.out.print("\nThe two numbers are not equivalent");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
Solution:
import java.util.Scanner;
592
b = STDIN_SCANNER.nextInt();
c = a % b;
System.out.print("\n The remainder of " + a + " and " + b + " is: " + c);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 22
Question:
Solution:
boolean x = true;
boolean y = false;
593
Question 23
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
String a;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Name : ");
a = scan.nextLine();
System.out.println("The length of the String is: " + a.length());
}
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
Solution:
594
public class MyClass {
public static void main(String[] args) {
char ch = 'a';
if(Character.isLowerCase(ch)) {
System.out.println("The given character is a lower case letter");
}
else {
System.out.println("The given character is a upper case letter");
}
}
}
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
Solution:
595
}
}
Question 26
Question:
Write a program to convert the lower case string to upper case string.
Solution:
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches.
596
Solution:
import java.util.Scanner;
Question 28
Question:
Einstein [0] = E
Einstein [1] = I
Einstein [2] = N
Einstein [3] = S
Einstein [4] = T
Einstein [5] = E
Einstein [6] = I
Einstein [7] = N
597
Solution:
?
public class MyClass { myMethod("Albert");
public static void main(String[] args) {
myMethod("Elsa");
for(int i = 1; i <= 10; i++) {
System.out.println("Hello World "); }
}
}
}
}
598
Question 30
Question:
Solution:
Question 31
Question:
Solution:
599
import java.util.Scanner;
Question 32
Question:
Solution:
import java.util.Scanner;
600
a = STDIN_SCANNER.nextInt();
if(a % 2 == 0) {
System.out.print("The entered number is even");
} else {
System.out.print("The entered number is odd");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 33
Question:
Solution:
601
Question 34
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder will be 2.
Solution:
import java.util.Scanner;
602
Question 35
Question:
Solution:
import java.util.Scanner;
603
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
not possible" if that is not possible.
Solution:
import java.util.Scanner;
604
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution:
import java.util.Scanner;
double y = 9.78d;
int x = (int) y;
System.out.println(x); // Output: 9
605
Question 38
Question:
Write a program that adds up all numbers between 1 and 100 that are not divisible by 12.
Solution:
Question 39
Question:
Solution:
606
public class MyClass {
public static void main(String[] args) {
float x = 0;
for(int i = 1; i <= 50; i++) {
x += (float)1 / i;
}
System.out.printf("Value of x: %.2f\n", x);
}
}
Question 40
Question:
Write a program that reads a number and find all its divisor.
Solution:
import java.util.Scanner;
607
}
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 41
Question:
Write a program to find the incremented and decremented values of two numbers.
Solution:
608
Question 42
Question:
Solution:
import java.util.Scanner;
609
Question 43
Question:
Write a program that accepts principal amount, rate of interest, time and compute the
simple interest.
Solution:
import java.util.Scanner;
610
Question 44
Question:
Write a program that swaps two numbers without using third variable.
Solution:
import java.util.Scanner;
611
Question 45
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of a side of the hexagon: ");
double s = input.nextDouble();
double area = (6*(s*s))/(4*Math.tan(Math.PI/6));
System.out.print("The area of the hexagon is: " + area);
}
}
Question 46
Question:
612
body [d] = d
body [y] = y
Solution:
Question 47
Question:
Write a program to calculate the discounted price and the total price after discount
Given:
If purchase value is greater than 1000, 10% discount
Solution:
613
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
double pv;
System.out.print("Enter purchased value: ");
pv = STDIN_SCANNER.nextDouble();
if(pv > 1000) {
System.out.printf("\n Discount = %f", pv * 0.1);
System.out.printf("\n Total = %f", pv - pv * 0.1);
} else if(pv > 5000) {
System.out.printf("\n Discount = %f", pv * 0.2);
System.out.printf("\n Total = %f", pv - pv * 0.2);
} else {
System.out.printf("\n Discount = %f", pv * 0.3);
System.out.printf("\n Total = %f", pv - pv * 0.3);
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 48
Question:
Write a program to print the first ten natural numbers using while loop statement.
Solution:
614
public static void main(String[] args) { import java.util.ArrayList;
?
x.add("Mary");
System.out.println(x);
Question 49
}
}
Question:
Solution:
import java.util.Scanner;
615
Question 50
Question:
Solution:
import java.util.Scanner;
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
616
Solution:
import java.util.Scanner;
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
Solution:
617
import java.util.Scanner;
Question 53
Question:
Solution:
618
System.out.format("\nCurrent Date time: %tc%n\n",
System.currentTimeMillis());
}
}
Question 54
Question:
Solution:
int y = 9;
double x = y;
619
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
is 50 or if their sum is 50.
Solution:
import java.util.Scanner;
620
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
import java.util.Scanner;
621
System.out.print("\nNumber of odd values: " + odd);
System.out.print("\nNumber of positive values: " + positive);
System.out.print("\nNumber of negative values: " + negative);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 57
Question:
import java.util.ArrayList;
Solution:
public class MyClass {
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
622
}
Question 58
Question:
Write a program that reads a student's three subject scores (0-100) and computes the
Solution:
import java.util.Scanner;
623
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 59
Question:
x.add("Joe");
x.add("Alan");
Solution:
x.add("Mary");
1 x.clear();
2
System.out.println(x);
// Output: []
624
public class MyClass {
public static void main(String[] args) {
System.out.println(-7 + 9 * 5);
System.out.println((68+7) % 8);
System.out.println(50 + -6*5 / 5);
System.out.println(6 + 25 / 3 * 6 - 8 % 2);
}
}
Solution:
38
3
44
54
Solution:
625
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever. .........
Solution:
2.010597302504817
626
Solution:
linux
} System.out.println("Access denied");
} else {
System.out.println("Access granted");
Solution:
}
1 }
2
public static void main(String[] args) {
4
myfunc(25); // Call the myfunc method and pass along an age of 25
5
}
?
}
627
}
}
Solution:
10
x.add("Albert");
x.add("Joe");
Solution: x.add("Alan");
x.add("Mary");
15
for(int i = 0; i < x.size(); i++) {
System.out.println(x.get(i));
?
}
628
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
System.out.print((i & 1) != 0 ? "odd\n" : "even\n");
}
System.exit(0);
}
}
Solution:
odd
even
odd
Solution:
629
|-2.50| = 2.50
} import java.util.Iterator;
}
x.add("John");
15
x.add("James");
x.add("Mary");
Solution:
630
15
Solution:
15
631
Solution:
Anyone who has never made a mistake has never tried anything new.
Anyone who has never made a mistake has never tried anything new.
Anyone who has never made a mistake has never tried anything new.
Question 60
Question:
Solution:
632
Question 61
Question:
Write a program that prints a sequence from 1 to a given integer, inserts a plus sign
between these numbers, and then removes the plus sign at the end of the sequence.
Solution:
import java.util.Scanner;
633
Question 62
Question:
Write a program to verify whether a triangle's three sides form a right angled triangle or
not.
Solution:
import java.util.Scanner;
634
Question 63
Question:
Write a program that will find the second-largest number among the user's input of three
numbers.
Solution:
import java.util.Scanner;
635
System.out.print("\n" + c + " is second largest number among three
numbers");
} else {
System.out.print("\n" + a + " is second largest number among
three numbers");
}
} else if(a > b) {
System.out.print("\n" + a + " is second largest number among three
numbers");
} else {
System.out.print("\n" + b + " is second largest number among three
numbers");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 64
Question:
Write a program to calculate the sum of the two given integer values. Return three times
the sum of the two values if they are equal.
Solution:
636
System.out.print("\n" + myfunc(6, 6));
}
public static int myfunc(int a, int b) {
return a == b ? (a + b) * 3 : a + b;
}
}
Question 65
Question:
Write a program that accepts minutes as input, and display the total number of hours and
minutes.
Solution:
import java.util.Scanner;
637
Question 66
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five.
Solution:
import java.util.Scanner;
638
Question 67
Question:
Write a program to verify whether one of the two entered integers falls within the range
of 100 to 200 included.
Solution:
import java.util.Scanner;
639
Question 68
Question:
Write a program to determine which of the two given integers is closest to the value 100.
If the two numbers are equal, return 0.
Solution:
int a = 15;
int b = 13;
System.out.println(a == b);
640
Question 69
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five, but not both.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
int x;
System.out.print("\nEnter a number: ");
x = STDIN_SCANNER.nextInt();
if(x % 3 == 0 ^ x % 5 == 0) {
System.out.print("True");
} else {
System.out.print("False");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
public class MyClass {
int x = 15;
641
Question 70
Question:
Write a program to determine whether two entered non-negative numbers have the same
last digit.
Solution:
import java.util.Scanner;
642
Question 71
Question:
import java.util.ArrayList;
?
System.out.print("False"); for(int i : x) {
}
System.out.println(i);
}
} }
Question 72
Question:
Write a program that accepts two integers and returns true when one of them equals 6, or
when their sum or difference equals 6.
643
Solution:
import java.util.Scanner;
Question 73
Question:
Write a program to check whether it is possible to add two integers to get the third
integer from three entered integers.
Solution:
644
import java.util.Scanner;
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
645
import java.util.Scanner;
Question 75
Question:
Solution:
import java.util.Scanner;
646
minor = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of an ellipse = %.4f", PI * major * minor);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
first two values are equal.
Solution:
647
import java.util.ArrayList;
if(a == c) {
public class MyClass {
return b;
public static void main(String[] args) {
}
if(b == c) { ArrayList<String> x = new ArrayList<String>();
return a; x.add("Apple");
} else {
x.add("Lemon");
return a + b + c;
x.add("Kiwi");
}
x.add("Orange");
}
?
} for(String i : x) {
System.out.println(i);
}
Question 77
}
Question:
Solution:
import java.util.Scanner;
648
}
Question 78
Question:
Solution:
import java.util.Scanner;
649
Question 79
Question:
Solution:
import java.util.Scanner;
650
Question 80
Question:
Solution:
import java.util.Scanner;
651
}
Question 81
Question:
Write a program that will accept two integers and determine whether or not they are
equal.
Solution:
import java.util.Scanner;
652
Question 82
Question:
Write a program to find the third angle of a triangle if two angles are given.
Solution:
import java.util.Scanner;
Question 83
Question:
653
Solution:
import java.util.Scanner;
Question 84
Question:
Write a program that reads the candidate's age and determine a candidate's eligibility to
cast his own vote.
654
Solution:
import java.util.Scanner;
Question 85
Question:
655
Solution:
import java.util.Scanner;
Question 86
Question:
Solution:
import java.util.Scanner;
656
megabytes = gigabytes * 1_024;
System.out.printf("\nThere are %f megabytes in %f gigabytes.", megabytes,
gigabytes);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 87
Question:
Solution:
import java.util.Scanner;
657
Question 88
Question:
Solution:
import java.util.Scanner;
Question 89
Question:
658
Solution:
import java.util.Scanner;
Question 90
Question:
Solution:
import java.util.Scanner;
659
int angle1, angle2, angle3, sum;
System.out.print("\nEnter the first angle of the triangle: ");
angle1 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second angle of the triangle: ");
angle2 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third angle of the triangle: ");
angle3 = STDIN_SCANNER.nextInt();
sum = angle1 + angle2 + angle3;
if(sum == 180) {
System.out.print("\nThe triangle is valid.");
} else {
System.out.print("\nThe triangle is not valid.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 91
Question:
Write a program to add the digits of a two-digit number that is entered by the user.
Solution:
import java.util.Scanner;
660
int x, y, sum = 0;
System.out.print("\nEnter a two-digit number: ");
x = STDIN_SCANNER.nextInt();
y = x;
while(y != 0) {
sum = sum + y % 10;
y = y / 10;
}
System.out.print("\nSum of digits of " + x + " is: " + sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 92
Question:
Solution:
import java.util.Scanner;
661
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
System.out.println(ch + " is vowel");
}
else {
System.out.println(ch + " is consonant"); import java.util.ArrayList;
}
public class MyClass {
}
} public static void main(String[] args) {
x.add("Apple");
x.add("Lemon");
x.add("Kiwi");
Question 93
x.add("Mango");
System.out.println(x.size());
Question:
// Output: 4
Write a program to find factorial of a number.
}
Solution:
import java.util.Scanner;
662
}
System.out.print("\nFactorial of " + num + " is: " + fact);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 94
Question:
Solution:
import java.util.Scanner;
663
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 95
Question:
Solution:
// Output: 5
Question 96 }
}
Question:
664
Solution:
import java.util.Scanner;
665
Question 97
Question:
Solution:
666
}
else {
System.out.println("The 2 strings are not equal.");
}
}
}
Question 98
Question:
Write a program to convert the upper case string to lower case string.
Solution:
String a = "20";
int b = 30;
String c = a + b;
667
Question 99
Question:
Write a program to find the quotient and remainder of a entered dividend and divisor.
Solution:
import java.util.Scanner;
Question 100
Question:
Write a program to determine the Size of int, float, double and char.
668
Solution:
Question 101
Question:
Solution:
import java.util.Scanner;
669
inputPass = input.nextLine();
if (inputPass.equals(password)) {
System.out.println("Welcome User!");
}
else {
for(int i = 0; i < 3; i++) {
System.out.println("Enter Your Password:");
inputPass = input.nextLine();
}
System.out.println("Access Denied! Try again");
}
}
}
Question 102
Question:
Solution:
import java.util.Scanner;
670
num = STDIN_SCANNER.nextInt();
System.out.println("\nAbsolute value of |" + num + "| is " + Math.abs(num));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
public class MyClass {
public static void main(String args[]) {
int x = 820;
int y = -985;
float z = -8.1f;
System.out.printf( "Absolute Value of x: %d \n", Math.abs(x) );
System.out.printf( "Absolute Value of y: %d \n", Math.abs(y) );
System.out.printf( "Absolute Value of z: %f \n", Math.abs(z) );
}
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
import java.util.Scanner;
671
float ht;
System.out.print("\nEnter the height (in cm): ");
ht = STDIN_SCANNER.nextFloat();
if(ht < 150.0) {
System.out.println("Dwarf.");
} else if(ht >= 150.0 && ht < 165.0) {
System.out.println("Average Height.");
} else if(ht >= 165.0 && ht <= 195.0) {
System.out.println("Taller.");
} else {
System.out.println("Abnormal height.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 104
Question:
Write a program to calculate the area of different geometric shapes using switch
statements.
Solution:
import java.util.Scanner;
672
int choice;
float r, l, w, b, h;
System.out.print("\nEnter 1 for area of circle: ");
System.out.print("\nEnter 2 for area of rectangle: ");
System.out.print("\nEnter 3 for area of triangle: ");
System.out.print("\nEnter your choice : ");
choice = STDIN_SCANNER.nextInt();
switch(choice) {
case 1:
System.out.print("Enter the radius of the circle: ");
r = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a circle is: %f", 3.14 * r * r);
break;
case 2:
System.out.println("Enter the length and width of the rectangle: ");
l = STDIN_SCANNER.nextFloat();
w = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a rectangle is: %f", l * w);
break;
case 3:
System.out.println("Enter the base and height of the triangle: ");
b = STDIN_SCANNER.nextFloat();
h = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a triangle is: %f", 0.5 * b * h);
break;
default:
System.out.print("\nPlease enter a number from 1 to 3.");
break;
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
673
}
Question 105
Question:
Write a program to accept a character from the keyboard and print "Yes" if it is equal to y.
Solution:
System.out.println(Math.random());
674
Question 106
Question:
Write a program that uses bitwise operators to multiply an entered value by four.
Solution:
import java.util.Scanner;
Question 107
Question:
Write a program to check whether a number entered by the user is power of 2 or not.
675
Solution:
import java.util.Scanner;
Question 108
Question:
Solution:
import java.util.Scanner;
676
public class MyClass {
public static void main(String[] args) {
int side1, side2, side3;
System.out.print("\nEnter the first side of the triangle: ");
side1 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second side of the triangle: ");
side2 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third side of the triangle: ");
side3 = STDIN_SCANNER.nextInt();
if(side1 == side2 && side2 == side3) {
System.out.print("\nThe given Triangle is equilateral.");
} else if(side1 == side2 || side2 == side3 || side3 == side1) {
System.out.print("\nThe given Triangle is isosceles.");
} else {
System.out.print("\nThe given Triangle is scalene.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 109
Question:
Write a program to print ASCII values of all the letters of the English alphabet from A to Z.
677
Solution:
Question 110
Question:
Solution:
import java.util.Scanner;
678
System.out.print("\nSum of all even number between 1 to " + num + " is: " +
sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 111
Question:
Solution:
import java.util.Scanner;
679
Question 112
Question:
Write a program that accepts an integer (x) and computes the value of x+xx+xxx.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
int x;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
x = in .nextInt();
System.out.printf("%d + %d%d + %d%d%d\n", x, x, x, x, x, x);
}
}
Question 113
Question:
Write a program that allows you to enter the cost price and the selling price of a product
and calculate profit or loss.
680
Solution:
import java.util.Scanner;
Question 114
Question:
Write a program that display the pattern like a right angle triangle using an asterisk.
681
Solution:
import java.util.Scanner;
Question 115
Question:
Write a program that display the pattern like a right angle triangle using a number.
Solution:
682
import java.util.Scanner;
Question 116
Question:
Write a program to determine the number and sum of all integers between 50 and 100
which are divisible by 2.
Solution:
683
int sum = 0;
System.out.println("Numbers between 50 and 100, divisible by 2: ");
for(int x = 51; x < 100; x++) {
if(x % 2 == 0) {
System.out.printf("%5d", x);
sum += x;
}
}
System.out.print("\nThe sum: " + sum);
}
}
Question 117
Question:
Write a program that uses the function to determine whether an entered number is even
or odd.
Solution:
import java.util.Scanner;
684
int x;
System.out.print("Enter any number: ");
x = STDIN_SCANNER.nextInt();
if(myfunc(x) != 0) {
System.out.print("\nThe number you entered is odd.");
} else {
System.out.print("\nThe number you entered is even.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 118
Question:
Solution:
import java.util.Scanner;
685
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 119
Question:
Solution:
import java.util.Scanner;
686
Question 120
Question:
Write a program to read 10 numbers from the keyboard and find their sum and average.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String [] args) {
int N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, sum;
float X;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any ten Numbers: ");
N1 = scan.nextInt();
N2 = scan.nextInt();
N3 = scan.nextInt();
N4 = scan.nextInt();
N5 = scan.nextInt();
N6 = scan.nextInt();
N7 = scan.nextInt();
N8 = scan.nextInt();
N9 = scan.nextInt();
N10 = scan.nextInt();
sum = N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 + N10;
X = sum /10;
System.out.println("The sum of 10 numbers = " + sum);
System.out.println("The average of 10 numbers = " + X);
}
}
687
Question 121
Question:
or not.
Solution:
Question 122
Question:
688
Solution:
Question 123
Question:
Solution:
689
}
Question 124
Question:
Solution:
Question 125
Question:
Solution:
690
public class MyClass {
public static void main(String[] args) {
String x = "Hai this is Alan";
String [] y = x. split(" ", 3);
for(String i : y)
System. out. println(i);
}
}
Question 126
Question:
Solution:
691
Question 127
Question:
Solution:
Question 128
Question:
Solution:
692
String a=String.join("-","Java","Programming");
System.out.println(a);
}
}
Question 129
Question:
Solution:
import java.util.Scanner;
693
Question 130
Question:
Solution:
Question 131
Question:
Solution:
694
}
}
Question 132
Question:
Solution:
Question 134
Question:
Solution:
695
public class MyClass {
public static void main(String[] args) {
int x = 12; public class MyClass {
System.out.print(x >> 1);
public static void main(String[] args) {
}
} String x = "Albert";
String y = "ALBERT";
System.out.println(x.equalsIgnoreCase(y))
;
Question 135
// Output: true
Question: }
Solution:
import java.util.Scanner;
696
Question 136
Question:
Solution:
import java.util.Scanner;
697
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
import java.util.Scanner;
698
Question 138
Question:
Solution:
import java.util.Scanner;
699
Question 139
Question:
Write a program to read integer "n" and print first three powers (n 1, n2, n3).
Solution:
import java.util.Scanner;
Question 140
Question:
700
Solution:
Question 141
Question:
Solution:
701
Question 142
Question:
Write a program to check if the string starts with the given prefix.
Solution:
Question 143
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
702
char ch;
Scanner x=new Scanner(System.in);
System.out.print("Enter a character: ");
ch=x.next().charAt(0);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) {
System.out.println(ch+" is Alphabet.");
}
else if(ch>='0'&&ch<='9') {
System.out.println(ch+" is Digit.");
}
else {
System.out.println(ch+" is Special Character.");
}
}
}
Question 144
Question:
Solution:
703
System.out.println("Java Home: "+System.getProperty("java.home"));
System.out.println("Java Vendor: "+System.getProperty("java.vendor"));
System.out.println("Java Vendor URL:
"+System.getProperty("java.vendor.url"));
System.out.println("Java Class Path:
"+System.getProperty("java.class.path")+"\n");
}
}
Question 145
Question:
Solution:
704
}
Question 146
Question:
Write a program to get the current system environment and system properties.
Solution:
import java.lang.*;
public class Main {
public static void main(String[] args) {
System.out.println("\nCurrent system environment:");
System.out.println(System.getenv());
System.out.println("\n\nCurrent system properties:");
System.out.println(System.getProperties());
}
}
Question 147
Question:
705
Solution:
import java.lang.*;
public class Main {
public static void main(String[] args) {
long startTime = System.nanoTime();
int i;
System.out.println ("The first 5 natural numbers are:\n");
for (i=1;i<=5;i++) {
System.out.println(i);
}
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Estimated time (in nanoseconds) to get the first 5
natural numbers: "+estimatedTime);
}
}
Question 148
Question:
Solution:
706
a = a.replace(' ', ch);
System.out.println("String after replacing spaces with the character '-': ");
System.out.println(a);
}
}
Question 149
Question:
Solution:
707
}
Question 150
Question:
Solution:
Question 151
Question:
Solution:
708
public class MyClass {
public static void main(String args[]){
System.out.println(Integer.toOctalString(8));
System.out.println(Integer.toOctalString(19));
System.out.println(Integer.toOctalString(81));
Question 152
Question:
Solution:
709
Question 153
Question:
Solution:
System.out.println(myfunc.x);
// Output: 15
}
Question 154
}
Question:
Solution:
710
public class MyClass {
public static void main(String args[]){
String hex="a";
int decimal=Integer.parseInt(hex,16);
System.out.println(decimal);
}
Question 155
Question:
Solution:
if(x.indexOf(y) != -1)
711
System.out.println("Second string is a rotation of first
string");
else
System.out.println("Second string is not a rotation of first
string");
}
}
}
Question 156
Question:
Solution:
Float a = Float.NaN;
Float b = 6.0f;
System.out.println(a +" - " + a.isNaN());
System.out.println(a +" - " + Float.isNaN(a));
System.out.println(b +" - " + Float.isNaN(b));
}
712
}
Question 157
Question:
Solution:
Float a = Float.NaN;
Float b = 6.0f;
System.out.println(a +" - " + a.isNaN());
System.out.println(a +" - " + Float.isNaN(a));
System.out.println(b +" - " + Float.isNaN(b));
}
public class MyClass {
}
public static void main(String[] args) {
for (String i : x) {
?
System.out.println(i);
713
Question 158
Question:
Solution:
import java.util.Scanner;
char operator;
Double number1, number2, result;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
switch (operator) {
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
714
break;
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
System.out.println(x[1][2]); // Output: 17
715
Question 159
Question:
Solution:
x[0] = "Elsa";
716
public class MyClass {
String x = "Einstein";
System.out.println(x.charAt(1));
// Output: i
double x =56.698;
double y =-56.898;
double z =56.45;
System.out.println(Math.round(x)); // Output: 57
System.out.println(Math.round(z)); // Output: 56
717
public class MyClass {
System.out.println(x.substring(15));
System.out.println(x.substring(26));
// Output: Concepts
718
public class MyClass {
int a = i; 10
System.out.println(a);
buffer.append(" Programming");
Output:
System.out.println(buffer);
Java Programming
}
Overloading provides
code clarity
reduce complexity
719
public class MyClass {
builder.append(" Programming");
System.out.println(builder);
Output:
Java Programming
720
Python Exercises
721
Question 1
Question:
import numpy as np
Solution:
x= np.ones([2,4])
a = 1
b = 2 print(x)
c= a+b print(x.dtype)
print(c)
print(x.shape)
# Output:
a = int(input("Enter a number: "))
b = int(input("Enter a number: ")) [[1. 1. 1. 1.]
c= a+b [1. 1. 1. 1.]]
print(c)
float64
(2, 4)
Question 2
Question:
Write a program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user.
722
Solution:
import sys
a = int(input("Enter a number: "))
if a % 2 == 0: print("Albert (Einstein)")
print("This is an even number.")
# Output: Albert (Einstein)
else:
print("This is an odd number.") print("Elsa (Einstein)", file=sys.stderr)
sys.stderr.write("David Einstein")
Question 3
# Output: David Einstein
Question:
Write a program to check whether a number entered by the user is positive, negative or
zero.
Solution:
print("Negative number") l
723
Question 4
Question:
names[0] = "David"
import calendar
yy = int(input("Enter year: ")) print(names)
mm = int(input("Enter month: "))
# Output: ['David', 'Paul', 'John']
print(calendar.month(yy, mm))
Question 5
Question:
Write a program to ask the user to enter the string and print that string as output of the
program.
x = ("ball", "bag", "bat")
y = iter(x)
# Output:
ball
Solution: print(next(y))
bag
x= input("Enter string: ") print(next(y))
bat
print("You entered:", x) print(next(y))
724
Question 6
Question:
Solution:
Question 7
Question:
Solution: x = abs(-9.78)
print(x)
x = ["ball", "book", "pencil"]
i = input("Type item to check: ") # Output: 9.78
if i in x:
print("Item exists in the list.")
else:
print("Item does not exist in the list.")
725
Question 8
Question:
Solution:
Question 9
print(x)
Question:
# Output: 15
Write a program to calculate cube of a number.
print(y)
# Output: 215
Solution:
import math
x = int(input("Enter a number: "))
y=math.pow(x,3)
print(y)
726
Question 10
Question:
x = math.ceil(6.8)
y = math.floor(6.8)
Solution:
print(x) # Output: 7
import math
print(y) # Output: 6
x = int(input("Enter a number: "))
y=math.sqrt(x)
print(y)
Question 11
Question:
Write a program that takes a list of numbers (for example, i = [6, 10, 75, 60, 55]) and
makes a new list of only the first and last elements of the given list.
Solution:
727
Question 12
Question:
Take a list, say for example this one: x = [1, 1, 2, 3, 2, 8, 18, 31, 14, 25, 78] and write a
program that prints out all the elements of the list that are less than 4.
x = "alan"
Solution:
y = iter(x) # Output:
x = [1, 1, 2, 3, 2, 8, 18, 31, 14, 25, 78]
a
for i in x:
l
if i < 4: print(next(y))
print(i) a
print(next(y))
n
print(next(y))
Question 13 print(next(y))
Question:
Let's say I give you a list saved in a variable: x = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write
one line of Python that takes this list 'x' and makes a new list that has only the even
Solution:
728
y = [i for i in a if i % 2 == 0]
print(y)
Question 14
Question:
Ask the user for a string and print out whether this string is a palindrome or not (A
palindrome is a string that reads the same forwards and backwards).
Solution:
import math
Question 15
Question:
Take two lists, say for example these two: x = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] y = [1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only
729
the elements that are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes.
Solution:
Question 16
Question:
for i in x:
file = open("testfile.txt","w")
file.write("Albert Einstein") print(i)
file.write("Elsa Einstein") if i == "john":
file.write("David Einstein.")
break
file.write("Why E=mc squared?.")
file.close()
# Output:
albert
john
730
Question 17
Question:
Solution:
with open('testfile.txt') as f:
i = f.readline() A program to split the string
while i: at every white-space character
print(i)
import re
line = f.readline()
x = re.split("\s", str)
Question 18 print(x)
Take two sets, say for example these two: x = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89} y = {1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} and write a program that returns a set that contains only
Solution:
731
Question 19
Question:
Write a program to split the characters of the given string into a list.
Solution:
print(y) import re
Question 20 print(x)
# Output: Stephen+William+Hawking
Question:
Create a program that asks the user for a number and then prints out a list of all the
divisors of that number.
Solution:
732
print(i)
Question 21
Question:
Solution:
largest = y
else: import re
largest = z
str = "Albert Einstein"
print("The largest number is", largest)
x = re.findall("in", str)
print(x)
Question:
733
Solution:
if x:
print("YES! We've got a match!")
else:
Question 23
print("No match")
Solution:
734
Question 24
Question:
A program to capitalize
Solution: the first letter of each
word in the string
x = int(input("Please Enter any Number: "))
for i in range(1, x+1):
print(i) import camelcase
c = camelcase.CamelCase()
str = "albert einstein"
print(c.hump(str))
Question 25
# Output: Albert Einstein
Question:
Write a program to calculate the sum and average of natural numbers from 1 to x.
Solution:
735
Question 26
Question:
print(type(True))
Solution:
# Output: <class 'bool'>
x = int(input("Please Enter any Number: "))
for i in range(x): print(type(False))
print("Albert Einstein")
# Output: <class 'bool'>
print(type([1,2]))
Question:
# Output: <class 'set'>
Solution:
def myfunc():
x = int(input("Enter a number: "))
y=int(input("Enter a number: "))
z= x*y
return z
736
i = myfunc()
print(i)
x = 6
y = 2
print(x+y)
Question 28
# Output: 8
Question:
print(x-y)
print(x*y)
# Output: 12
Solution:
print(x/y)
x = ["pen", "book", "ball"]
# Output: 3.0
x.append("bat")
print(x)
x = "23"
Question 29
y = "54"
z = x + y
Question:
print(z)
Write a program to remove an item from the list.
# Output: 2354
Solution:
737
print(x)
Question 30
Question:
Solution:
sys.stdout.write("Einstein")
Question:
Write a program to calculate the variance and standard deviation of the elements of the
list.
Solution:
import numpy as np
x= [2,6,8,12,18,24,28,32]
738
variance= np.var(x)
std = np.std(x) def main():
print(variance) print("Albert Einstein")
print(std)
if name == "__main__":
main()
Question 32
739
import random
x = ['Paper', 'Pencil', 'Book', 'Bag', 'Pen']
print(random.choice(x))
Question 34
Question:
Write a program that prints all the numbers from 0 to 6 except 2 and 6.
def main():
print("William")
Solution:
for x in range(6):
print("Stephen")
if (x == 2 or x==6):
main()
continue
print(x) print("Hawking") # Output:
Stephen
William
Question 35 Hawking
Question:
Write a program that takes input from the user and displays that input back in upper and
lower cases.
Solution:
740
x = input("What is your name? ")
print(x.upper()) print("Albert ", sep="")
print(x.lower()) print("Einstein")
# Output:
Albert
Question 36
Einstein
Question:
Solution:
x = "science.com"
print(x.startswith("phy"))
print("Albert ", end="")
print("Einstein")
Question:
Solution:
741
print(x,'x',i,'=',x*i)
Question 38
Question:
?
if x == y == z:
print("Equilateral triangle") main()
elif x==y or y==z or z==x:
print("isosceles triangle")
else:
print("Scalene triangle")
Question 39
Question:
Write a program to sum of two given integers. However, if the sum is between 15 to 20 it
will return 20.
742
Solution:
print(z)
main()
# Output: 4
Question 40
Question:
# Output:
albert
david
743
Question 41
Question:
def main():
Solution:
a = 2.5
import random
b = 2.9
print(random.randint(0,9))
print(float(a) + float(b))
main()
Question 42
# Output: 5.4
Question:
Solution:
744
Question 43
Question:
Given a list of numbers, iterate it and print only those numbers which are divisible of 2.
Solution: x = '2'
print(x)
x = [10, 20, 33, 46, 55]
for i in x: # Output: 2
if (i % 2 == 0): print(x.isdecimal())
print(i)
# Output: True
print(x.isnumeric())
# Output: True
Question 44
if x.isdecimal():
Question:
y = int(x)
# Output: 2
Solution:
import numpy
x = [1, 2, 3]
y = numpy.prod(x)
print(y)
745
Question 45
Question:
print(type(x))
A program to convert
Question 46
'string' to 'int'
Question:
x = 56.39
Solution:
print(type(x))
for x in range(0, 5):
print('#', end="") # Output: <class 'float'>
print("\n")
y = int(x)
A program to convert
746
Question 47
Question:
Solution: print(int(float(5.6)))
# Output: 5
x = "546.11235"
print(float(x)) print(int(float("5")))
print(int(float(x)))
# Output: 5
print(int(float(5)))
# Output: 5
Question 48
Question:
Solution:
# Define a dictionary
customers = {'1':'Mehzabin Afroze','2':'Md. Ali',
'3':'Mosarof Ahmed','4':'Mila Hasan', '5':'Yaqub Ali'}
747
print("The customer names are:")
# Print the values of the dictionary
def main():
for customer in customers:
print(customers[customer]) x = input('First number: ')
Question 49
?
Question:
Solution:
import math
print(dir(math))
748
Question 50
Question:
# Exception block
except (ValueError):
# Print error message
print("Enter a numeric value")
Output:
11
import array 13
x = array.array('i', [11,13,15,17,19]) 15
for i in x:
17
print(i)
19
749
Question 51
Question:
a = 4
Solution: b = 2
b -= 1 # is the same as b = b - 1
print(b)
Question 52 # Output: 1
Question:
750
Solution:
Question 53
Question:
Write a program that sorts three integers without the need of loops or conditional
statements.
import random
x = "123456789"
# Output: 3
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))
x = min(a, b, c)
z = max(a, b, c)
y = (a + b + c) - x - z
print("Numbers in sorted order: ", x, y, z)
751
import random
?
print(1 + int(3 * random.random()))
print(random.randrange(1, 3))
Question 54
Question:
Solution:
Question 55
Question:
Write a program to take in the marks of 5 subjects and display the grade.
752
Solution:
Question 56
Question:
Solution:
753
x=int(input("Enter lower range limit: "))
y=int(input("Enter upper range limit: "))
n=int(input("Enter the number to be divided by: "))
for i in range(x,y+1):
if(i%n==0):
print(i)
Question 57
Question:
Write a program to read two numbers and print their quotient and remainder.
Solution:
754
Question 58
Question:
Solution: x = 0
if x:
Question 59
x = 1
if x:
Question:
print("Albert Einstein")
Write a program to print odd numbers within a given range.
else:
print("Elsa Einstein")
Solution:
# Output: Albert Einstein
755
x=int(input("Enter the lower limit for the range: "))
y=int(input("Enter the upper limit for the range: "))
for i in range(x,y+1):
if(i%2!=0):
print(i)
Question 60
Question:
for i in range(5):
Solution:
print(i)
else:
n=int(input("Enter an integer: "))
a=[] print("Albert!")
for i in range(2,n+1):
if(n%i==0): # Output:
a.append(i)
0
a.sort()
print("Smallest divisor is:",a[0]) 1
Albert!
756
Question 61
Question:
y = 56
print(x == y)
Solution:
# Output: False
i=0
# Output: True
while(n>0):
i=i+1 print(y == 56.0)
n=n//10
# Output: True
print("The number of digits in the number are:", i)
print(None == None)
# Output: True
print(None == False)
Question 62
# Output: False
Question:
Write a program to read a number n and print and compute the series "1+2+…+n=".
Solution:
757
x=[]
for i in range(1, n+1):
a = 16
print(i, sep=" ", end=" ")
if(i<n): b = 4
print()
Question 63
Question:
Write a program to read a number n and print the natural numbers summation pattern.
Solution:
758
print()
Question 64
Question:
Write a program to read a number n and print an identity matrix of the desired size.
Solution:
11
13
import array 15
x = array.array('i', [11,13,15,17,19])
17
x.append(115)
19
for i in x:
115
print(i)
759
Question 65
Question:
Write a program to read a number n and print an inverted star pattern of the desired size.
Solution:
print(x)
Question:
Solution:
760
z = sqrt(x**2 + y**2)
print("The length of the hypotenuse is: ", z)
Question 67
x = """Stephen
Question:
William
print(x)
Solution:
# Output:
x=[] Stephen
n=int(input("Enter number of elements: "))
William
for i in range(1, n+1):
Hawking
y=int(input("Enter element: "))
x.append(y)
x.sort()
print("Largest element is: ",x[n-1])
Question 68
Question:
761
Solution:
x=[]
n=int(input("Enter number of elements: ")) x = 3 * 'Alan '
for i in range(1,n+1):
print(x)
y=int(input("Enter element: "))
# Output: Alan Alan Alan
x.append(y)
x.sort()
print("Second largest element is: ",x[n-2])
Question 69
Question:
Write a program to put the even and odd elements in a list into two different lists.
x = "Einstein"
Solution:
a = x[0]
a=[]
n=int(input("Enter number of elements:")) print(a)
for i in range(1,n+1):
# Output: E
b=int(input("Enter element:"))
a.append(b) b = x[3]
even=[]
print(b)
odd=[]
for j in a: # Output: s
762
if(j%2==0):
even.append(j)
else:
str = "wxyz"
odd.append(j)
print("The even list", even) print(str)
print("The odd list", odd)
# Output: wxyz
print(str)
Question:
Write a program to concatenate all elements in a list into a string and return it.
x = ["Alan", "Albert"]
y = ["Turing", "Einstein"]
Solution:
def myfunc(list):
for a in x:
result= ''
for i in list: for b in y:
Alan Einstein
Albert Turing
Albert Einstein
763
Question 71
Question:
Write a program to add the three integers given. However, the sum will be zero if two
values are equal.
Solution:
else:
print(y)
sum = a + b + c
return sum # Output: ALBERT
Question 72
Question:
764
Solution: x = "Einstein"
if "ein" in x:
Question 73
Question:
Write a program to create a list of tuples with the first element as the number and the
second element as the square of the number.
Solution:
765
Question 74
Question:
Write a program to create a list of all numbers in a range which are perfect squares and
the sum of the digits of the number is less than 10.
Solution:
?
print(x, chr(x))
Question 75
Question:
Write a program to convert a distance (in feet) to inches, yards, and miles.
Solution:
766
n = int(input("Enter the distance in feet: "))
x = n * 12
y = n / 3.0
x = "Albert Einstein"
z = n / 5280.0
print(x[1:4])
print("The distance in inches is: %i inches." % x)
# Output: lbe
print("The distance in yards is: %.2f yards." % y)
print("The distance in miles is: %.2f miles." % z) print(x[2:])
print(x[:2])
# Output: Al
Question 76
Question:
Write a program to generate random numbers from 1 to 20 and append them to the list.
Solution:
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
767
Question 77
Question:
Write a program to sort a list of tuples in increasing order by the last element in each
tuple.
import numpy as np
x = np.array([2, 4, 8])
y = np.array([3, 6, 12])
Solution:
print(x)
# Output: [2 4 8]
def last(n): print(y)
return n[-1]
# Output: [3 6 12]
# Output: 126
Output:
import array
19
x = array.array('i', [11,13,15,17,19])
17
x.reverse()
15
for i in x:
13
print(i)
11
768
Question 78
Question:
for i in x:
if i == ' ':
Solution:
break
Question 79 t
Question:
Solution:
769
import sys
x = ', '.join(sorted(sys.builtin_module_names))
print("The available built-in modules are: ")
print()
print(x) x = 2
i = x == 2
print(i)
if i:
Question:
print("Albert Einstein")
print("Elsa Einstein")
import sys
x = "three"
y = 154
z = [11, 12, 13, 'Ball', 'Bat']
print("Size of ",x,"=",str(sys.getsizeof(x))+ " bytes")
print("Size of ",y,"=",str(sys.getsizeof(y))+ " bytes")
print("Size of ",z,"=",str(sys.getsizeof(z))+ " bytes")
770
Question 81
Question:
x = 'Albert Einstein'
if i == ' ':
continue
Solution:
print(i)
t
Question 82
E
i
Question:
n
Write a program to display the current date and time.
s
e
Solution:
i
n
import datetime
771
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
x = 1915
y = 'Albert'
Question 83
print("%s Einstein's %s papers." % (y, x))
Solution:
pi=22/7
r = 8.0
V = 4.0/3.0*pi*r**3
print('The volume of the sphere is: ',V)
Question 84
Question:
Write a program to check whether every number in a list exceeds a specific number.
Solution:
772
x = [12, 33, 44, 55]
print()
print(all(i > 11 for i in x))
print(all(i > 100 for i in x))
print()
x = 1915
y = 'Albert'
Write a program that count the occurrences of a particular character within a given string.
Solution:
x = "Albert Einstein."
print("Number of occurrence of 'e' in the given string: ")
print(x.count("e"))
Question 86
Question:
Write a program to compute simple interest given all the required values.
773
Solution:
x = 1915
y = 'Albert'
Solution:
774
Question 88
Question:
Solution:
import os
path="1.txt"
if os.path.isdir(path):
print("It is a directory")
elif os.path.isfile(path):
print("It is a regular file")
else:
print("It is a unique file (socket, FIFO, device file)" )
print()
x = 1915
y = 'Albert'
Question:
Solution:
775
x=int(input("Enter an integer: "))
print("The divisors of", x, "are: ")
for i in range(1, x+1):
if(x%i==0):
print(i)
x = 1915
y = 'Albert'
Question:
Solution:
Question 91
Question:
776
Solution:
x = 1915
y = 'Albert'
Solution:
import site
print(site.getsitepackages())
777
Question 93
Question:
Solution:
x = 1915
y = 'Albert'
Solution:
778
x = 'Albert Einstein'
x=int(input("Enter the first number: "))
for i in x:
y=int(input("Enter the second number: "))
if(x>y): if i == ' ':
min=x
else: continue
min=y if i == 'n':
while(1):
if(min%x==0 and min%y==0): break
# Output:
A
Question 95
l
b
Question:
e
Solution: i
NSTEIN
import math
x=int(input("Enter the first number: "))
y=int(input("Enter the second number: "))
print("The GCD of the two numbers is", math.gcd(x,y))
779
x = [
["John", 56],
["Albert", 77],
["Mary", 39],
Question:
["James", 44],
print(type(x))
import os for i in x:
John 56
Albert 77
Alan 17
Question 97
Mary 39
James 44
Question:
Solution:
780
y=int(input('Enter number 2: '))
sum1=0 x = "Albert"
sum2=0
for i in range(1,x): print("'{}'".format(x))
if x%i==0: print("'{:12}'".format(x))
sum1+=i
for j in range(1,y): print("'{:<12}'".format(x))
if y%j==0:
print("'{:>12}'".format(x))
sum2+=j
if(sum1==y and sum2==x): print("'{:^12}'".format(x))
print('Amicable!')
else: # Output:
print('Not Amicable!')
'Albert'
'Albert '
'Albert '
' Albert'
Question 98
' Albert '
Question:
Write a program to find the area of a triangle given all three sides.
Solution:
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
781
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
x = "Albert"
Question 99
print("{:s}".format(x))
Write a program to find the gravitational force acting between two objects.
Solution:
Question 100
Question:
782
Solution:
a = 549.9678962314589
print("{:e}".format(a))
x = 'x549'
try: # Output: 5.499679e+02
i = float(x)
print("{:E}".format(a))
print('Numeric')
except (ValueError, TypeError): # Output: 5.499679E+02
print('Not numeric')
print("{:f}".format(a))
print()
# Output: 549.967896
print("{:.2f}".format(a))
# Output: 549.97
# Output: 549.967896
Question:
print("{:g}".format(a))
Write a program to find out which host the routine is running on. # Output: 549.968
print("{:G}".format(a))
# Output: 549.968
Solution:
print("{:n}".format(a))
# Output: 549.968
import socket
x = socket.gethostname()
print("Host name: ", x)
783
Question 102
Question:
Solution:
print("Albert " + x)
myfunc("Einstein")
784
Question 103
Question:
Write a program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/n.
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[::])
Question 104
# Output: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Question:
Write a program to get numbers divisible by 12 from a list using an anonymous function.
Solution:
785
Question 105
Question:
pi = 3.141592653589793
Solution:
r = 6
Question:
Write a program that accepts a number as input and returns an error if it is not a number.
Solution:
786
while True:
try:
x = 68
a = int(input("Enter a number: "))
print("This is a number") print("<%s>" % x)
break
# Output: <68>
except ValueError:
print("This isn't a number") print("<%10s>" % x)
print()
# Output: < 68>
print("<%-10s>" % x)
print("<%c>" % x)
Question 107
# Output: D
print("<%d>" % x)
Question:
# Output: <68>
Write a program to filter the negative numbers from a list.
print("<%0.5d>" % x)
# Output: <00068>
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[::1])
# Output: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
787
Question 108
Question:
Solution:
import array
x = array.array('i', [11,13,15,17,19,13])
print("Number of times the number 13 appears in the above array is: ", x.count(13))
# Output: Number of times the number 13 appears in the above array is: 2
788
Question 109
Question:
Solution:
a, b = 2, 4
result = a * a - 2 * a * b + b * b
print("({} - {}) ^ 2 = {}".format(a, b, result))
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[::2])
Question 110
# Output: ['1', '3', '5', '7', '9']
Question:
Write a program to generate a new string with the prefix "Al" from a given string. Return
the given text in its original form if it already contains the "Al" prefix.
Solution:
def myfunc(x):
if len(x) >= 2 and x[:2] == "Al":
return x
789
return "Al" + x
print(myfunc("Albert"))
print(myfunc("bert"))
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[1::2])
Question 111
# Output: ['2', '4', '6', '8', '10']
Question:
Solution:
def myfunc(y):
def myfunc(x):
i = 0
for x in y: return 6 * x
if x == 5:
i = i + 1
print(myfunc(6))
# Output: 36
return i
790
Question 112
Question:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[2:8:2])
Solution: # Output: ['3', '5', '7']
import os.path
print(os.path.isfile('1.txt'))
print(os.path.isfile('1.pdf'))
x[0] = '10'
print(x)
Question 113
# Output: ['10', '12', '13', '14']
Question:
Solution:
791
print(x)
Write a program to calculate the product of a list of numbers (without using for loop).
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Question 115
print(num[1:20:3])
Solution:
792
x=input("Enter first string: ")
y=input("Enter second string: ")
if(sorted(x)==sorted(y)):
print("The 2 strings are anagrams.")
else:
print("The 2 strings aren't anagrams.")
x[1:3] = ['john']
Question:
Write a program to form a string where the first character and the last character have
been exchanged.
Solution:
def change(x):
return x[-1:] + x[1:-1] + x[:1]
x=input("Enter a string: ")
print("Modified string: ")
print(change(x))
print(x)
793
Question 117
Question:
Solution:
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
x = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
print(x)
# Output: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
Question: # Output: [11, 10, 13, 10, 15, 10, 17, 10, 19, 10, 21, 10]
Write a program to take a string and replace every blank space with a hyphen.
Solution:
794
string=input("Enter a string: ")
a = ['alan', 'john', 'mary', 'david']
string=string.replace(' ','-')
print("Modified string:") b = a
print(string) a[0] = 'computer'
print(a)
print(b)
Question 119
# Output: ['computer', 'john', 'mary', 'david']
Question:
Write a program to calculate the length of a string without using library functions.
Solution:
import array
x = array.array('i', [11,13,15,17,19,22])
795
Question 120
Question:
b = deepcopy(a)
x = 'Albert Einstein'
print(any(i.islower() for i in x)) a[0] = 'albert'
print(a)
print(b)
Question:
Write a program to calculate the number of words and characters present in a string.
796
if(i==' '):
word=word+1
print("Number of words in the string: ")
print(word)
print("Number of characters in the string: ")
print(char)
Question:
places.
print('%f' % x)
# Output: albert:1915:john
print('%.2f' % x)
print()
def myfunc(x,y):
print(x+y) # Output: 58
myfunc("5","8")
797
Question 123
Question:
Solution:
count=0
# Output: ['xy', 'wz', 'pq']
for i in x:
if(i.islower()):
count=count+1
print("The number of lowercase characters is: ")
print(count)
Question 124
Question:
Write a program to count the number of lowercase letters and uppercase letters in a
string.
Solution:
798
x=input("Enter a string: ")
count1=0 x = "bat ball bag".split()
count2=0 print(x)
for i in x:
# Output: ['bat', 'ball', 'bag']
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is: ")
print(count1)
print("The number of uppercase characters is: ")
print(count2)
Question 125
Question:
print(x.index('orange'))
count1=0
count2=0
for i in x:
if(i.isdigit()):
799
count1=count1+1
count2=count2+1
print("The number of digits is: ")
print(count1)
print("The number of characters is: ")
print(count2)
x.insert(2, 'fig')
print(x)
Question 126
# Output: ['apple', 'orange', 'fig', 'mango', 'kiwi']
Question:
Write a program to form a new string made of the first 2 characters and last 2 characters
Solution:
x.insert(len(x), 'papaya')
print(x)
800
Question 127
Question:
Solution:
x[2:4] = []
print(x)
Question 128
# Output: ['apple', 'orange', 'papaya']
Question:
Solution:
x = 60
if x.bit_length() <= 63:
801
print((-2 ** 63).bit_length())
print((2 ** 63).bit_length()) x = [17, 22, -44, 38, 6]
print(x)
x.sort(reverse=True)
Write a program that returns true if the two given integer values are equal, or if their sum
or difference is 10.
Solution:
802
Question 130
Question:
Write a program to add two objects if they are both of the integer type.
Solution:
x.sort(key=len)
Question 131
print(x)
Solution:
803
x='122.22'
x = x.ljust(8, '0')
print(x)
x = ['alan', 'albert', 'james', 'bob']
x = x.ljust(10, '0')
print(x) x.sort(key=len, reverse=True)
print(x)
Question 132
Question:
Solution:
import json
print(json.dumps({'Albert': 1, 'Alan': 2, 'Alex': 3}))
Question 133
Question:
804
Solution:
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else: for x in range(10, 19, 5):
print("Key isn't present!")
print(x)
# Output:
10
Question 134 15
Question:
Solution:
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary is: ")
print(sum(d.values()))
805
Question 135
Question:
y = ['david']
d={'A':10,'B':10,'C':239} print(x)
x=1
for i in d: # Output: ['albert', 'elsa']
x=x*d[i]
print(x * 2)
print(x)
# Output: ['albert', 'elsa', 'albert', 'elsa']
print(x + y)
Question:
Solution:
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
806
print(d)
a, b = 11, 12
key=input("Enter the key to delete(a-d):")
if key in d: print(a)
del d[key]
# Output: 11
else:
print("Key not found!") print(b)
exit(0)
# Output: 12
print("Updated dictionary")
print(d) a, b = b, a
print(a)
# Output: 12
print(b)
Question 137
# Output: 11
Question:
Write a program to list the home directory without using an absolute path.
Solution:
import os.path
print(os.path.expanduser('~'))
x = [5,8,57,35,44,14,28]
807
Question 138 x = [0] * 5
0 0
1 0
Solution:
2 0
3 0
print("Enter the value of a and b: ")
4 0
a, b = map(int, input().split())
print("The value of a and b are: ", a, b)
print([2] * 5)
Question 139
# Output: [2, 2, 2, 2, 2]
Question:
Solution:
a = 'true'
a = int(a == 'true')
print(a)
a = 'xyz'
808
a = int(a == 'true')
print(a)
y = 'AB+CD+EF+GH+IJ+KL+MN'
x = y.split('+')
x.sort(key=len, reverse=True)
print(x)
Question 140
# Output: ['AB', 'CD', 'EF', 'GH', 'IJ', 'KL', 'MN']
Question:
Solution:
print(isinstance(16,int) or isinstance(16,str))
print(isinstance("16",int) or isinstance("16",str))
Question 141
Question:
Write a program to count the number of vowels present in a string entered by the user
using sets.
809
Solution:
x.extend(y)
Solution:
810
Question 143
Question:
Write a program to display which letters are in the first string but not in the second string.
Solution:
Distributed computing systems can vary in size and complexity, ranging from small peer-to-peer
networks to large-scale grid computing systems that involve thousands of computers. Examples of
distributed computing systems include cloud computing platforms, content delivery networks, and
distributed databases.
Question 144
Distributed computing can offer a number of advantages over traditional centralized computing
systems, such as increased processing power, scalability, fault tolerance, and reduced latency.
Question: However, it can also introduce challenges related to security, data consistency, and communication
between the different nodes in the network.
Solution:
811
i = ['list', True, 8.9, 6] import numpy as np
if type(i) is list:
x = np.random.randint(10, size=(2, 3))
print('i is a list')
elif type(i) is set: print(x)
?
print('i is a set')
elif type(i) is tuple:
print('i is a tuple')
else:
print('Neither a set, list, or tuple.')
Question 145
Question:
# Output:
albert => 46
Solution: x = {
bob => 18
"albert" : "46",
john => 68
def myfunc(n): "bob" : "18",
if (n < 2): "john" : "68",
return (n % 2 == 0)
}
return (myfunc(n - 2))
n=int(input("Enter a number: "))
if(myfunc(n)==True): for name, age in x.items():
print("Number is even!")
print("{} => {}".format(name, age))
else:
812
print("Number is odd!")
Question 146
Question:
Write a program that examines a list of numbers to see if they are all distinct from one
another. x = {}
x['name'] = 'albert'
print(x)
Solution:
# Output: {'name': 'albert'}
x['email'] = 'albert_john@gmail.com'
def myfunc(x):
if len(x) == len(set(x)): print(x)
x = "Albert "
print(x + y)
813
Question 147
Question:
Write a program to add two positive numbers without using the '+' operator.
Solution: x = {
'name': 'Albert',
print(x.get('age'))
# Output: 26
print(x.get('email'))
# Output: None
Question 148
print(x.get('address'))
Solution:
814
def myfunc(n): x = {
return(n*myfunc(n-1))
'email': None
n = int(input("Enter a number: "))
print("Factorial of", n, "is:", myfunc(n)) }
print('name' in x.values())
# Output: False
# Output: True
Question:
Write a program to determine whether a right triangle is formed by three given side
lengths. If the specified sides make a right triangle, print "Yes," otherwise print "No."
Solution:
815
Question 150
Question:
Write a program to find the number of equal numbers among three given integers.
x = {
Solution:
'name': 'Albert',
def myfunc(a, b, c):
'age': 26,
result= set([a, b, c])
if len(result)==3: 'email': None
return 0 }
else:
return (4 - len(result))
print(x)
Question 151
Question:
Solution:
816
def myfunc(x):
result = [int(x) for x in x.split() if x.isdigit()]
return result
x = "5 bags, 10 pencils and 55 books"
print(myfunc(x))
Question 152
Question:
x = {}
x['A'] = 11
Solution:
x['B'] = 12
x = list[0]
x['D'] = 14
for i in list:
if i < x: print(x)
x = i
return x
print(myfunc([11, 22, -28, 3])) # Output: {'A': 11, 'B': 12, 'C': 13, 'D': 14}
817
Question 153
Question:
Write a program to determine whether every string in a list is equal to a given string..
x = {
Solution:
'name': 'Albert',
# Output:
Question 154
name -> Albert
Solution:
818
with open(x, 'r') as f:
for line in f: import numpy as np
num_words += len(line.split())
x = np.random.random((3, 6))
print("Number of words: ", num_words)
print(x)
Question 155 ?
Question:
Solution:
y = 12.5
z = "Albert"
819
Question 156
Question:
x = set()
# Output: set()
x.add('Mary')
Solution:
print(x)
x.add('Mary')
print(x)
# Output: {'Mary'}
Question 157
x.add('John')
Question: print(x)
Write a program that computes the average of two lists. # Output: {'John', 'Mary'}
Solution:
820
print("The Average of two lists: ", myfunc(x, y))
Question 158
Question:
Write a program to determine the maximum and minimum value in the three given lists.
Solution:
x = [12,13,15,28,27,32,53]
y = [54,32,91,0,41,13,19]
z = [12,11,51,16,15,58,49]
print("Maximum value in the three given lists is: ")
print(max(x+y+z))
print("Minimum value in the three given lists is: ")
print(min(x+y+z))
x = int(5)
y = int(5.2)
w = float(5.6)
z = int("6")
print(x) # Output: 5
print(y) # Output: 5
print(z) # Output: 6
821
Question 159
Question:
Solution:
Question 160
Question:
import numpy as np
# Output:
x = np.eye(2)
Solution: [[1. 0.]
print(x)
[0. 1.]]
print()
x = [{},{},{}]
y = [{2:6},{},{}] y = np.eye(2, 4) [[1. 0. 0. 0.]
print(all(not i for i in x)) [0. 1. 0. 0.]]
print(y)
print(all(not i for i in y))
822
Question 161
Question:
Write a program that takes two lists and returns True when at least one of the elements in
x = 5
Solution:
def myfunc(i):
i = i+1
def myfunc(A, B):
return i
result = False
for x in A:
for y in B: print(x)
if x == y: # Output: 5
result = True
print(myfunc(x))
return result
# Output: 6
print(myfunc([21,22,23,24,25], [25,26,27,28,29]))
print(myfunc([31,32,33,34,35], [36,37,38,39])) print(x)
# Output: 5
x = "Albert Einstein"
823
Question 162
Question:
Solution: x = lambda a, b, c: a + b + c
print(x(2, 2, 2))
x = []
# Output: 6
if x:
print("List is not empty")
else:
print("List is empty")
Question 163
Question:
Write a program to read a file and capitalize the first letter of every word in the file.
Solution:
824
set(['John', 'Mary'])
print(x)
print(y)
Question 164
# Output: {'Joe', 'Bob', 'Mary', 'Albert'}
Question:
c = a + b
x=input("Enter the file name: ") return c
for line in reversed(list(open(x))):
print(line.rstrip())
print(myfunc(12, 33))
# Output: 45
print(myfunc(28, 93))
Question:
825
Solution:
x :int = 6
print(x)
# Output: 6
Question 166
Question:
Solution:
def myfunc(x):
x :str = "Albert"
x = x.replace(' ','')
return x print(x)
# Output: Albert
print(myfunc("a lbe rt ein stein"))
print(myfunc("a l a n"))
826
Question 167
Question:
Write a program that calculate the difference between a given number and 10, returning
double the absolute difference if the value is higher than 10.
Solution:
def myfunc(x):
if x <= 10: x :float = 26.69
return 10 - x
print(x)
else:
return (x - 10) * 2 # Output: 26.69
print(myfunc(8))
print(myfunc(16))
Question 168
Question:
Write a program that adds three given numbers, returning three times their sum if the
values are equivalent.
827
Solution:
if a == b == c:
sum = sum * 3 print(myfunc(12, 13))
return sum
# Output: 25
Question 169
Question:
Solution:
import platform
print(platform.architecture()[0])
828
Question 170
Question:
import os
birthdays = {
'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
829
Question 171
Question:
Write a program to find the name and location of the file that is currently running.
Solution:
import os
print("Current File Name : ", os.path.realpath(__file__))
import platform
print(platform.system())
print(platform.release())
Question:
# Output: 10
Write a program to implement password generator.
Solution:
import random
x =
"abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
830
passlen = 8
print("".join(random.sample(x, passlen)))
831
Question 174
from functools import reduce
Question:
print(reduce(lambda a, b: a+b, [], 1))
# Output: 10
Solution:
print(reduce(lambda a, b: a*b, [5, 6], 0))
x='Albert Einstein\n'
# Output: 0
print(x.rstrip())
print(reduce(lambda a, b: a*b, [6, 5], 1))
# Output: 30
Question:
Write a program to remove existing indentation from all of the lines in a given text.
Solution:
import textwrap
x = '''
Albert Einstein was a German-born theoretical physicist,
widely acknowledged to be one of the greatest and most
influential physicists of all time. Einstein is best known
for developing the theory of relativity, but he also made
832
important contributions to the development of the theory of
quantum mechanics.
'''
print(x)
print(textwrap.dedent(x))
Question 176
Question:
?
print(multiprocessing.cpu_count())
Question 177
Question:
833
Solution:
def myfunc(x):
if len(x) % 6 == 0:
return ''.join(reversed(x))
return x
print(myfunc('alan'))
print(myfunc('albert'))
y = [1, 2, 3, 4, 5]
Question 178
print(list(zip(x, y)))
# Output: [('Mon', 1), ('Tue', 2), ('Wed', 3), ('Thru', 4), ('Fri', 5)]
Question:
Put "xyz" at the end of the specified string (length should be at least 3). If the provided
string already ends with "xyz," add "123" to it. If the specified string's length is less than
import numpy as np
Solution:
x= np.zeros(5, dtype='float32')
print(x)
def myfunc(x):
i = len(x) # Output: [0. 0. 0. 0. 0.]
print(x.dtype)
if i > 2:
if x[-3:] == 'xyz': # Output: float32
x += '123'
834
else:
x += 'xyz'
return x
print(myfunc('xy'))
print(myfunc('xyz'))
print(myfunc('morning'))
y = [1, 2, 3, 4, 5]
print(dict(zip(x, y)))
Question 179
# Output: {'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thru': 4, 'Fri': 5}
Question:
import random
print(x /2)
x = [11, 12, 13, 14, 15]
random.shuffle(x) # Output: [3. 4. 5.]
print(x)
print(x.dtype)
# Output: int8
835
Question 180
Question:
Three positive numbers are present in a list. Write a program to determine whether the
sum of the digits in each number is equal or not. If true, return true; otherwise, return
false.
x = [True, True]
y = [True, False]
Solution:
z = [False, False]
print(all(x))
def myfunc(x):
return x[0] % 9 == x[1] % 9 == x[2] % 9 # Output: True
x = [14, 5, 23]
print(all(y))
print(myfunc(x))
# Output: False
print(all(z))
# Output: False
Question 181
print()
print(any(x))
Question:
# Output: True
Write a program to get IP address of your computer.
print(any(y))
# Output: True
Solution: print(any(z))
836
y = socket.gethostbyname(x)
print("Your Computer Name is: " + x)
print("Your Computer IP Address is: " + y)
Question 182
Question:
Write a program to determine whether a series of integers has an increasing trend or not.
Solution:
def myfunc(x):
if (sorted(x) == x): print(12 > 10)
return True
# Output: True
else:
print(10 > 15)
return False
# Output: False
print(myfunc([11,12,13,14]))
print(myfunc([11,12,15,13,14]))
x.clear()
print(x) # Output: []
837
Question 183
Question:
x = [12, 14]
Solution:
print(all(map(lambda i: i > 5, x)))
import random
min = 1 # Output: True
max = 6
print(all(map(lambda i: i > 13, x)))
Question 184
Question:
838
Solution:
Question 185
Question:
import numpy as np
# Output: int32
Question:
Write a program to check whether the given integer is a multiple of both 3 and 5.
839
Solution:
Question 187
Question:
Write a program to display all the multiples of 5 within the range 10 to 70.
for i in x:
?
for i in range(10,70):
if (i%5==0): print(i)
print(i)
print(x)
Question 188
Question:
Write a program to display all integers within the range 50-100 whose sum of digits is an
even number.
840
Solution:
for i in range(50,100):
num = i
sum = 0 x = lambda a: a + 5
while(num!=0):
print(x(2))
digit = num%10
sum = sum + digit # Output: 7
num = num//10
if(sum%2==0):
print(i)
Question 189
Question:
Write a program to print the numbers from a given number n till 0 using recursion.
841
myfunc(9)
from functools import reduce
x = 5
Question:
Solution:
num = [8,3,1,6,2,4,5,9]
count = 0
for i in range(len(num)):
if(num[i]%2!=0):
count = count+1
print("The number of odd numbers in the array are: ", count)
Question 191
Question:
Solution:
842
import numpy as np
def myfunc(x):
x = np.array([
return x[::-1].lower()
[ 11, 12, 13, 14, 15],
?
x = "JAVASCRIPT"
print(myfunc(x)) [ 12, 13, 14, 15, 16]
])
print(x)
print(x * 6)
Question 192 print(x + 5)
Question:
import itertools
if a >= b: 11
break
return a
12
else:
13
return b
14
a = 3 15
b = 5
16
print(maximum(a, b))
Solution:
843
a = 3
b = 5
Solution:
print(issubclass(GeneratorType, Iterator))
a = 3
# Output: True
b = 5
print(issubclass(Iterator, Iterable))
print(a if a >= b else b)
# Output: True
A generator is an iterator
An iterator is an iterable
Question 193
Question:
y = x[2:5]
Solution: print(y)
x[2] = 99
if a <= b:
print(x)
return a
else: # Output: [11, 11, 99, 13, 15, 18, 19, 35, 64]
return b print(y)
844
import itertools
a = 3
b = 9 i = 0
print(minimum(a, b))
for x in itertools.cycle(['A', 'B', 'C']):
print(x)
i = i+1 # Output:
Question 194
A
if i >= 4:
Question: B
break
C
Write a program to calculate Profit or Loss. print('')
A
12
Question 195 14
845
Solution:
def myfunc():
total = physics + math + chemistry
percentage = (total / 300) * 100 yield 24
yield 48
print("Total Marks = %.2f" %total)
yield 64
print("Percentage = %.2f" %percentage)
x = 5
y = 100
# Output: Y
846
Question 196 def myfunc():
yield 24
Question:
yield 48
x = myfunc()
Solution:
print(type(x))
x = int(input(" Enter the Value of N : "))
for i in x:
<class 'generator'>
24
Question 197
48
64
Question:
Solution:
847
Question 198
Question:
def myfunc(name):
def x():
Solution: print(f"Albert {name}")
total = 0 y = myfunc("Einstein")
y()
for num in range(1, x+1):
# Output: Albert Einstein
if(num % 2 == 0):
print("{0}".format(num))
total = total + num
Question 199
Question:
Solution:
848
x = int(input(" Enter the Value of N : "))
total = 0
Question 200
Question:
Solution:
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print(ch, "is an Alphabet.")
else: x = 21
print(ch, "is Not an Alphabet.")
y = 5
z = 35
849
Question 201
Question:
Solution:
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print(ch, "is an Alphabet.")
elif(ch >= '0' and ch <= '9'):
print(ch, "is a Digit.")
else:
print(ch, "is a Special Character.") say = print
say("Albert Einstein")
Question:
Solution:
850
if(ch.islower()):
print(ch, "is a Lowercase character")
else:
print(ch, "is Not a Lowercase character")
def myfunc():
Question 203
x = 2
yield x
Question:
yield x
Solution:
x += 2
if(ch.isupper()):
for i in myfunc():
print(ch, "is a Uppercase character")
else: print(i)
# Output:
Question 204 2
4
Question: 6
851
Solution:
while True:
yield x
Question 205
x += 1
Question:
for i in myfunc():
Write a program to convert string to Uppercase.
print(i)
if i >= 5:
break
Solution:
1
string = str.upper()
2
852
Question 206
def myfunc():
Question: i = 0
return i
Solution:
print(myfunc())
2
Question 207
Question:
Solution:
binary = bin(decimal)
853
octal = oct(decimal)
hexadecimal = hex(decimal)
Question 208
Question:
Solution:
i = 0
i += 1 # Output:
if total == 180:
print("\nThis is a Valid Triangle") print(i) 1
else:
if i > 0:
print("\nThis is an Invalid Triangle")
break
854
Question 209
Question:
Write a program that inputs an age and print age after 20 years .
Solution:
print(i)
Question:
if i == 12:
Write a program to print the number of seconds in year. x.remove(12)
# Output:
print(x)
11
12
Solution:
13
days=365
14
hours=24
[11, 13, 14]
minutes=60
seconds=60
print("Number of seconds in a year : ",days*hours*minutes*seconds)
855
Question 211
Question:
Write a program that inputs a string and then prints it equal to number of times its
length. i = 0
def myfunc():
global i # Output:
Solution:
i += 1 1
str = input("Enter string: ")
return i 2
b = len(str)
3
a = str * b
print(a)
print(myfunc())
print(myfunc())
Question:
Write a program to convert a given list of strings and characters to a single list of
characters.
Solution:
def myfunc(x):
result = [i for y in x for i in y]
return result
856
x = ["alan", "john", "w", "p", "james", "q"]
print(myfunc(x))
x = 22
y = 5
z = 73
if x > y or x > z:
x = 1
print(x) 0
if (x == 3): 1
break 2
x = x+1 3
x = 0 1
while x < 8: 2
x = x+1 4
if (x == 3): # Output 5
continue 6
print(x) 7
857
say = print
import numpy as np
def mult(x, y):
x = np.array([11, 11, 12, 13, 15, 18, 23, 31, 65])
return x * y
print(x)
print(x[2:5])
# Output: 36
# Output: [12 13 15]
import numpy as np
print(x) # Output:
[[ 2 4 6]
[ 8 10 12]]
print(y)
# Output:
[[ 3 6 12]
[15 18 21]]
print(x*y)
# Output:
[[ 6 24 72]
858
print(np.multiply(x, y))
# Output:
[[ 6 24 72]
import numpy as np
print(x.dtype)
# Output: bool
print(x)
import numpy as np
print(x)
print(np.vectorize(len)(x))
# Output: [6 5 4 8 3]
def myfunc():
# Output:
return 26
26
print(myfunc())
26
print(myfunc())
26
print(myfunc())
859
a = ['pqrs', 'wxyz']
print(a)
def myfunc():
# Output: ['pqrs', 'wxyz'] return 26
print(a[0:1]) return 27
print(a[0])
print(myfunc())
# Output: pqrs
print(myfunc())
print(a[0][0])
print(myfunc())
# Output: p
# Output:
print(a[0][1]) 26
# Output: q 26
print(a[0][0:2]) 26
# Output: pq
import numpy as np
# Output: [(6, 'Albert'), (5, 'James'), (4, 'Mary'), (8, 'Einstein'), (3, 'Bob')]
import multiprocessing as mp
# Output: 4
860
x = complex(5, 6)
return y
print(x.real)
# Output: 5.0
print(f(11))
print(x.imag)
print(f(12))
print((-1) ** 0.5)
# Output:
# Output: (6.123233995736766e-17+1j)
[11]
print(complex(0, 1))
[11, 12]
# Output: 1j
[11, 12, 13]
print(complex(0, 1) ** 2)
# Output: (-1+0j)
if y == None:
y = [] # Output:
y.append(x) [11]
return y [12]
[13]
print(f(11))
print(f(12))
print(f(13))
861
x = 59
def f():
print(x)
f()
# Output: 59
import pandas
0 11
print(x)
1 11
2 12
print(x.values)
3 13
print(x.sum()) 5 18
dtype: int64
# Output: 80
print(x.count())
# Output: 6
print(x.mean())
# Output: 13.333333333333334
print(x.median())
# Output: 12.5
print(x.std())
# Output: 2.7325202042558927
862
import numpy as np
for _ in range(10):
x = np.array([112], 'uint8')
?
print('Albert')
print(x.dtype)
# Output: uint8
print(x)
# Output: [112]
x[0] += 1
import numpy as np
print(x)
x = np.array([11, 12, 13])
# Output: [113]
y = np.array([14, 15, 16])
x[0]-=1
z = np.array([17, 18, 19])
print(x)
print(x)
# Output: [112]
# Output: [11 12 13]
x[0]= 126
print(y)
print(x)
# Output: [14 15 16]
# Output: [126]
print(z)
x[0]+=1
# Output: [17 18 19]
print(x)
w = np.hstack([x, y])
# Output: [127]
print(w)
q = np.hstack([w, z])
print(q)
863
for i in [1, 2, 3]:
1
print(i)
Albert
print('Albert' * i)
2
AlbertAlbert
3
# Output:
AlbertAlbertAlbert
print(6, type(6))
print(6.8, type(6.8)) b = 1
print(False, type(False))
print(None, type(None))
def x(i):
# Output: None <class 'NoneType'>
return 5*i
b = 3
print(x(b) + x(3*b-1))
# Output: 55
864
print(format(.1, '.20f'))
# Output: 0.10000000000000000555
print(format(.2, '.20f'))
# Output: 0.20000000000000001110
# Output: 0.30000000000000004441
print(format(.3, '.20f'))
# Output: 0.29999999999999998890
Image processing refers to the use of algorithms and techniques to analyze, transform, enhance, and manipulate digital images.
It involves the application of various mathematical and computational methods to extract useful information from an image,
correct image defects, and create new images. Image processing techniques can be used for a wide range of applications,
including medical imaging, remote sensing, surveillance, computer vision, and digital photography. Some common tasks
performed by image processing algorithms include:
• Image filtering: This involves the removal of noise, enhancement of image features, and smoothing of edges.
• Image segmentation: This involves dividing an image into meaningful regions, based on properties such as color,
texture, and intensity.
• Image compression: This involves reducing the size of an image while preserving its quality, to save storage space
and reduce transmission time.
• Image recognition: This involves the automatic identification of objects, patterns, and features in an image, using
machine learning and computer vision techniques.
• Image restoration: This involves the recovery of lost or damaged image information, such as removing scratches,
stains, and other defects.
Overall, image processing plays an important role in many fields, enabling researchers and professionals to extract valuable
insights and information from digital images.
865
LINUX − OVERVIEW
Linux is an operating system that is free and open-source and is based on the Unix system. It
was first released in 1991 by Linus Torvalds and has since become one of the most widely
used operating systems in the world, powering everything from mobile devices to
supercomputers. Linux is renowned for its dependability, flexibility, and safety. It is highly
customizable and can be used for a wide range of applications, from servers and
supercomputers to desktops and laptops. Linux distributions, or "distros", are created by
different organizations and individuals to cater to different needs and use cases. One of the
key features of Linux is its command-line interface, which allows users to interact with the
system using text commands. This can be daunting for new users, but it offers a high degree
of control and customization that is not available in other operating systems. Many Linux
distros also come with graphical user interfaces (GUIs) that make it easier for beginners to
use. Another key feature of Linux is its package management system, which allows users to
easily install and manage software packages from online repositories. This makes it easy to
keep the system up-to-date and install new software. Linux is also known for its security
features, including built-in firewalls, encryption, and permission-based access control. This
makes it a popular choice for servers and other applications where security is a top priority.
Overall, Linux is a powerful and flexible operating system that offers many advantages over
other operating systems. While it can be challenging to learn at first, it offers a high degree of
control and customization that is not available in other operating systems, which makes it an
appealing option for programmers, system administrators, and other power users.
Linux is a free and open-source operating system that has many advantages over proprietary
operating systems like Windows and macOS. Here are some of the main advantages of Linux:
866
• Cost: Linux is free to use and distribute, which makes it a cost-effective option for both
personal and business use. You don't need to purchase a license or pay for updates, which
can save a significant amount of money over time.
• Flexibility: Linux is highly customizable and can be tailored to meet the specific needs
of users. This allows users to create a personalized computing environment that suits their
workflow and preferences.
• Stability: Linux is renowned for its dependability and durability. It rarely crashes or
freezes, and is not vulnerable to viruses or malware as Windows is. This makes it an ideal
choice for mission-critical applications and servers.
• Security: Linux is more secure than other operating systems because of its built-in
security features, such as secure boot, firewall, and file permissions. Additionally, since
Linux is open-source, security experts around the world can contribute to identifying and
fixing vulnerabilities, making it more secure than proprietary operating systems.
• Performance: Linux is renowned for its quick responsiveness and little resource needs.
It can run on older hardware and doesn't require high-end hardware to run smoothly.
• Open-source community: Linux has a large and active community of developers and
users who contribute to its development and support. This means that there is a wealth of
online resources, documentation, and forums available to help users solve problems and
get the most out of Linux.
• Compatibility: Linux is compatible with a wide range of hardware, making it a versatile
choice for users who have older or specialized hardware.
• Free software: Linux comes with a wide range of free and open-source software,
including productivity tools, media players, and development tools. This means that users
can save money on software licenses and have access to high-quality software for free.
Overall, Linux is a powerful, customizable, and cost-effective operating system that offers many
advantages over proprietary operating systems. It's an ideal choice for users who value
performance, stability, security, and flexibility in their computing environment. While Linux has
many advantages, there are also some disadvantages to using it. Here are some of the main disadvantages
of Linux:
867
• Lack of user-friendly interface: While the command-line interface of Linux provides
greater control and flexibility, it can be difficult for beginners to use. The graphical user
interface of some Linux distributions may also be less polished and intuitive than those of
Windows or macOS.
• Limited software availability: While there is a wide range of software available for
Linux, it can still be more limited than what is available for Windows or macOS. Some
specialized software, such as Adobe Photoshop or Microsoft Office, may not be available
for Linux.
• Compatibility issues: Linux may not be compatible with all hardware or software. This
can be especially problematic for users who need to use specific hardware or software for
their work or hobbies.
• Fragmentation: The open-source nature of Linux means that there are many different
distributions and versions available. This can lead to fragmentation in the community and
make it more difficult for users to find support or find the right distribution for their
needs.
• Learning curve: Because Linux is different from Windows and macOS, there can be a
steep learning curve for new users. Users may need to learn new commands and methods
for accomplishing tasks that are familiar on other operating systems.
• Lack of professional support: While there are many online resources and forums
available to help Linux users, there may be a lack of professional support options for
users who need more advanced help or support.
• Gaming support: While gaming on Linux has improved significantly in recent years, it
still lags behind Windows in terms of support and compatibility for many games.
• Security: While Linux is generally considered to be more secure than Windows, it is not
immune to security vulnerabilities or malware. Linux users must still take appropriate
security precautions to protect their systems.
Overall, Linux can be a great operating system for many users, but it may not be the best fit for
everyone. It's important to carefully consider the advantages and disadvantages of Linux before
deciding whether to use it.
868
Here are some funny facts about Linux:
The original name for Linux was "Freax", which was a combination of "free", "freak",
and "Unix". The name was changed to Linux by the creator of the kernel, Linus Torvalds.
The Linux mascot is a penguin named Tux. The original concept art for Tux was created
by Larry Ewing in 1996.
The first ever recorded message sent from space to Earth was sent using Linux. The
message was sent by astronaut David A. Wolf, who used a laptop running Linux to send
the message to Mission Control.
There is a Linux distribution called "Gentoo" that is designed to be compiled from
source code by the user. This can take hours or even days, but it allows for a highly
customized and optimized system.
The creator of Linux, Linus Torvalds, once said that he named his kernel "Linux"
because it sounded better than "Freax" and because he wanted to "annoy" the creator of
the Unix operating system, which he was inspired by.
In 2012, a group of programmers from the Netherlands created a fully functioning car
that was powered by Linux. The car was named "Edison", and it was able to drive up to
60 miles per hour.
There is a Linux distribution called "Damn Small Linux" that can fit on a business card-
sized CD-ROM.
In 2016, the Linux kernel reached over 20 million lines of code, making it one of the
largest software projects in the world.
The operating system on the International Space Station (ISS) is based on Linux.
The Linux operating system has been used to power everything from smartphones and
tablets to supercomputers and servers. It's even used to power the majority of the world's
top 500 supercomputers.
869
C − OVERVIEW
• Simple and easy to learn: C has a simple and concise syntax, making it easy for beginners
to learn and use.
• Portable: C code can be compiled and run on different platforms, including Windows,
macOS, Linux, and embedded systems.
• Low-level programming: C allows programmers to write code that interacts directly with
hardware and memory, making it ideal for developing system software and drivers.
• Fast and efficient: C is a fast and efficient programming language that can be used to
develop high-performance applications.
• Modular programming: C supports modular programming, allowing programmers to
divide code into smaller, more manageable functions and modules.
• Standard library: C comes with a standard library of functions that provide commonly
used functionality, such as input/output, string handling, and mathematical operations.
• Pointers: C allows programmers to work with pointers, which are memory addresses that
point to specific data in memory. Pointers are a powerful feature of C that allow for more
efficient memory management and manipulation.
• Preprocessor directives: C includes preprocessor directives, which are special statements
that are processed by the compiler before the code is compiled. Preprocessor directives are
used to define constants, include header files, and perform other tasks.
Overall, C is a powerful and versatile programming language that is widely used for
developing a variety of applications, including system software, embedded systems, and high-
performance applications. It is a well-liked choice among developers worldwide because of its
portability, effectiveness, and simplicity.
870
Here's an example of a "Hello, World!" program in C:
#include<stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
Explanation:
• #include<stdio.h> − This line includes the standard input and output library, which
• int main() − This line defines the main() function, which is the entry point of the
program.
• {} − The curly braces contain the code that will be executed when the program runs.
• printf("Hello, World!\n"); − This line uses the printf() function to display the
text "Hello, World!" to the console. The \n is a special character that represents a
• return 0; − This line returns a value of 0 from the main() function, indicating that
When you run this program, it will display the text "Hello, World!" on the console. This program
is often used as a simple test to make sure that a new programming environment is set up correctly.
871
In C programming language, comments are used to explain the code and make it more readable
for other developers. Comments are ignored by the compiler and do not affect the functionality
of the code. There are two types of comments in C: single-line comments and multi-line
comments.
Single-line comments start with two forward slashes (//) and continue until the end of
the line. For example:
Multi-line comments start with /* and end with */. Everything between these two symbols is
considered a comment. For example:
/*
This is a multi-line comment
It can span multiple lines
*/
int y = 10; /* This line initializes the variable y to 10 */
Comments are important for making the code more understandable and easier to maintain. They
can also be used to temporarily remove a section of code during testing or debugging. For
example:
// int z = someFunction(); // This line is temporarily commented out for testing purposes
int a = 10; // This line initializes the variable a to 10
In the above example, the line that calls the function someFunction() has been commented out
for testing purposes. This allows the developer to test the rest of the code without the potentially
872
problematic function call. Once the testing is complete, the comment can be removed and the
code will work as intended.
In the above examples, int, float, and char are data types in C. The variable x is declared
without an initial value, while y and z are declared with initial values. Variables can be assigned
new values using the assignment operator ( =). For example:
int a = 10;
int b = 5;
int c = a + b; // assigns the value 15 to the variable c
In the above example, the variables a and b are used in an expression to calculate the value of the
variable c. In C, variables have a scope, which defines the parts of the program where the
873
variable can be accessed. Variables declared inside a function have local scope, which means
they can only be accessed within that function. Variables declared outside of any function have
global scope, which means they can be accessed from any part of the program. To sum up,
variables in C are named memory locations that store values of specific data types. They can be
declared with or without initial values, assigned new values, and used in expressions.
Understanding variables is essential for writing C programs.
In C programming language, data types specify the type of data that can be stored in a variable.
The format specifiers are used to indicate the type of data being printed or scanned in
input/output operations. Here are the commonly used data types and format specifiers in C:
Data Types:
Format Specifiers:
874
%x: used to print or scan hexadecimal values
Here are some examples of using data types and format specifiers in C:
#include<stdio.h>
int main() {
int x = 10;
float y = 3.14;
char z = 'A';
scanf("%d", &x);
scanf("%f", &y);
scanf("%c", &z);
return 0;
}
In the above example, the int, float, and char data types are used to declare variables x, y, and
z. The %d, %f, and %c format specifiers are used to print or scan these variables. The scanf
function is used to scan input from the user, and the printf function is used to print output to
the screen. Understanding data types and format specifiers is essential for working with variables
and input or output operations in C.
875
In C programming language, a constant is a value that cannot be changed during program
execution. Constants are typically used to represent fixed values that are used in a program.
Constants can be of different data types, such as integer, floating-point, character, and boolean.
Here are some examples of defining constants in C:
In the above examples, #define, const, and enum are used to define constants in C. #define is
a preprocessor directive that defines a constant value that can be used throughout the program.
const is a keyword that defines a constant variable that cannot be modified. enum is a keyword
that defines a set of named integer constants. Here are some examples of using constants in C:
#include<stdio.h>
#define PI 3.14159
const int MAX = 100;
int main() {
float radius = 5.0;
float circumference = 2 * PI * radius;
int count = MAX;
return 0;
}
876
In the above example, the constant PI is used to calculate the circumference of a circle, and the
constant MAX is used to set the maximum count. By using constants instead of hard-coded values,
the program becomes more readable and easier to maintain. Constants in C are typically defined
at the beginning of a program or in a separate header file. By convention, constant names are
written in uppercase letters to distinguish them from variables. Overall, constants in C are values
that cannot be changed during program execution. They can be defined using #define, const,
or enum, and are typically used to represent fixed values in a program. Understanding constants
is essential for writing C programs that are readable and maintainable.
In this example, the string "Hello, World!" is stored in the array str. The null character '\0' is
automatically added to the end of the string to indicate its termination. Strings in C can be
manipulated using various string functions, such as strlen(), strcpy(), and strcat(). Here
are some examples of using string functions in C:
#include<stdio.h>
#include<string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char buffer[50];
877
// concatenate two strings
strcpy(buffer, str1);
strcat(buffer, " ");
strcat(buffer, str2);
printf("The concatenated string is %s\n", buffer);
In this example, the strlen() function is used to find the length of a string, the strcpy() and
strcat() functions are used to concatenate two strings, and the strcmp() function is used to
compare two strings. C also provides various ways to input and output strings. The scanf()
function is used to input strings from the standard input, while the printf() function is used to
output strings to the standard output. Here is an example of using scanf() and printf() to
input and output strings:
#include<stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
878
In this example, the scanf() function is used to input a string from the standard input and store
it in the array name, while the printf() function is used to output a greeting message that
includes the input string. To sum up, strings in C are represented as arrays of characters
terminated by a null character '\0'. String functions can be used to manipulate strings, and various
ways to input and output strings are available in C. Understanding strings is essential for writing
C programs that deal with text data.
In C programming, operators are symbols that represent actions or computations. They allow
you to perform mathematical or logical operations on one or more operands. Here are the most
commonly used operators in C:
1. Arithmetic Operators
Example:
int a = 5, b = 2, c;
c = a + b; // c is now 7
c = a - b; // c is now 3
c = a * b; // c is now 10
c = a / b; // c is now 2
c = a % b; // c is now 1
2. Assignment Operators
879
Assignment operators are used to assign values to variables. These include:
Assignment (=): Assigns the value of the right operand to the left
operand
Addition assignment (+=): Adds the value of the right operand to the
left operand and assigns the result to the left operand
Subtraction assignment (-=): Subtracts the value of the right operand
from the left operand and assigns the result to the left operand
Multiplication assignment (*=): Multiplies the left operand by the right
operand and assigns the result to the left operand
Division assignment (/=): Divides the left operand by the right operand
and assigns the result to the left operand
Modulus assignment (%=): Calculates the remainder of the left operand
divided by the right operand and assigns the result to the left operand
Example:
int a = 5, b = 2;
a += b; // a is now 7
a -= b; // a is now 5 again
a *= b; // a is now 10
a /= b; // a is now 5 again
a %= b; // a is now 1
3. Comparison Operators
Comparison operators are used to compare two values. They return a Boolean value (true
or false). These include:
880
Greater than or equal to (>=): Returns true if the first operand is
greater than or equal to the second operand
Less than or equal to (<=): Returns true if the first operand is less
than or equal to the second operand
Example:
int a = 5, b = 2;
if (a == b) {
printf("a is equal to b\n");
} else {
printf("a is not equal to b\n");
}
if (a > b) {
printf("a is greater than b\n");
}
if (a < b) {
printf("a is less than b\n");
}
4. Logical Operators
Logical operators are used to combine multiple conditions. They return a Boolean value
(true or false). These include:
Example:
int a = 5, b = 2;
if (a > 0 && b > 0) {
printf("Both a and b are positive\n");
}
881
In this example, the condition inside the if statement will be true only if both a and b are
greater than 0.
Example:
int a = 5, b = 2;
if (a > 0 || b > 0) {
printf("At least one of a and b is positive\n");
}
In this example, the condition inside the if statement will be true if either a or b is
greater than 0.
Example:
int a = 5, b = 2;
if (!(a > b)) {
printf("a is not greater than b\n");
}
In this example, the condition inside the if statement will be true only if a is not greater
than b. The NOT operator reverses the result of the comparison operator ( >), so if a is not
greater than b, the NOT operator will return true.
We can also combine multiple logical operators to form complex conditions. For
example:
int a = 5, b = 2, c = 7;
if (a > 0 && b > 0 || c > 0) {
printf("At least one of a and b is positive or c is positive\n");
}
882
In this example, the condition inside the if statement will be true if either a or b is
greater than 0, or if c is greater than 0. The AND operator has higher precedence than the
OR operator, so the condition inside the parentheses is evaluated first.
C language does not have a built-in Boolean data type. However, C99 introduced a new data
type called _Bool (or bool) which can be used to represent Boolean values. Additionally, the
header file stdbool.h provides a macro bool which can be used instead of _Bool. Here is an
example of using bool in C:
#include<stdbool.h>
#include<stdio.h>
int main() {
bool a = true;
bool b = false;
if (a && !b) {
printf("a is true and b is false\n");
}
return 0;
}
In this example, we have defined two Boolean variables a and b. The values of these variables
are assigned using the keywords true and false, which are defined in the stdbool.h header
file. We then use these variables in an if statement, where we use the "&&" (AND) operator and
the "!"(NOT) operator to create a Boolean expression.
883
a is true and b is false
Note that any nonzero value is considered to be true in C, while the value 0 is considered to be
false. Therefore, you can also use integers to represent Boolean values in C:
#include <stdio.h>
int main() {
int a = 1;
int b = 0;
if (a && !b) {
printf("a is true and b is false\n");
}
return 0;
}
In this example, we have defined two integer variables a and b. We then use these variables in an
if statement to create a Boolean expression. Since a is nonzero and b is 0, the expression
evaluates to true and the message is printed. However, this approach can be less clear and more
error-prone than using bool variables, especially in more complex programs.
"Any fool can write code that a computer can understand. Good
programmers write code that humans can understand."
― Martin Fowler
884
C program to add two numbers:
#include<stdio.h>
int main() {
return 0;
• First, we include the standard input and output library header file stdio.h.
• We prompt the user to enter two numbers to add using the printf function.
• We use the scanf function to read in the two numbers entered by the user and store them
in the variables num1 and num2.
• We add the two numbers together and store the result in the variable sum.
• Finally, we use the printf function again to print out the sum of the two numbers.
When the program runs, it will prompt the user to enter two numbers to add. After the user enters
the numbers, the program will add them together and display the result.
885
C program to check whether a number is even or odd:
#include<stdio.h>
int main() {
int num;
printf("Enter an integer:\n");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is even\n", num);
} else {
printf("%d is odd\n", num);
}
return 0;
}
• First, we include the standard input and output library header file stdio.h.
• We use the scanf function to read in the integer entered by the user and store it in the
variable num.
• We use an if-else statement to check if num is even or odd. The % operator is used to find
the remainder of num divided by 2. If the remainder is 0, then num is even, and the
program will print out a message saying so. If the remainder is not 0, then num is odd, and
886
When the program runs, it will prompt the user to enter an integer. After the user enters the integer,
the program will check if it's even or odd and display a message accordingly.
#include<stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("Hello World\n");
}
return 0;
}
• First, we include the standard input and output library header file stdio.h.
• We use a for loop to print "Hello World" ten times. The loop runs from i = 0 to i <
10, incrementing i by 1 each time the loop runs. Inside the loop, we use the printf
When the program runs, it will print "Hello World" ten times to the screen. The for loop allows
us to repeat the printing of "Hello World" multiple times without having to write out the same
printf statement multiple times.
887
#include<stdio.h>
int main() {
int i = 0;
while (i < 10) {
printf("Hello World\n");
i++;
}
return 0;
}
• First, we include the standard input and output library header file stdio.h.
• We use a while loop to print "Hello World" ten times. The loop runs as long as i is less
than 10. Inside the loop, we use the printf function to print "Hello World" to the screen
When the program runs, it will print "Hello World" ten times to the screen using the while
loop. The while loop is another way to repeat a set of statements multiple times, as long as
the condition specified in the loop header is true. In this case, the loop runs as long as i is
less than 10, allowing us to print "Hello World" ten times without having to write out the
same printf statement multiple times.
888
#include<stdio.h>
int main() {
int i = 0;
do {
printf("Hello World\n");
i++;
} while (i < 10);
return 0;
}
• First, we include the standard input and output library header file stdio.h.
• We use a do-while loop to print "Hello World" ten times. The loop runs at least once,
even if the condition in the loop header is false. Inside the loop, we use the printf
• The loop condition is checked at the end of each iteration of the loop. If the condition is
true, the loop continues to run, and if the condition is false, the loop exits.
When the program runs, it will print "Hello World" ten times to the screen using the do-while
loop. The do-while loop is another way to repeat a set of statements multiple times, but it
guarantees that the loop body will be executed at least once, even if the loop condition is false. In
this case, the loop runs as long as i is less than 10, allowing us to print "Hello World" ten times
without having to write out the same printf statement multiple times.
889
In C programming language, switch statement is used to execute a block of code depending
on the value of an expression. The switch statement works by evaluating the expression and
then executing the code associated with the matching case label. If no case label matches the
value of the expression, then the default code block is executed.
#include<stdio.h>
int main() {
char operator;
int operand1, operand2, result;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%d %d", &operand1, &operand2);
switch(operator) {
case '+':
result = operand1 + operand2;
printf("%d + %d = %d\n", operand1, operand2, result);
break;
case '-':
result = operand1 - operand2;
printf("%d - %d = %d\n", operand1, operand2, result);
break;
case '*':
result = operand1 * operand2;
printf("%d * %d = %d\n", operand1, operand2, result);
break;
case '/':
if(operand2 == 0) {
printf("Error: Cannot divide by zero\n");
890
} else {
result = operand1 / operand2;
printf("%d / %d = %d\n", operand1, operand2, result);
}
break;
default:
printf("Error: Invalid operator\n");
break;
}
return 0;
}
In this example, the program asks the user to enter an operator (+, -, *, /) and two operands.
The program then uses a switch statement to perform the appropriate arithmetic operation based
on the operator entered by the user. If an invalid operator is entered, the program displays an
error message. The switch statement begins with the expression operator which is evaluated to
determine which case label matches. The case labels +, -, *, and / are associated with the
appropriate arithmetic operations. The default label is used to handle any case where the
expression does not match any of the other case labels. Each case label contains a block of code
that is executed when the expression matches that label. The break statement is used to exit the
switch statement after the matching case label is executed. In this example, if the user enters
the operator +, the block of code associated with the case '+' label is executed. This block of code
adds the two operands and displays the result. Similarly, the other arithmetic operations are
handled by their respective case labels. If an invalid operator is entered, the default label is
executed, displaying an error message. Overall, the switch statement provides a convenient way
to perform different actions based on the value of a single expression, making it a useful
construct in many C programs.
891
In C programming language, break and continue are two control flow statements that are
used to modify the execution of loops (such as for, while, and do-while loops) and switch
statements. break statement is used to terminate the execution of the loop or switch statement
immediately. When a break statement is encountered, the control is transferred to the next
statement after the loop or switch statement. Here is an example:
#include<stdio.h>
int main() {
int i;
for(i = 1; i <= 10; i++) {
if(i == 5) {
break;
}
printf("%d\n", i);
}
return 0;
}
In this example, the program uses a for loop to print the values of i from 1 to 10. However,
when i equals 5, the break statement is executed, and the loop is terminated immediately.
Therefore, the program only prints the values of i from 1 to 4, and the loop does not complete.
On the other hand, the continue statement is used to skip the current iteration of the loop and
move to the next iteration. When a continue statement is encountered, the control is transferred
to the next iteration of the loop. Here is an example:
#include <stdio.h>
int main() {
int i;
892
}
printf("%d\n", i);
}
return 0;
}
In this example, the program uses a for loop to print the values of i from 1 to 10. However,
when i equals 5, the continue statement is executed, and the current iteration of the loop is
skipped. Therefore, the program does not print the value 5, but continues with the next iterations
and prints the other values. Both break and continue statements are useful for controlling the
flow of execution in loops and switch statements, allowing programs to skip certain iterations or
terminate the loop altogether based on certain conditions.
In C programming language, an array is a collection of elements of the same data type, stored
in contiguous memory locations. Arrays are a powerful and efficient way to store and manipulate
large amounts of data in C programs. Here is an example of how to use arrays in C:
#include<stdio.h>
int main() {
int numbers[5]; // declare an array of 5 integers
int i;
893
// print the array elements
for(i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
In this example, an array named numbers is declared, which can store up to 5 integers. The
elements of the array are accessed using an index, starting from 0. In this case, the elements of
the array are initialized with the values 1, 3, 5, 7, and 9. To access an element of the array, we
can use its index as shown in the for loop. In this loop, we print the array elements using the
printf statement, with the %d format specifier indicating that we are printing an integer.
Another way to initialize an array is to use an initializer list, which allows you to specify the
values of the array elements at the time of declaration. Here is an example:
#include<stdio.h>
int main() {
int numbers[] = {1, 3, 5, 7, 9}; // declare and initialize an array
int i;
In this example, the array numbers is declared and initialized using an initializer list. The size of
the array is automatically determined by the number of elements in the list. The output of this
program is the same as the previous example. Arrays are a fundamental data structure in C, and
894
their simplicity and efficiency make them a popular choice for many programming tasks. They
are widely used in applications such as sorting, searching, and data processing, among others.
#include<stdio.h>
int main() {
// declare a structure variable of type "student"
struct student s1;
// assign values to the structure members
strcpy(s1.name, "John");
s1.roll_no = 1;
s1.marks = 85.5;
// print the structure members
printf("Name: %s\n", s1.name);
printf("Roll No.: %d\n", s1.roll_no);
printf("Marks: %f\n", s1.marks);
return 0;
}
895
In this example, a structure named "student" is defined using the struct keyword. The structure
has three members: a character array name, an integer roll_no, and a float marks. The main
function declares a structure variable s1 of type student and assigns values to its members
using the " . " operator. The printf statements then print the values of the structure members.
Another way to declare and initialize a structure variable is to use an initializer list, which allows
you to specify the values of the structure members at the time of declaration. Here is an example:
#include<stdio.h>
struct book {
char title[50];
char author[50];
float price;
};
int main() {
return 0;
}
896
In this example, a structure named "book" is defined with three members: a character array
title, a character array author, and a float price. The main function declares and initializes a
structure variable b1 of type book using an initializer list. The printf statements then print the
values of the structure members. Structures are a powerful feature of C programming language
that allows programmers to create custom data types that can be used to represent complex data
structures. They are widely used in applications such as database management, file handling, and
graphics programming, among others.
In C programming language, a pointer is a variable that stores the memory address of another
variable. Pointers allow you to manipulate data directly in memory, which can be useful for tasks
such as dynamically allocating memory or working with complex data structures. Here's an
example of how pointers work:
#include<stdio.h>
int main() {
int var = 10; /* actual variable declaration */
int *p; /* pointer variable declaration */
return 0;
}
897
In this example, we declare an integer variable var and a pointer variable p. We then store the
address of var in p using the & operator. We can then access the value of var using the *
operator on the pointer variable p. When we run this program, it will output the following:
Here, the %p format specifier is used to print the memory addresses. The addresses of var and p
are the same, as expected, since p points to var. Pointer arithmetic is another important aspect of
pointers in C. You can perform arithmetic operations on pointers such as addition, subtraction,
and comparison. Here's an example:
#include<stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
for(int i=0; i<5; i++) {
printf("Value of arr[%d]: %d\n", i, *(p+i));
}
return 0;
}
In this example, we declare an integer array arr and a pointer variable p initialized to the first
element of the array. We then use pointer arithmetic to iterate through the array and print out the
values. When we run this program, it will output the following:
Value of arr[0]: 10
Value of arr[1]: 20
Value of arr[2]: 30
Value of arr[3]: 40
Value of arr[4]: 50
898
Here, the *(p+i) expression is used to access the i-th element of the array through pointer
arithmetic. The *(p+i) is equivalent to p[i] and both are valid expressions to access the
elements of the array.
#include<stdio.h>
/* function declaration */
int max(int num1, int num2);
int main() {
int a = 100;
int b = 200;
int ret;
return 0;
}
899
In this example, we declare a function named max that takes two integer arguments and returns
the maximum value. The function is declared before the main function using a function
prototype or declaration, which specifies the function's name, return type, and parameter types.
This allows the compiler to check for errors and ensure that the function is used correctly. In the
main function, we declare two integer variables a and b and assign them the values 100 and 200,
respectively. We then call the max function and pass it a and b as arguments, storing the result in
the ret variable. Finally, we print out the maximum value using printf. When we run this
program, it will output the following:
Functions can also have multiple return statements, which allows for early termination of the
function based on certain conditions. Here's an example:
#include<stdio.h>
/* function declaration */
int find_factorial(int num);
int main() {
int num, factorial;
factorial = find_factorial(num);
if (factorial != -1) {
900
} else {
printf("Error: Factorial of negative numbers doesn't exist\n");
}
return 0;
}
if (num < 0) {
return -1;
}
In this example, we declare a function named find_factorial that takes a single integer
argument and returns the factorial of the number. The function checks for negative input and
returns -1 if the input is negative. Otherwise, it calculates the factorial using a for loop and
returns the result. In the main function, we prompt the user to enter a positive integer and store it
in the num variable. We then call the find_factorial function and store the result in the
factorial variable. If the result is not -1, we print out the factorial. Otherwise, we print an
error message. When we run this program, it will output the following:
901
Functions can also have default arguments and variable-length arguments, but these are more
advanced features beyond the scope of this explanation.
In C programming language, an enum (short for enumeration) is a user-defined data type that
consists of a set of named integer constants. Enums provide a way to define a set of related
constants with meaningful names, which makes code more readable and easier to maintain.
Here's an example of how enums work:
#include<stdio.h>
int main() {
return 0;
}
902
In this example, we define an enum named week that consists of seven named constants
representing the days of the week. By default, the constants are assigned integer values starting
from 0 for the first constant, 1 for the second constant, and so on. We then declare two variables
of type enum week named today and tomorrow, and assign them the values Wednesday and
Thursday, respectively. Finally, we print out the values using printf. When we run this
program, it will output the following:
Today is 3
Tomorrow is 4
Enums can also have explicit values assigned to their constants, which allows for more control
over the values. Here's an example:
#include<stdio.h>
int main() {
903
printf("c2 = %d\n", c2);
printf("c3 = %d\n", c3);
return 0;
}
In this example, we define an enum named color that consists of three named constants
representing colors. We assign explicit values to the constants using the assignment operator, so
that Red is assigned the value 1, Green is assigned the value 2, and Blue is assigned the value 4.
We then declare three variables of type enum color named c1, c2, and c3, and assign them the
values Red, Green, and Blue, respectively. Finally, we print out the values using printf. When
we run this program, it will output the following:
c1 = 1
c2 = 2
c3 = 4
Enums can also be used as switch case statements, allowing for easy handling of related
constants. Here's an example:
#include<stdio.h>
int main() {
/* declare a variable of type enum week */
enum week day;
904
/* use a switch statement to handle the input */
switch (day) {
case Sunday:
printf("Sunday\n");
break;
case Monday:
printf("Monday\n");
break;
case Tuesday:
printf("Tuesday\n");
break;
case Wednesday:
printf("Wednesday\n");
break;
case Thursday:
printf("Thursday\n");
break;
case Friday:
printf("Friday\n");
break;
case Saturday:
printf("Saturday\n");
break;
}
return 0;
}
905
To use files in C, you need to include the stdio.h header file. This file contains functions for
input and output, including functions for reading and writing files. Here's an example of how to
open a file for writing:
#include<stdio.h>
int main() {
return 0;
}
In this example, we declare a file pointer named fptr, which is a variable that holds a reference
to a file. We then open a file named example.txt for writing using the fopen function, which
takes two arguments: the name of the file, and the mode in which to open the file. In this case,
we're using the mode "w", which means "write mode". If the file doesn't exist, it will be created.
Once the file is open, we use the fprintf function to write some text to the file. This function
works like printf, but instead of printing to the console, it writes to the file. Finally, we close
the file using the fclose function. Here's an example of how to read from a file:
906
#include<stdio.h>
int main() {
return 0;
}
In this example, we open the same file we created earlier, but this time in read mode ("r"). We
declare a character array named buffer to hold the text we read from the file. We then use the
fgets function to read up to 100 characters from the file into the buffer. Finally, we print out the
text using printf.
It's important to note that when you open a file in write mode, any existing data in the file will be
overwritten. If you want to append data to the end of the file instead, you can use the mode "a"
(append mode) instead of "w". Here's an example:
907
#include <stdio.h>
int main() {
/* declare a file pointer */
FILE *fptr;
return 0;
}
In this example, we open the same file we created earlier, but this time in append mode ("a").
This means that any data we write to the file will be added to the end of the file, rather than
overwriting existing data. We use the fprintf function again to write some additional text to the
file, and then close the file using the fclose function.
908
C programming is a popular and widely used programming language with many advantages.
Here are some of the key advantages of C programming:
• Speed and efficiency: C is a high-performance language that is known for its speed and
efficiency. It is commonly used to develop software that requires fast execution and low-
level memory manipulation, such as operating systems, device drivers, and embedded
systems.
• Portability: C programs can be compiled and run on different platforms, including
Windows, macOS, Linux, and embedded systems, making it a portable language. This
means that code written in C can be easily transferred to other systems without significant
modifications.
• Low-level programming: C allows programmers to write code that interacts directly
with hardware and memory, making it ideal for developing system software and drivers.
• Memory management: C provides a level of control over memory management that is
not available in many other programming languages. This allows programmers to allocate
and deallocate memory manually, resulting in more efficient and optimized code.
• Extensive standard library: C comes with an extensive standard library that provides
many useful functions, such as input/output, string handling, and mathematical
operations.
• Flexibility: C is a flexible language that can be used to develop a wide range of
applications, from low-level system software to high-level applications.
• Reusability: C supports modular programming, which allows code to be divided into
smaller, more manageable functions and modules. As a result, code is easier to maintain
and more reusable.
• Widely used: C is a popular language that is widely used in industry, making it a
valuable skill for programmers to have. Many operating systems, embedded systems, and
applications are written in C.
Overall, C programming is a powerful and versatile language that is well-suited for developing
a wide range of applications. Its speed, efficiency, portability, and low-level programming
capabilities make it a popular choice for developers around the world. Using C has certain
909
drawbacks in addition to its many benefits. The following are some of the primary drawbacks of
C:
• Low-level language: C is a low-level language, which means that it requires a lot of code to
perform simple tasks. For example, in C, you need to write a lot of code to read and write files,
whereas in higher-level languages like Python, it can be done in just a few lines.
• No automatic garbage collection: C does not have automatic garbage collection, which means
that you have to manage memory allocation and deallocation yourself. This can be very tedious
and error-prone, especially when dealing with complex data structures.
• No built-in support for object-oriented programming: Unlike some other programming
languages, C does not have built-in support for object-oriented programming. This means that if
you want to use OOP concepts in your C code, you have to implement them yourself, which can
be a time-consuming process.
• Vulnerability to buffer overflow attacks: C is vulnerable to buffer overflow attacks, which
occur when a program tries to store too much data in a buffer, causing the excess data to
overwrite adjacent memory locations. This can lead to the program crashing or, in some cases,
being exploited by attackers.
• Lack of dynamic memory management: C does not have dynamic memory management built
into the language, which means that you have to manually allocate and deallocate memory. This
can lead to memory leaks if you forget to deallocate memory, which can cause your program to
consume more and more memory until it crashes.
Example:
Here's an example of a program written in C that illustrates some of these disadvantages:
#include<stdio.h>
int main() {
char buffer[100];
scanf("%s", buffer);
return 0;
910
In this program, the user is prompted to enter a string, which is then stored in a buffer.
However, the program does not perform any input validation, which means that if the
user enters a string that is longer than 100 characters, it will overflow the buffer and
potentially overwrite adjacent memory locations, leading to undefined behavior or a
crash. Additionally, the program does not perform any memory management, which
means that the buffer will remain in memory even after it is no longer needed, potentially
causing a memory leak. Finally, the program does not use any object-oriented
programming concepts, making it harder to maintain and extend as it grows in
complexity.
• No built-in support for exception handling: C does not have built-in support for
exception handling, which means that error handling must be done manually using
conditional statements and error codes. This could make code more challenging to read
and maintain.
• Lack of standardization: The C language has no official standard library, which means
that different implementations of C may have different libraries and functions. This can
lead to portability issues when trying to run code on different platforms or compilers.
• Lack of type safety: C is a weakly-typed language, which means that it does not enforce
strict type checking. This can lead to errors and bugs when working with complex data
structures or when trying to perform operations on incompatible data types.
• Difficulty in debugging: Debugging C code can be difficult due to its low-level nature
and lack of built-in debugging tools. This can make it hard to find and fix bugs in
complex code.
• Potential for security vulnerabilities: Because of its low-level nature and lack of built-
in security features, C code can be vulnerable to security attacks such as buffer
overflows, which can lead to serious security issues.
Example:
911
#include<stdio.h>
int main() {
int num;
scanf("%d", &num);
if (num % 2 == 0) {
else {
return 0;
In this program, the user is prompted to enter a number, which is then checked to see if
it's even or odd. However, the program does not perform any input validation, which
means that if the user enters a non-numeric value, it will cause an error. Additionally, the
program does not handle any exceptions, which means that if an error occurs, it will
simply crash. Finally, the program uses a conditional statement to check if the number is
even or odd, which can be harder to read and maintain as the code grows in complexity.
C language is a widely used programming language that has numerous practical applications.
Here are some examples of its practical applications:
912
• Embedded Systems: C is popularly used to write code for embedded systems, such as
microcontrollers and other electronic devices, where the code must be fast, efficient, and
lightweight.
• Database Systems: C is often used in the development of database management systems
(DBMS) like MySQL and PostgreSQL, which are widely used in web and mobile
applications.
• Compilers and Interpreters: C is used to create compilers and interpreters for other
programming languages, which are essential tools for software development.
• Graphics Applications: C is often used in the development of graphics applications such
as video games, 3D modeling, and animation software.
• Web Applications: C is often used in the backend of web applications, where it's used to
handle the heavy processing of data and requests, such as parsing and manipulating XML
and JSON data.
• Scientific and Engineering Applications: C is popularly used in scientific and
engineering applications, where high-performance computing is required to handle large
amounts of data.
• Business Applications: C is also used in business applications, such as accounting
software, inventory management software, and customer relationship management
(CRM) systems.
• Artificial Intelligence and Machine Learning: C is used in the development of artificial
intelligence and machine learning algorithms, where its speed and low-level control make
it ideal for high-performance computing tasks.
• C is often referred to as the "Dennis Ritchie Language" after its creator. In the early
days of computing, programmers had to write in machine language, which was incredibly
difficult and time-consuming. C was created to make programming easier, but ironically,
it ended up becoming one of the most complex programming languages of all time!
913
• C programming can be quite cryptic and hard to read, especially for beginners. Some
programmers have joked that C stands for "Confusing" or "Cryptic"!
• One of the most famous quotes about C programming is from Brian Kernighan, one of
the co-authors of "The C Programming Language": "Debugging is twice as hard as
writing the code in the first place. Therefore, if you write the code as cleverly as
possible, you are, by definition, not smart enough to debug it."
• C programming can be a bit of a headache because of its use of pointers. Pointers are
variables that store the memory address of another variable, and they can be quite tricky
to use correctly.
• Despite its reputation for being difficult, C programming can also be quite fun and
rewarding. There's a certain satisfaction that comes with writing code that works
perfectly and efficiently, and C programming can provide that feeling in spades.
Overall, C programming can be both frustrating and entertaining at the same time. Despite its
challenges, it remains one of the most widely used programming languages in the world, and
mastering it can be a rewarding experience for anyone who is willing to put in the time and
effort.
914
C++ − OVERVIEW
915
Templates: C++ supports templates, which allow developers to write generic
code that can work with different data types.
Multi-paradigm support: C++ supports multiple programming paradigms,
including procedural, functional, and generic programming. This allows
developers to write code in a style that suits their needs.
Low-level programming: C++ allows low-level programming, which means
developers can write code that interacts directly with hardware, such as device
drivers and operating systems.
Overall, C++ is a powerful and versatile language that can be used for a wide range of
programming tasks. Its flexibility, performance, and support for multiple programming
paradigms make it a popular choice for developers working on complex and demanding
projects.
#include<iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This program simply prints the string "Hello, World!" to the console.
#include<iostream>: This line includes the iostream header file, which provides
input and output streams like cin and cout.
int main() {: This line declares the main function, which is the entry point of the
program. int is the return type of the function, which indicates that it will return an
integer value. The empty parentheses indicate that the function takes no arguments.
916
std::cout << "Hello, World!" << std::endl;: This line prints the string "Hello,
World!" to the console. std::cout is a standard output stream object, and the <<
operator is used to insert the string into the stream. std::endl is a special character that
adds a new line to the output.
return 0;: This line indicates that the program has finished executing and returns the
value 0 to the operating system. A return value of 0 typically indicates success.
The std:: prefix before cout and endl is used to specify that these names are part of the std
namespace, which is the standard namespace for C++ library functions and objects. Overall, this
program demonstrates the basic syntax and structure of a C++ program. By using the iostream
library, it shows how to perform basic input or output operations, and by defining the main
function, it specifies the entry point of the program.
In C++, comments are used to add explanatory text to a program that is ignored by the compiler.
There are two types of comments in C++: single-line comments and multi-line comments.
Single-line comments start with // and continue until the end of the line. Here's an
example:
int main() {
// This is also a single-line comment
return 0;
}
In this example, the text after // is ignored by the compiler. Single-line comments are often used
to explain individual lines of code or to temporarily disable code during development.
Multi-line comments start with /* and end with */. Here's an example:
917
/*
This is a multi-line comment
that can span multiple lines
*/
int main() {
/*
This is also a multi-line comment
that can span multiple lines
*/
return 0;
}
In this example, the text between /* and */ is ignored by the compiler. Multi-line comments are
often used to explain larger blocks of code or to temporarily disable large sections of code. It's
important to note that comments should be used sparingly and only when necessary. Overuse of
comments can make code harder to read and maintain, and can also become outdated or
misleading if the code changes. However, when used appropriately, comments can be a useful
tool for improving the clarity and understandability of a program.
Data that can be used and modified across a program is stored in variables in C++. A variable is
defined by stating its data type, name, and, if applicable, initial value. The following are some
C++ examples of variable declarations:
int age = 30; // integer variable named "age" with initial value of 30
float pi = 3.14159; // floating-point variable named "pi" with initial value of 3.14159
double salary = 50000.0; // double-precision floating-point variable named "salary" with initial value of 50000.0
char grade = 'A'; // character variable named "grade" with initial value of 'A'
bool isStudent = true; // boolean variable named "isStudent" with initial value of true
918
In these examples, we declare variables with different data types including int, float, double,
char, and bool. We also assign an initial value to each variable using the assignment operator =.
Variables can be modified by assigning a new value to them, as shown in this example:
int count = 0; // declare an integer variable named "count" with initial value of 0
count = count + 1; // increment the value of "count" by 1
In this example, we increment the value of the count variable by 1 using the + operator and
assignment operator =. It's important to note that variables have a scope, which determines where
they can be accessed in a program. A variable declared inside a function, for example, can only
be accessed within that function. A variable declared outside of any function, on the other hand,
can be accessed throughout the entire program.
#include<iostream>
int main() {
int local_var = 20; // Local variable
std::cout << "Global variable value: " << global_var << std::endl;
std::cout << "Local variable value: " << local_var << std::endl;
return 0;
}
In this example, we declare a global variable named global_var outside of any function, and a
local variable named local_var inside the main function. We can access both variables within
the main function, but only the global variable can be accessed outside of the function. Overall,
919
variables are an essential part of C++ programming and are used to store and manipulate data
throughout a program.
In C++, data types specify the type of data that can be stored in a variable. C++ supports a wide
range of data types, including:
1. Integers: used to store whole numbers. There are several integer data types in C++,
including int, short, long, and long long. Example:
2. Floating-point numbers: used to store numbers with decimal points. There are two
floating-point data types in C++, float and double. Example:
float pi = 3.14159;
double salary = 50000.0;
3. Characters: used to store single characters. Character data types are denoted by the char
keyword. Example:
4. Boolean: used to store true or false values. Boolean data types are denoted by the
bool keyword. Example:
920
5. Arrays: used to store a collection of data of the same data type. Example:
It's important to note that data types have different ranges and precision, and choosing the
appropriate data type for a variable is important for performance and accuracy. For example,
using a short data type instead of an int data type for large numbers can cause overflow or
truncation of the value. C++ also provides type modifiers, such as signed and unsigned, to
further specify the range of a data type. For example, unsigned int can only store non-negative
integers. Overall, understanding data types in C++ is important for writing efficient and accurate
code.
C++ operators are special symbols and keywords used to perform various operations on
variables and values. Here are some common C++ operators with examples:
1. Arithmetic Operators:
Addition (+): int sum = 5 + 3; (sum equals 8)
Subtraction (-): int difference = 5 - 3; (difference equals 2)
Multiplication (*): int product = 5 * 3; (product equals 15)
Division (/): float quotient = 5.0 / 3.0; (quotient equals 1.66667)
Modulo (%): int remainder = 5 % 3; (remainder equals 2)
2. Assignment Operators:
Simple Assignment (=): int a = 5; (a equals 5)
Compound Assignment (+=, -=, *=, /=, %=): a += 3; (a equals 8)
3. Comparison Operators:
Equal to (==): bool isEqual = 5 == 3; (isEqual equals false)
921
Not equal to (!=): bool isNotEqual = 5 != 3; (isNotEqual equals true)
Greater than (>): bool isGreater = 5 > 3; (isGreater equals true)
Less than (<): bool isLess = 5 < 3; (isLess equals false)
Greater than or equal to (>=): bool isGreaterOrEqual = 5 >= 3;
(isGreaterOrEqual equals true)
Less than or equal to (<=): bool isLessOrEqual = 5 <= 3; (isLessOrEqual
equals false)
4. Logical Operators:
Logical AND (&&): bool isTrue = (5 > 3) && (4 < 6); (isTrue equals true)
Logical OR (||): bool isFalse = (5 < 3) || (4 > 6); (isFalse equals
false)
Logical NOT (!): bool isNotTrue = !(5 > 3); (isNotTrue equals false)
5. Bitwise Operators:
Bitwise AND (&): int result = 5 & 3; (result equals 1)
Bitwise OR (|): int result = 5 | 3; (result equals 7)
Bitwise XOR (^): int result = 5 ^ 3; (result equals 6)
Bitwise NOT (~): int result = ~5; (result equals -6)
Left shift (<<): int result = 5 << 1; (result equals 10)
Right shift (>>): int result = 5 >> 1; (result equals 2)
In C++, a string is a sequence of characters stored in a contiguous block of memory. The string
data type is defined in the <string> header file. Here are some examples of working with C++
strings:
1. Creating a string:
#include<string>
using namespace std;
922
2. Accessing and modifying characters in a string:
3. Concatenating strings:
4. Finding substrings:
string sentence = "The quick brown fox jumps over the lazy dog.";
int position = sentence.find("fox"); // finding the first occurrence of "fox"
string word = sentence.substr(16, 5); // extracting the word "brown" starting from position 16
7. Comparing strings:
923
string s1 = "hello";
string s2 = "world";
if (s1 == s2) {
// strings are equal
} else {
// strings are not equal
}
In C++, the math library provides a set of functions for performing mathematical operations.
Here are some examples of working with C++ math functions:
1. Absolute value:
#include<cmath>
using namespace std;
2. Square root:
double x = 16.0;
double sqrt_x = sqrt(x); // taking the square root of a number
3. Trigonometric functions:
924
4. Exponential function:
double x = 2.0;
double exp_x = exp(x); // taking the exponential function of a number
5. Logarithmic functions:
double x = 10.0;
double log_x = log(x); // taking the natural logarithm of a number
double log10_x = log10(x); // taking the base 10 logarithm of a number
6. Power function:
7. Rounding functions:
double x = 3.7;
double rounded_down = floor(x); // rounding down to the nearest integer
double rounded_up = ceil(x); // rounding up to the nearest integer
double rounded_nearest = round(x); // rounding to the nearest integer
Note that the math library also provides many more functions than what is covered here, such
as hyperbolic functions, inverse trigonometric functions, and more. You can include the <cmath>
header file to use these functions in your C++ programs.
925
In C++, a boolean is a data type that represents either true or false. Here are some examples of
working with C++ booleans:
1. Creating a boolean:
#include<iostream>
using namespace std;
2. Comparing values:
3. Logical operators:
bool a = true;
bool b = false;
bool and_result = a && b; // logical AND
bool or_result = a || b; // logical OR
bool not_result = !a; // logical NOT
926
5. Boolean expressions in loops:
Note that boolean values are commonly used in conditional statements, loops, and other control
structures in C++. In addition, C++ provides the keywords true and false to represent boolean
values, and the <stdbool.h> header file can be included for compatibility with C.
In C++, the if...else statement allows you to execute different code based on whether a
condition is true or false. Here are some examples of working with if...else statements in
C++:
1. Basic if statement:
int x = 10;
if (x > 5) {
cout << "x is greater than 5" << endl;
}
int x = 10;
2. if...else statement: if (x > 5) {
cout << "x is greater than 5" << endl;
} else {
cout << "x is less than or equal to 5" << endl;
}
927
3. Nested if...else statements:
int x = 10;
if (x > 5) {
if (x < 15) {
cout << "x is between 5 and 15" << endl;
} else {
cout << "x is greater than or equal to 15" << endl;
}
} else {
cout << "x is less than or equal to 5" << endl;
}
int x = 10;
if (x < 5) {
cout << "x is less than 5" << endl;
} else if (x < 10) {
cout << "x is between 5 and 10" << endl;
} else {
cout << "x is greater than or equal to 10" << endl;
}
5. Ternary operator:
int x = 10;
int result = (x > 5) ? 1 : 0; // if x > 5, set result to 1, otherwise set it to 0
Note that the if...else statement is a fundamental control structure in C++, and can be used to
control the flow of your program based on specific conditions. By combining if...else
928
statements with logical operators and comparison operators, you can create complex control
structures that can handle a wide variety of conditions.
In C++, the switch statement allows you to execute different code based on the value of a
variable. Here is the basic syntax of a switch statement:
switch(variable){
case value1:
// code to execute when variable == value1
break;
case value2:
// code to execute when variable == value2
break;
// additional cases can be added
default:
// code to execute when variable does not match any of the cases
break;
}
#include<iostream>
using namespace std;
int main() {
int day = 3;
switch(day) {
case 1:
cout << "Monday";
break;
929
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Invalid day";
break;
}
return 0;
}
Output:
Wednesday
930
#include<iostream>
using namespace std;
int main() {
int a = 10, b = 5;
char op = '-';
int result;
switch(op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
cout << "Invalid operator";
return 1;
}
cout << "Result: " << result;
return 0;
}
Output:
Result: 5
931
Example 3: Checking the type of a variable
#include<iostream>
#include<typeinfo>
using namespace std;
int main() {
auto x = 1.5;
switch(typeid(x).hash_code()) {
case typeid(int).hash_code():
cout << "x is an integer";
break;
case typeid(float).hash_code():
cout << "x is a float";
break;
case typeid(double).hash_code():
cout << "x is a double";
break;
default:
cout << "x has an unknown type";
break;
}
return 0;
}
Output:
x is a double
932
Loops in C++ allow you to execute a block of code repeatedly based on a certain condition.
There are three types of loops in C++:
The for loop is used when you know exactly how many times you want to execute the
loop. It has three parts: initialization, condition, and increment or decrement.
Syntax:
Example:
#include<iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
return 0;
}
Output:
933
0
Explanation:
In this example, the loop will execute five times because the condition is set to run while i is less
than 5. The i variable is initialized to 0 and incremented by 1 at the end of each loop iteration.
The while loop is used when you don't know exactly how many times you want to
execute the loop. It will continue to run until the condition becomes false.
Syntax:
while (condition) {
// code to be executed repeatedly
}
Example:
#include<iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
return 0;
}
934
Output:
0
1
2
3
4
Explanation:
This example achieves the same result as the for loop example above. The loop will continue to
execute as long as the i variable is less than 5.
The do-while loop is similar to the while loop, but the condition is checked at the end of
the loop iteration instead of the beginning. This means that the loop will always execute
at least once.
Syntax:
do {
// code to be executed repeatedly
} while (condition);
#include<iostream>
Example:
using namespace std;
int main() {
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
return 0;
}
935
Output:
Explanation:
This example also achieves the same result as the previous two examples. The loop will execute
at least once because the condition is checked at the end of the first iteration.
In C++, an array is a collection of elements of the same data type that are stored in contiguous
memory locations. Each element in the array is accessed using an index, which represents the
position of the element in the array. Arrays can be useful for storing and manipulating large
amounts of data.
dataType arrayName[arraySize];
Here, dataType is the data type of the elements you want to store, arrayName is the name of the
array, and arraySize is the number of elements in the array.
Example:
int arr[5];
936
Initialization of an array can be done using braces {}. The values are separated by commas and
the number of values must match the number of elements in the array.
Example:
This initializes an array of integers with 5 elements, where the first element is 1, the second
element is 2, and so on.
Accessing elements of an array can be done using indices, starting from 0 for the first element.
Example:
In C++, arrays are fixed in size, which means that the number of elements in the array cannot be
changed after the array is declared. To change the value of an element in the array, simply assign
a new value to the element using the index.
Example:
In addition to one-dimensional arrays, C++ also supports multidimensional arrays, such as two-
dimensional arrays, three-dimensional arrays, and so on. A two-dimensional array can be thought
of as a table, with rows and columns of elements.
937
Example of a two-dimensional array:
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
To sum up, arrays are a fundamental data structure in C++, and can be useful for storing and
manipulating large amounts of data in a structured manner.
In C++, a reference is an alias for a variable, which allows you to refer to the original variable
using a different name. References can be useful for passing arguments to functions, as they
avoid the overhead of making a copy of the argument.
Here, dataType is the data type of the variable being referred to, refName is the name of the
reference, and variableName is the name of the variable being referred to.
Example:
Assigning a value to a reference changes the value of the original variable being referred to.
Example:
938
numRef = 20;
cout << num; // Outputs 20
This assigns the value 20 to the reference numRef, which changes the value of the original
variable num to 20.
References can be useful for passing arguments to functions by reference, which allows the
function to modify the original value of the argument.
Example:
int main() {
int num = 10;
doubleValue(num);
cout << num; // Outputs 20
return 0;
}
This declares a function named doubleValue, which takes an integer reference as an argument
and doubles the value of the argument. The function is then called in the main function with the
integer variable num as the argument.
Overall, references in C++ are aliases for variables, which can be useful for passing
arguments to functions and modifying the original value of the argument.
939
In C++, a pointer is a variable that stores the memory address of another variable. Pointers
can be useful for manipulating memory directly and for implementing complex data structures.
dataType* pointerName;
Here, dataType is the data type of the variable being pointed to, and pointerName is the name
of the pointer.
Example:
int* numPtr;
To assign a value to a pointer, you must use the address-of operator & to obtain the memory
address of the variable being pointed to.
Example:
This assigns the memory address of the integer variable num to the pointer numPtr.
To access the value of the variable being pointed to, you must use the dereference operator *.
Example:
940
This outputs the value of the integer variable being pointed to by numPtr.
Pointers can be useful for passing arguments to functions, as they allow the function to access
and modify the original value of the argument.
Example:
int main() {
int num = 10;
int* numPtr = #
doubleValue(numPtr);
cout << num; // Outputs 20
return 0;
}
This declares a function named doubleValue, which takes a pointer to an integer variable as an
argument and doubles the value of the variable using the dereference operator. The function is
then called in the main function with the pointer to the integer variable num as the argument.
In addition to pointers to variables, C++ also supports pointers to arrays and pointers to
functions.
941
This declares an array of integers with 5 elements and a pointer to the first element of the array.
This declares a function named add, which takes two integer arguments and returns their sum,
and a pointer to the add function.
Overall, pointers in C++ are variables that store the memory address of another variable,
which can be useful for manipulating memory directly and for implementing complex data
structures.
In C++, files are used for input and output operations. Input operations involve reading data
from a file into a program, while output operations involve writing data from a program to a file.
C++ provides several file stream classes for handling file input and output operations: ifstream
for input from a file, ofstream for output to a file, and fstream for both input and output.
fstream fileStream;
fileStream.open("filename", mode);
Here, filename is the name of the file to be opened, and mode is the mode in which to open the
file, which can be either ios::in for input, ios::out for output, or ios::in | ios::out for
both input and output.
942
Example of opening a file for output:
ofstream outputFile;
outputFile.open("output.txt", ios::out);
To write data to a file, you can use the insertion operator <<.
To read data from a file, you can use the extraction operator >>.
ifstream inputFile;
inputFile.open("input.txt", ios::in);
string data;
inputFile >> data;
This opens a file named input.txt in input mode and reads a string of data from the file into the
variable data.
After finishing file operations, it is important to close the file using the close function.
943
Example of closing a file:
outputFile.close();
In addition to the basic file operations, C++ also provides functions for checking the status of a
file, moving the file pointer, and working with binary files. Overall, files in C++ are used for
input and output operations, and C++ provides several file stream classes for handling file input
and output. To perform file operations, a file must be opened, data must be read from or written
to the file, and the file must be closed after finishing the operations.
In C++, functions are blocks of code that perform specific tasks. They are used to break down
a program into smaller, more manageable pieces of code, and to avoid writing the same code
repeatedly. Here are some examples of C++ functions:
#include<iostream>
void printHello() {
std::cout << "Hello, world!" << std::endl;
}
int main() {
printHello(); // prints "Hello, world!"
return 0;
}
944
This function printHello takes no parameters and returns no value. It simply prints
"Hello, world!" to the console.
#include <iostream>
int main() {
printName("Alice"); // prints "Hello, Alice!"
printName("Bob"); // prints "Hello, Bob!"
return 0;
}
This function printName takes a std::string parameter name and returns no value. It prints
"Hello, " followed by the value of name and an exclamation mark.
#include<iostream>
int main() {
std::cout << square(5) << std::endl; // prints 25
std::cout << square(-3) << std::endl; // prints 9
return 0;
}
945
This function square takes an int parameter num and returns the square of num. It is used in
main to print the square of 5 and -3.
4. Recursive function
#include<iostream>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
std::cout << factorial(5) << std::endl; // prints 120
std::cout << factorial(0) << std::endl; // prints 1
return 0;
}
This function factorial is a recursive function that calculates the factorial of a number n. It
uses the formula n! = n * (n-1)!. The base case is when n is 0, in which case the function
returns 1.
#include<iostream>
946
int main() {
printAge("Alice"); // prints "Alice is 18 years old."
printAge("Bob", 25); // prints "Bob is 25 years old."
return 0;
}
This function printAge takes a std::string parameter name and an optional int parameter
age with a default value of 18. It prints name and age to the console.
6. Function overloading
Function overloading in C++ allows multiple functions to have the same name but different
parameter lists. This makes it possible to use the same function name for operations that are
conceptually similar but differ in the types or number of arguments used. Here's an example of
function overloading:
#include<iostream>
int main() {
std::cout << add(1, 2) << std::endl; // calls integer version of add()
std::cout << add(3.14, 2.71) << std::endl; // calls double version of add()
return 0;
}
947
In this example, we have two functions with the same name add, but one takes two int
parameters and the other takes two double parameters. When the function is called with int
arguments, the integer version of the function is called, and when the function is called with
double arguments, the double version of the function is called. This is possible because the
function signature (name and parameter list) determines which function is called. Function
overloading can be useful in many situations, such as when you need to perform a similar
operation on different types of data, or when you want to provide multiple ways to call a function
with different numbers or types of arguments. However, care should be taken to ensure that the
overloaded functions have different parameter lists to avoid ambiguity.
7. Lambda function
#include<iostream>
int main() {
int x = 5;
int y = 7;
auto sum = [](int a, int b) -> int {
return a + b;
};
std::cout << sum(x, y) << std::endl; // prints 12
return 0;
}
948
In C++, a class is a user-defined data type that encapsulates data and functions into a single
entity. It provides a way to organize and structure code, and to create objects that can be used to
represent real-world entities or concepts. In this section, we'll look at how to define and use a
class in C++. Here's an example of a simple class:
#include<iostream>
class Rectangle {
public:
int width, height;
int area() {
return width * height;
}
void print() {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
};
int main() {
Rectangle r;
r.width = 10;
r.height = 20;
std::cout << "Area: " << r.area() << std::endl;
r.print();
return 0;
}
In this example, we define a class Rectangle that has two data members width and height,
and two member functions area() and print(). The area() function calculates the area of
949
the rectangle by multiplying the width and height, and the print() function prints the width
and height to the console. In the main() function, we create an object r of the Rectangle
class and set its width and height to 10 and 20, respectively. We then call the area() function to
calculate the area of the rectangle and print it to the console, followed by a call to the print()
function to print the width and height of the rectangle.
Classes can also have constructors and destructors, which are special member functions that are
called when an object is created and destroyed, respectively. Here's an example that shows how
to define a constructor and destructor for the Rectangle class:
#include<iostream>
class Rectangle {
public:
int width, height;
Rectangle() {
width = 0;
height = 0;
std::cout << "Rectangle constructor called" << std::endl;
}
Rectangle(int w, int h) {
width = w;
height = h;
std::cout << "Rectangle constructor called" << std::endl;
}
~Rectangle() {
std::cout << "Rectangle destructor called" << std::endl;
}
950
int area() {
return width * height;
}
void print() {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
};
int main() {
Rectangle r1;
r1.print();
return 0;
}
In this example, we define two constructors for the Rectangle class: a default constructor that
sets the width and height to 0, and a parameterized constructor that takes two integer arguments
and initializes the width and height with those values. We also define a destructor that prints a
message to the console when the object is destroyed. In the main() function, we create two
objects of the Rectangle class: r1 using the default constructor, and r2 using the
parameterized constructor with arguments 10 and 20. We then call the print() function on
both objects to print their width and height to the console. Classes can be used to encapsulate
data and behavior, and to create objects that represent real-world entities or concepts. They can
also be used to define more complex data structures and algorithms, such as linked lists, trees,
and graphs. Understanding how to define and use classes is an important part of C++
programming.
951
In C++, an object is an instance of a class. It is a concrete representation of the data and behavior
defined by the class, and can be used to perform operations and interact with other objects and
the environment. When you create an object of a class, you are essentially creating a new
variable of that type. The object has its own set of data members, which are initialized according
to the constructor of the class, and its own set of member functions, which can be used to
manipulate the data members and perform operations. Here's an example that demonstrates
how to create and use objects in C++:
#include<iostream>
class Rectangle {
public:
int width, height;
Rectangle(int w, int h) {
width = w;
height = h;
}
int area() {
return width * height;
}
void print() {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
};
int main() {
Rectangle r1(10, 20);
r1.print();
std::cout << "Area: " << r1.area() << std::endl;
return 0;
}
952
In this example, we define a class Rectangle that has two data members width and height, a
constructor that initializes the data members with the provided values, and two member functions
area() and print() that calculate the area of the rectangle and print its dimensions to the
console, respectively. In the main() function, we create two objects of the Rectangle class,
r1 and r2, with different values for the width and height data members. We then call the
print() function and the area() function on both objects to print their dimensions and
calculate their areas. Objects in C++ are an important tool for representing real-world entities
and for creating data structures and algorithms. They provide a way to encapsulate data and
behavior into a single entity, and to create multiple instances of that entity with different data
values. Understanding how to create and use objects is an essential part of C++ programming.
C++ exceptions are a way to handle runtime errors in a program. Exceptions allow the program
to detect and handle errors gracefully, rather than crashing or producing undefined behavior.
When an error occurs, an exception object is created and thrown to the nearest enclosing try-
catch block that can handle it. If no such block is found, the program terminates. Here's an
example that demonstrates how to use exceptions in C++:
#include<iostream>
int main() {
int x, y;
try {
if (y == 0) {
953
catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
In this example, we ask the user to enter two integers x and y, and then attempt to divide x by y.
If y is zero, we throw an exception with a message "Division by zero". We catch the exception
with a try-catch block that handles std::exception objects. If an exception is thrown, we
print an error message to the console. Here's another example that demonstrates how to define
and use custom exception classes:
#include<iostream>
#include<string>
int main() {
try {
954
throw MyException("Custom exception");
}
catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
In this example, we define a custom exception class MyException that inherits from
std::exception. The MyException class has a constructor that takes a message string as
input, and a what() function that returns the message string when called. In the main()
function, we throw a MyException object with the message "Custom exception", and catch it
with a try-catch block that handles std::exception objects. Exceptions are a powerful
tool for handling errors and preventing crashes in C++ programs. By throwing and catching
exceptions, you can detect and recover from errors gracefully, and provide useful error messages
to the user. When designing C++ programs, it's important to consider the potential errors that can
occur and to use exceptions to handle them appropriately.
Encapsulation is the concept of hiding the implementation details of a class from the outside
world and providing a public interface to access its functionality. In C++, encapsulation is
achieved through the use of access modifiers like public, private, and protected in the class
definition.
955
#include<iostream>
class BankAccount {
private:
std::string accountNumber;
double balance;
public:
BankAccount(std::string num, double bal) {
accountNumber = num;
balance = bal;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc("12345", 1000.0);
acc.deposit(500.0);
std::cout << "Balance after deposit: " << acc.getBalance() << std::endl;
acc.withdraw(2000.0);
std::cout << "Balance after withdrawal: " << acc.getBalance() << std::endl;
return 0;
}
956
In this example, we define a class BankAccount that has two private data members,
accountNumber and balance, and three public member functions, deposit(),
withdraw(), and getBalance(). The deposit() and withdraw() functions modify the
balance data member, while the getBalance() function returns the balance to the calling
code. The private data members accountNumber and balance are not directly accessible
from the outside world. The calling code can only interact with the public member functions,
which provide a safe and controlled way of accessing and modifying the object's data. This way
of encapsulating the data members of a class ensures that they cannot be accidentally modified
from outside the class, which makes the code more robust and maintainable.
Inheritance is a key concept in object-oriented programming that allows a new class to be based
on an existing class, inheriting its attributes and behavior. In C++, inheritance is implemented
using the class keyword, followed by the name of the new class, a colon, and the name of the
base class. Here is an example of inheritance in C++:
#include<iostream>
class Shape {
protected:
int width;
int height;
public:
Shape(int w, int h) {
width = w;
height = h;
}
return 0;
957
};
class Rectangle : public Shape {
public:
Rectangle(int w, int h) : Shape(w, h) {}
int main() {
Shape* shape;
Rectangle rect(10, 5);
Triangle tri(10, 5);
shape = ▭
std::cout << "Rectangle area: " << shape->area() << std::endl;
shape = &tri;
std::cout << "Triangle area: " << shape->area() << std::endl;
return 0;
}
958
In this example, we define a base class Shape that has two protected data members width and
height, and a public member function area(). We also define two derived classes
Rectangle and Triangle that inherit from Shape. The derived classes Rectangle and
Triangle add their own implementation of the area() function, which overrides the
implementation in the base class. This is achieved by using the override keyword, which tells
the compiler to check that the function is actually overriding a base class function. In the
main() function, we create objects of type Rectangle and Triangle, and use a pointer of
type Shape* to point to them. We then call the area() function on these objects through the
Shape* pointer, which invokes the overridden functions in the derived classes. This way of
using inheritance allows us to reuse code from the base class and add new functionality in the
derived classes, while still maintaining a common interface through the public member functions
of the base class.
Run-time polymorphism is the most commonly used type of polymorphism in C++. It allows
you to write code that works with objects of different types, as long as they all implement the
same interface (i.e. have the same set of virtual functions). When you call a virtual function on a
base class pointer or reference, the actual function that gets called depends on the type of the
object that the pointer or reference points to. This allows you to write code that works with
objects of different types, but still calls the correct function for each type. For example, consider
a base class Animal and two derived classes Dog and Cat. The Animal class has a virtual
959
function makeSound() that is overridden in the Dog and Cat classes. We can create a pointer
of type Animal* that can point to objects of type Dog and Cat. When we call the
makeSound() function on the Animal* pointer, the actual function that gets called depends on
the type of the object that the pointer points to. This allows us to write code that works with both
Dog and Cat objects, but still calls the correct makeSound() function for each type.
#include<iostream>
class Animal {
public:
virtual void makeSound() {
std::cout << "Animal sound" << std::endl;
}
};
int main() {
Animal* animal;
Dog dog;
Cat cat;
animal = &dog;
animal->makeSound(); // Output: Woof!
animal = &cat;
animal->makeSound(); // Output: Meow!
return 0;
}
960
In this example, we use the Animal* pointer to point to objects of type Dog and Cat. When we
call the makeSound() function on the Animal* pointer, the actual function that gets called
depends on the type of the object that the pointer points to. This allows us to write code that
works with both Dog and Cat objects, but still calls the correct makeSound() function for each
type.
In C++, a constructor is a special member function of a class that is called when an object of
that class is created. The purpose of the constructor is to initialize the data members of the object
to some initial values. The syntax for a constructor is as follows:
class ClassName {
public:
ClassName(); // Constructor declaration
};
The constructor has the same name as the class and does not have a return type. It can have
parameters, just like a regular function. There are two types of constructors in C++: default
constructor and parameterized constructor. The default constructor is a constructor that
takes no parameters, and its purpose is to initialize the data members of the object to some
default values. If a class does not have any constructors defined, the compiler automatically
generates a default constructor for the class. For example:
#include<iostream>
class Point {
public:
int x, y;
Point() {
x = 0;
y = 0;
961
}
};
int main() {
Point p;
std::cout << p.x << ", " << p.y << std::endl; // Output: 0, 0
return 0;
}
In this example, we have defined a class Point that represents a point in 2D space. We have
defined a default constructor that initializes the x and y data members to 0. When we create an
object of the Point class using the default constructor, the x and y data members are
initialized to 0. A parameterized constructor is a constructor that takes one or more
parameters, and its purpose is to initialize the data members of the object to some specific values
based on the arguments passed to the constructor. For example:
#include <iostream>
class Point {
public:
int x, y;
Point(int x, int y) {
this->x = x;
this->y = y;
}
};
int main() {
Point p(1, 2);
std::cout << p.x << ", " << p.y << std::endl; // Output: 1, 2
return 0;
}
962
In this example, we have defined a parameterized constructor that takes two integers x and y
as arguments. The constructor initializes the x and y data members of the object to the values
passed as arguments. When we create an object of the Point class using the parameterized
constructor with arguments 1 and 2, the x and y data members are initialized to 1 and 2,
respectively.
High performance: C++ is a compiled language, which means that code written in C++
is compiled into machine code that can be executed directly by the computer's processor.
This makes C++ programs very fast and efficient.
Object-oriented programming: C++ supports object-oriented programming (OOP),
which allows developers to write code that is organized around objects and classes. OOP
makes it easier to write and maintain large, complex programs.
Portability: C++ code can be compiled and run on a wide variety of platforms, including
Windows, macOS, Linux, and many others.
Standard libraries: C++ comes with a large number of standard libraries that provide a
wide range of functionality, including input/output, strings, math functions, and more.
These libraries can save developers a lot of time and effort by providing pre-written code
that can be used in their programs.
Compatibility with C: C++ is largely backwards-compatible with C, which means that
many C programs can be easily converted to C++.
Operating systems: Many operating systems, including Windows and macOS, are
written in C++.
Game development: C++ is a popular language for game development due to its high
performance and support for OOP.
963
Web browsers: Both Google Chrome and Mozilla Firefox are built using C++.
Financial software: C++ is often used in financial software due to its speed and ability
to handle large amounts of data.
Industrial automation: Many industrial automation systems use C++ for their control
software due to its real-time performance and ability to interface with hardware.
In this code, memory is allocated twice for ptr without deallocating the first allocation.
This creates a memory leak.
Complexity: C++ can be complex to learn and use, especially for beginners. For
example, consider the following code:
class Rectangle {
int width, height;
public:
Rectangle(int w, int h) {
width = w;
height = h;
}
int area() {
return width * height;
}
};
int main() {
Rectangle rect(5, 10);
std::cout << "Area: " << rect.area() << std::endl;
return 0;
}
964
This code defines a class Rectangle with a constructor and a method area(). While
this is a simple example, it illustrates the complexity of the C++ syntax and the need to
understand concepts such as classes and methods.
int main() {
char buffer[8];
std::strcpy(buffer, "Hello world!");
return 0;
}
This code copies the string "Hello world!" into a buffer that is only 8 bytes long. This can
lead to a buffer overflow, where the extra characters overwrite adjacent memory,
potentially leading to a security vulnerability.
Compiler compatibility issues: Different compilers can produce different results when
compiling C++ code. For example, consider the following code:
int main() {
int x = 0;
std::cout << x++ << ++x << std::endl;
return 0;
}
The output of this code is undefined because the order in which the expressions x++ and ++x
are evaluated is not specified by the C++ standard. This can lead to compatibility issues
between different compilers and environments.
Lack of garbage collection: C++ does not have automatic garbage collection, which
means that the programmer is responsible for managing memory manually. For example,
consider the following code:
965
int* ptr = new int;
// ...
delete ptr;
This code allocates memory for an integer using new, and then deallocates the memory using
delete. If the programmer forgets to deallocate the memory, a memory leak can occur. If
the programmer deallocates the memory twice, the program can crash.
Slow development time: C++ can be slower to develop in than other languages such as
Python or Ruby, due to its complex syntax and manual memory management.
It's worth noting that many of these disadvantages can be mitigated with careful coding practices
and the use of libraries and frameworks that provide higher-level abstractions for memory
management and other tasks.
966
C++ has been used to create some of the most popular software in the world, including
Microsoft Windows, Adobe Photoshop, and Google Chrome.
C++ has a reputation for being a difficult language to learn and use, but many
programmers find it rewarding and even fun to work with.
There are many puns and jokes related to C++ and programming in general. For example,
"Why did the C++ developer break up with the Java developer? Because she didn't
like his class."
967
JAVA – OVERVIEW
Java is a popular programming language that was created in the mid-1990s by James
Gosling and his team at Sun Microsystems. It is a general-purpose, high-level, object-
oriented programming language that is designed to be platform-independent, meaning that
it can be run on any operating system or platform that has a Java Virtual Machine (JVM).
Java is widely used for developing a variety of applications, including desktop applications,
web applications, mobile applications, and enterprise applications. It is also used for
developing software for embedded systems and Internet of Things (IoT) devices. Some
key features of Java include:
Java is widely used in industries such as finance, healthcare, and technology, and it is also
used extensively in education for teaching programming concepts. Many popular software
applications, such as Adobe Creative Suite and Minecraft, are built on Java. Additionally,
Java is used for developing Android apps, making it a popular choice for mobile
development.
968
Here's an example of how to write "Hello, world!" in Java:
The public keyword means that this class is accessible to code outside of its own
package.
The class keyword is used to declare a new class.
MyClass is the name of the class. The class name must match the file name.
The opening and closing curly braces { } define the boundaries of the class definition.
public static void main(String[] args) is the declaration of the main method,
which is the entry point of the program. It is required for every Java program.
The System.out.println() statement prints the string "Hello, world!" to the console.
Hello, world!
Java comments are used to provide information or explanation about the code to other
developers who may read the code. Comments are not executed by the computer and do not
affect the code's functionality. There are three types of comments in Java:
Single-line comments − These comments are created using // and are used to explain a
single line of code. Everything after the // is ignored by the compiler.
Example:
969
// This is a single-line comment
int x = 5; // this assigns the value 5 to x
Multi-line comments − These comments are created using /* to start and */ to end the
comment block. They can span across multiple lines of code.
Example:
/*
This is a multi-line comment
It can span across multiple lines
*/
int y = 10;
Javadoc comments − These comments are created using /** to start and */ to end the
comment block. They are used to provide documentation about classes, methods, and
fields, and are used by JavaDoc tools to create API documentation.
Example:
/**
* This is a Javadoc comment. It is used to provide documentation for a class,
* method or field.
* In this example, we are defining a class called ExampleClass.
*/
public class ExampleClass {
/**
* This is a Javadoc comment for the ExampleMethod method. It explains what the
* method does and what it returns.
* @param x an integer parameter
* @return the sum of x and y
*/
public int ExampleMethod(int x) {
int y = 5;
return x + y;
}
}
970
Overall, comments are a useful tool for developers to explain their code and improve its readability.
In Java, a variable is a named memory location used to store data. A variable can hold
different types of data, such as integers, floating-point numbers, characters, and strings. Here are
some examples of how to use variables in Java:
float y = 3.14f; // declaring and initializing a float variable with the value 3.14
char c = 'a'; // declaring and initializing a character variable with the value 'a'
String name = "John"; // declaring and initializing a string variable with the value "John"
boolean flag = true; // declaring and initializing a boolean variable with the value true
971
7. Using a variable in an expression:
int x = 10;
int y = 20;
int sum = x + y; // using the variables x and y to calculate the sum
Overall, variables are an essential part of Java programming, and they allow developers to
store and manipulate data in their programs.
In Java, data types are used to classify the type of data that a variable can hold. Java has two
categories of data types: primitive data types and reference data types.
Primitive Data Types: Primitive data types are the most basic data types in Java, and they are
used to store simple values such as integers, floating-point numbers, characters, and boolean
values. There are eight primitive data types in Java:
Reference Data Types: Reference data types are used to store complex objects and are created
using classes or interfaces. These data types refer to a memory location where the object is
stored, rather than storing the object directly. Examples of reference data types include String,
Arrays, and Class objects.
972
Here are some examples of how to declare and use data types in Java:
String name = "John"; // initializing a String variable with the value "John"
int[] arr = {1, 2, 3, 4}; // initializing an integer array with the values 1, 2, 3, and 4
Overall, data types are used to define the type of data that a variable can hold in Java. The
primitive data types are used to store simple values, while reference data types are used to store
complex objects. Understanding data types is important for writing effective Java programs.
973
Java Type Casting is the process of converting the value of one data type to another data
type. This is necessary when you want to use a value of one data type in an expression that
expects another data type. In Java, there are two types of type casting: explicit and implicit.
Explicit Type Casting: This is when you convert a data type to another data type
explicitly by specifying the target type in parentheses before the value being cast. For
example:
double d = 3.14;
int i = (int) d;
In this example, we convert a double value to an int value using explicit type casting. The value
of the double variable d is cast to an int value and stored in the int variable i. Note that this may
result in data loss as the decimal part of the double value is truncated.
Implicit Type Casting: This is when you convert a data type to another data type
implicitly by the compiler. Implicit type casting occurs when the data type of the target
variable is larger than the data type of the source variable. For example:
int i = 10;
float f = i;
In this example, we convert an int value to a float value using implicit type casting. The
value of the int variable i is automatically cast to a float value and stored in the float variable f.
Note that this does not result in data loss as the float data type is larger than the int data type.
It is important to note that type casting can result in data loss or overflow if the target data type is
not large enough to hold the value of the source data type. In such cases, you may need to use
additional logic to handle such scenarios.
974
Java operators are symbols or keywords that perform certain operations on one or more
operands. They are classified into different categories based on their functionality. Here are
some of the commonly used operators in Java:
Operator Description
+ Addition
− Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
Assignment Operators: These operators are used to assign a value to a variable. The
following table shows the assignment operators in Java:
975
Operator Example Same As
= a = 10; a = 10;
+= a += 10; a = a + 10;
−= a −= 10; a = a − 10;
*= a *= 10; a = a * 10;
/= a /= 10; a = a / 10;
%= a %= 10; a = a % 10;
Comparison Operators: These operators are used to compare two values and return a
boolean value (true or false). The following table shows the comparison operators in
Java:
976
Operator Description
== Equal to
!= Not equal to
Logical Operators: These operators are used to combine two or more boolean
expressions and return a boolean value. The following table shows the logical
operators in Java:
Operator Description
977
&& Logical AND
! Logical NOT
Increment and Decrement Operators: These operators are used to increase or decrease
the value of a variable by 1. The following table shows the increment and decrement
operators in Java:
Operator Description
++ Increment by 1
−− Decrement by 1
Bitwise Operators: These operators are used to perform bitwise operations on binary
numbers. The following table shows the bitwise operators in Java:
Operator Description
978
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
These are the main categories of Java operators. Understanding and using these operators
correctly is important for writing efficient and effective Java code.
In Java, a String is an object that represents a sequence of characters. Strings are widely
used in Java programming, and here are some examples of how to work with strings in Java:
1. Creating a String:
979
In this example, we create a String variable called greeting and initialize it with the value
"Hello, world!".
2. Concatenating Strings:
In this example, we concatenate two String variables, firstName and lastName, with a space
in between, and store the result in a new String variable called fullName.
In this example, we get the length of a String variable called text using the length() method
and store the result in an integer variable called length.
4. Comparing Strings:
In this example, we compare two String variables, str1 and str2, using the equals() method
and store the result in a boolean variable called result.
980
String str = "123";
int num = Integer.parseInt(str);
In this example, we convert a String variable called str to an integer variable using the
parseInt() method of the Integer class.
6. Substring:
In this example, we get a substring of a String variable called text starting from index 8 and
ending at index 12, and store the result in a new String variable called subString. These are
just a few examples of how to work with Strings in Java. Strings are very versatile and there are
many other methods and operations that can be performed on them.
In Java, the Math class provides a set of static methods for performing various mathematical
operations. Here are some commonly used methods from the Math class in Java:
Math.abs(): This method returns the absolute value of a number. For example,
Math.abs(-5) would return 5.
Math.ceil(): This method returns the smallest integer greater than or equal to
the specified number. For example, Math.ceil(3.2) would return 4.0.
Math.floor(): This method returns the largest integer less than or equal to
the specified number. For example, Math.floor(3.9) would return 3.0.
Math.round(): This method returns the closest integer to the specified number.
For example, Math.round(3.2) would return 3.
Math.max(): This method returns the greater of two numbers. For example,
Math.max(3, 5) would return 5.
Math.min(): This method returns the smaller of two numbers. For example,
Math.min(3, 5) would return 3.
981
Math.pow(): This method returns the value of the first argument raised to the
power of the second argument. For example, Math.pow(2, 3) would return 8.0.
Math.sqrt(): This method returns the square root of a number. For example,
Math.sqrt(25) would return 5.0.
Math.random(): This method returns a random number between 0.0 and 1.0. For
example, Math.random() would return a value between 0.0 and 1.0 (exclusive).
Math.PI: This is a constant in the Math class that represents the value of pi
(approximately 3.141592653589793). It can be used in mathematical calculations
that involve circles, such as calculating the circumference or area of a
circle.
These are just a few examples of the methods available in the Math class. There are many other
methods available for performing more complex mathematical operations. The Math class is an
essential part of Java programming and is used extensively in many applications.
In Java, boolean is a primitive data type that can only have two values: true or false.
Boolean values are used to represent logical values in Java programming. Here are some
examples of how to work with booleans in Java:
In this example, we declare a boolean variable called isRaining and initialize it with the value true.
boolean a = true;
boolean b = false;
boolean result = a && b;
982
In this example, we compare two boolean variables, a and b, using the logical AND operator
(&&) and store the result in a boolean variable called result.
In this example, we define a method called isEven that takes an integer argument and returns a
boolean value indicating whether the number is even or not.
boolean a = true;
boolean b = false;
boolean result1 = a && b; // logical AND
boolean result2 = a || b; // logical OR
boolean result3 = !a; // logical NOT
983
In this example, we use three different boolean operators (&&, ||, and !) to combine and
negate boolean values. These are just a few examples of how to work with booleans in Java.
Boolean values are an important part of programming in Java and are used extensively in many
applications.
In Java, the if...else statement is used to execute different blocks of code depending on
whether a particular condition is true or false. The basic syntax for if...else is as follows:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Here, condition is a boolean expression that evaluates to either true or false. If the condition is
true, the code inside the first set of curly braces is executed. If the condition is false, the code
inside the second set of curly braces is executed. For example, let's say we want to write a Java
program that checks whether a given number is positive or negative. We can use if...else to
accomplish this as follows:
if (number > 0) {
System.out.println(number + " is positive");
} else {
System.out.println(number + " is negative");
}
}
}
984
In this example, we declare an integer variable called number and initialize it to −7. We then use
if...else to check whether number is greater than 0. Since −7 is less than 0, the condition is
false, so the code inside the else block is executed. This code simply prints a message to the
console indicating that number is negative. If number had been positive, the code inside the if
block would have been executed instead, printing a message indicating that number is positive.
In Java, the switch statement provides a way to execute different blocks of code based on the
value of a single variable or expression. The basic syntax for switch is as follows:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
...
case valueN:
// code to execute if expression == valueN
break;
default:
// code to execute if none of the cases match
}
Here, expression is the variable or expression that we want to compare against the different
cases. Each case statement specifies a value that expression might take, and the code inside
the corresponding block is executed if expression has that value. If none of the cases match,
the code inside the default block is executed. For example, let's say we want to write a Java
program that prints the name of a month based on its number (1 for January, 2 for February,
etc.). We can use switch to accomplish this as follows:
985
public class MyClass {
public static void main(String[] args) {
int month = 5;
switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid month number");
}
}
}
986
In this example, we declare an integer variable called month and initialize it to 5, which
corresponds to May. We then use switch to check the value of month. Since month is equal to
5, the case 5 is matched and the code inside the corresponding block is executed, which simply
prints the name of the month "May". If month had been a different value, the corresponding case
block would have been executed instead, or if none of the cases matched, the code inside the
default block would have been executed.
In Java, loops are used to execute a block of code repeatedly while a certain condition is true.
There are three types of loops in Java: for, while, and do...while.
1. for loop
The for loop is used to execute a block of code for a fixed number of times. The basic
syntax for "for" is as follows:
987
In this example, we use "for" to initialize a loop control variable i to 1, execute the loop as
long as i is less than or equal to 10, and increment i by 1 after each iteration. The code inside
the curly braces simply prints the value of i to the console.
2. while loop
The while loop is used to execute a block of code as long as a certain condition is true. The
basic syntax for while is as follows:
while (condition) {
// code to execute repeatedly
}
Here, condition is a boolean expression that is evaluated before each iteration of the loop.
The code inside the curly braces is executed repeatedly as long as condition is true. For
example, let's say we want to write a Java program that prints the numbers from 1 to 10 using
a while loop. We can accomplish this as follows:
In this example, we initialize a loop control variable i to 1 before entering the loop. We then use
while to execute the loop as long as i is less than or equal to 10. The code inside the curly
braces simply prints the value of i to the console and increments i by 1 after each iteration.
988
3. do...while loop
The do...while loop is similar to the while loop, but the condition is evaluated after
the code inside the loop is executed, so the code is guaranteed to execute at least once.
The basic syntax for do...while is as follows:
do {
// code to execute repeatedly
} while (condition);
Here, condition is a boolean expression that is evaluated after each iteration of the
loop. The code inside the curly braces is executed repeatedly until condition is false.
For example, let's say we want to write a Java program that prints the numbers from 1 to
10 using a do...while loop. We can accomplish this as follows:
In this example, we initialize a loop control variable i to 1 before entering the loop. We then use
do...while to execute the loop at least once, printing the value of i to the console and
incrementing i by 1 after each iteration. The loop continues to execute as long as i is less than
or equal to 10. One important thing to note about do...while loops is that the code block
inside the loop is guaranteed to execute at least once, regardless of whether the condition is true
989
or false. This makes do...while loops particularly useful when you need to execute a block of
code at least once before checking a condition.
In Java, an array is a data structure that allows you to store a collection of elements of the
same type in a contiguous memory location. Arrays are one of the fundamental data structures in
programming, and they are used extensively in Java and many other programming languages. To
declare an array in Java, you need to specify the type of the elements and the size of the array.
The syntax for declaring an array is as follows:
Here, type is the type of the elements in the array, arrayName is the name of the array variable,
and size is the number of elements in the array. For example, to declare an array of 5 integers,
you would use the following code:
Once you have declared an array, you can access its elements using an index. The index of the
first element in the array is 0, and the index of the last element is (size – 1). You can access
an element in the array using the following syntax:
arrayName[index]
Here, arrayName is the name of the array variable, and index is the index of the element you
want to access. For example, to assign a value of 10 to the first element of the numbers array,
you would use the following code:
numbers[0] = 10;
990
Arrays can also be initialized with values at the time of declaration using an array initializer.
The syntax for initializing an array is as follows:
Here, type is the type of the elements in the array, arrayName is the name of the array variable,
and value1, value2, ..., valueN are the values to be stored in the array. For example, to
declare and initialize an array of 3 integers with values of 1, 2, and 3, you would use the
following code:
Arrays can also be used with loops to iterate over their elements. For example, to print all the
elements in the numbers array, you could use a "for" loop as follows:
Here, numbers.length gives the size of the numbers array, and the loop iterates over all the
elements in the array, printing each element to the console. Arrays are an important data
structure in Java, and they are used extensively in many applications for the following reasons:
• Grouping Data: Arrays allow you to group related data of the same type into a single
data structure. This makes it easier to manage and manipulate the data as a whole.
• Efficient Access: Arrays provide efficient access to their elements through their index,
which allows you to quickly retrieve or modify a specific element in the array.
991
• Iteration: Arrays can be easily iterated over using loops, which allows you to perform
operations on all the elements in the array.
• Memory Efficiency: Arrays store their elements in contiguous memory locations, which
makes them more memory-efficient than other data structures that require more complex
memory allocation.
• Passing Arrays to Methods: Arrays can be passed as arguments to methods, which
allow you to reuse code and perform operations on arrays in a modular and reusable way.
• Sorting and Searching: Arrays provide built-in methods for sorting and searching their
elements, which makes it easier to perform these operations without having to write your
own algorithms.
In addition to these benefits, arrays are also widely used in many algorithms and data
structures, such as sorting algorithms, binary search trees, and hash tables. Overall, arrays are an
important data structure in Java that provide a powerful and efficient way to group and manage
related data.
In Java, a method is a block of code that performs a specific task or set of tasks. Methods
provide a way to modularize code and reuse it in different parts of a program. Methods can also
accept parameters and return values, which make them more flexible and powerful. To define a
method in Java, you need to specify its name, return type (if any), and parameter list (if any).
The syntax for defining a method is as follows:
Here, accessModifier specifies the visibility of the method (e.g. public, private,
protected, or no modifier), returnType specifies the type of value that the method returns
(or void if it doesn't return anything), methodName is the name of the method, and
992
parameterList is a comma-separated list of parameters that the method accepts (if any). For
example, the following method "add" takes two integers as parameters and returns their sum:
Once a method is defined, it can be called from other parts of the program using its name and
passing in the necessary arguments. For example, to call the "add" method defined above, you
would use the following code:
Methods can also be overloaded, which means you can define multiple methods with the same
name but different parameter lists. Java determines which method to call based on the number
and types of arguments passed to the method. For example, the following method "add" is an
overloaded version of the method defined above that takes three integers as parameters and
returns their sum:
Overall, methods are an important concept in Java that provides a powerful way to organize
code and make it more reusable and flexible.
993
public class Example {
public static void main(String[] args) {
// Call the hello method
hello();
}
In this example, we define a class called Example that contains a single method called hello.
The "hello" method simply prints the string "Hello, world!" to the console using the
System.out.println statement. In the main method, we call the hello method using the
method name and the parentheses operator. When the program runs, it will print the message
"Hello, world!" to the console. Here's another example of a method that accepts parameters and
returns a value:
// Define the add method that accepts two integers and returns their sum
public static int add(int x, int y) {
int sum = x + y;
return sum;
}
}
994
In this example, we define a method called add that accepts two integer parameters and returns
their sum. In the main method, we call the add method with the integers 2 and 3, and assign the
result to the "result" variable. We then print the value of "result" to the console, which
should be 5.
Java is an object-oriented programming language, which means that it revolves around the
concept of classes and objects. Classes are blueprints for creating objects, and objects are
instances of a class. In simpler terms, a class defines the properties and behaviors of an object,
while an object is a specific instance of that class with its own unique values. Let's take an
example to understand this concept better. Suppose we want to create a class named "Person"
that has the properties of "name", "age", and "gender". We can define the class as follows:
In this class, we have defined three properties: "name" (a string), "age" (an integer), and
"gender" (a character). Now that we have defined our class, we can create an object of this
class using the "new" keyword as follows:
Here, we have created an object named "person1" of the "Person" class. Now, we can set the
values for the properties of this object as follows:
person1.name = "John";
person1.age = 25;
person1.gender = 'M';
995
We can also create multiple objects of the same class, each with its own set of values, as follows:
Now we have two objects of the "Person" class: "person1" and "person2", each with their
own set of values for the properties. In addition to properties, classes can also have methods,
which are functions that can be called on an object of the class. For example, we can add a
method to the "Person" class that prints out the name and age of the person as follows:
Now, we can call the "printDetails" method on any object of the "Person" class as follows:
person1.printDetails(); // Output: Name: John, Age: 25
person2.printDetails(); // Output: Name: Jane, Age: 30
Overall, classes are the blueprints for creating objects, and objects are specific instances of a
class with their own set of values for the properties. Classes can have properties and methods,
which define the characteristics and behavior of the objects.
996
In Java, modifiers are keywords that can be added to classes, methods, and variables to
modify their behavior or characteristics. There are two types of modifiers in Java: access
modifiers and non-access modifiers.
Access modifiers control the accessibility of classes, methods, and variables from other parts of
the program. There are four access modifiers in Java: public, private, protected, and default.
Public: A public class, method, or variable can be accessed from any other part of the
program.
Private: A private class, method, or variable can only be accessed within the same class.
Protected: A protected class, method, or variable can be accessed from within the same
package or from a subclass in a different package.
Default: A default (package-private) class, method, or variable can only be accessed
within the same package.
Non-access modifiers modify the behavior or characteristics of classes, methods, and variables.
There are several non-access modifiers in Java:
Final: A final variable cannot be changed once it is initialized. A final method cannot be
overridden in a subclass, and a final class cannot be subclassed.
Static: A static variable or method belongs to the class rather than an instance of the
class.
Abstract: An abstract class or method is declared but not defined. An abstract class
cannot be instantiated, and an abstract method must be implemented by a subclass.
Synchronized: A synchronized method can only be accessed by one thread at a time,
ensuring that the method is thread-safe.
Volatile: A volatile variable is not cached, and its value is always read from the main
memory. This is useful for variables that are shared between threads.
By using modifiers effectively, you can control the behavior and accessibility of your classes,
methods, and variables, making your code more robust and efficient.
997
In Java, encapsulation is a mechanism that allows you to control access to the internal state
of an object. It is one of the fundamental principles of object-oriented programming and is
achieved through the use of access modifiers and getter or setter methods. Encapsulation
ensures that the internal state of an object is only modified through well-defined methods,
preventing other parts of the program from directly accessing or modifying the object's data. This
provides several benefits, including:
Improved security: Encapsulation ensures that the internal state of an object cannot be
accessed or modified by unauthorized parts of the program.
Improved maintainability: Encapsulation makes it easier to change the internal
implementation of an object without affecting other parts of the program.
Improved flexibility: Encapsulation allows you to define a well-defined interface for an
object, making it easier to use in different parts of the program.
998
In this example, the balance variable is declared as private, which means it cannot be
accessed or modified directly by other parts of the program. Instead, the deposit and
withdraw methods are used to modify the balance. The getBalance method is defined as
public, which allows other parts of the program to retrieve the current balance. This method
provides a well-defined interface for accessing the internal state of the BankAccount object,
ensuring that it is only modified through the deposit and withdraw methods. By using
encapsulation in your Java programs, you can ensure that your objects are well-defined and
secure, making them easier to maintain and more flexible to use in different parts of your
program.
In Java, a package is a way of organizing related classes and interfaces into a single unit of
code. Packages help to avoid naming conflicts and provide a mechanism for access control. A
package can contain sub-packages, classes, interfaces, and other resources like images, audio
files, etc. Java packages are identified by their package name, which is a unique identifier that is
used to distinguish them from other packages. The package name is typically written in reverse
domain name notation, such as com.example.myapp. Here is an example of how to declare a
package in Java:
package com.example.myapp;
In this example, the MyClass class is declared in the com.example.myapp package. To use a
class from another package, you must either import the class or use its fully qualified name. For
example:
import com.example.myapp.MyClass;
999
In this example, the MyClass class is imported using the import statement, and an instance of
MyClass is created using the new keyword. If you don't want to use an import statement, you
can use the fully qualified name of the class instead:
In this example, the fully qualified name of the MyClass class is used to create an instance of
the class. By using packages in your Java programs, you can organize your code into logical
units, avoid naming conflicts, and provide a mechanism for access control.
In Java, inheritance is a mechanism that allows you to create a new class based on an
existing class. The new class, called the subclass, inherits the properties and behavior of the
existing class, called the superclass, and can also add its own properties and behavior.
Inheritance is one of the fundamental principles of object-oriented programming and is used to
create a hierarchy of related classes. The superclass is at the top of the hierarchy, and the
subclasses are below it. Here is an example of inheritance in Java:
1000
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
In this example, the Animal class is the superclass, and the Cat class is the subclass. The Cat
class inherits the name and age properties from the Animal class and adds its own method,
meow. To create an instance of the Cat class, you can use the following code:
In this example, the myCat object is an instance of the Cat class and can access the eat, sleep,
and meow methods. By using inheritance in your Java programs, you can create a hierarchy of
related classes that share common properties and behavior, making your code more modular and
easier to maintain.
In Java, an inner class is a class that is defined inside another class. Inner classes are a powerful
feature of Java that allows you to logically group classes and interfaces in one place, and to
encapsulate
There are fourthem inside
types another
of inner class.
classes in Java:
1001
There are four types of inner classes in Java:
Member Inner Class: A member inner class is defined inside a class and can access the
members of the enclosing class, including private members. To create an instance of a
member inner class, you must first create an instance of the enclosing class.
Local Inner Class: A local inner class is defined inside a method or a block, and can
only be accessed within that method or block. Local inner classes are typically used to
define an implementation of an interface or an abstract class.
Anonymous Inner Class: An anonymous inner class is a local inner class that does not
have a name. Anonymous inner classes are typically used to define an implementation of
an interface or an abstract class on the fly.
Static Nested Class: A static nested class is a class that is defined inside another class,
but is not an inner class. Static nested classes can only access static members of the
enclosing class.
class InnerClass {
public void printX() {
System.out.println(x);
}
}
}
In this example, the InnerClass is a member inner class of the OuterClass. The printX
method of the InnerClass can access the private x variable of the OuterClass. To create an
instance of the InnerClass, you must first create an instance of the OuterClass:
1002
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.printX(); // outputs "10"
In this example, the innerObject is an instance of the InnerClass and can access the
private x variable of the OuterClass. By using inner classes in your Java programs, you can
create more modular and organized code, and encapsulate related classes and interfaces inside
another class. Inner classes can also access the members of the enclosing class, which can be
useful in certain situations.
Java abstraction and interfaces are two important concepts in object-oriented programming
that help in achieving modular, maintainable, and reusable code. Abstraction is the process of
hiding the implementation details of a class or an object and exposing only the necessary
information to the user. It is one of the key principles of object-oriented programming and is
used to simplify complex systems by breaking them down into smaller, more manageable pieces.
In Java, abstraction is achieved through abstract classes and interfaces. An abstract class is a
class that cannot be instantiated, and is used as a base class for other classes. It contains one or
more abstract methods, which are declared but not implemented in the abstract class. The
subclasses of an abstract class must implement all the abstract methods declared in the abstract
class. Here is an example of an abstract class in Java:
1003
public String getColor() {
return color;
}
}
In this example, the Shape class is an abstract class that contains two abstract methods getArea
and getPerimeter. The subclasses of the Shape class, such as Circle and Rectangle, must
implement these methods. An interface in Java is similar to an abstract class, but it only contains
abstract methods and constant fields. An interface is a contract between the interface and the
implementing class, specifying the methods that must be implemented by the implementing
class. Here is an example of an interface in Java:
In this example, the Drawable interface contains only one method draw. Any class that
implements the Drawable interface must implement the draw method. Interfaces can also
extend other interfaces, allowing for multiple inheritance. Here is an example:
In this example, the Shape interface extends the Drawable interface and contains two abstract
methods getArea and getPerimeter. By using abstraction and interfaces in your Java
1004
programs, you can create modular, maintainable, and reusable code. Abstraction allows you to
hide the implementation details of a class and expose only the necessary information to the user,
while interfaces allow you to define a contract between the interface and the implementing class,
specifying the methods that must be implemented by the implementing class.
In Java, an enum is a special type of class that represents a fixed set of constants. Enums are
useful when you have a predefined set of values that a variable can take, and you want to restrict
the values that the variable can have. An enum is defined using the enum keyword, and the
constants are listed inside the curly braces. Here is an example of an enum in Java:
In this example, the Day enum represents the days of the week, and the constants are the days
themselves. Each constant is implicitly declared as a public static final field of the enum type.
You can use an enum in your Java program by declaring a variable of the enum type. Here is an
example:
In this example, the variable today is declared as an instance of the Day enum, and is initialized
to the MONDAY constant. You can also use enums in switch statements, which can make your
code more readable and maintainable. Here is an example:
1005
switch (today) {
case MONDAY:
System.out.println("It's Monday!");
break;
case TUESDAY:
System.out.println("It's Tuesday!");
break;
// ... other cases ...
default:
System.out.println("It's not a weekday!");
break;
}
In this example, the switch statement is used to print a message depending on the value of the
today variable. Enums can also have fields, constructors, and methods, just like regular classes.
Here is an example:
1006
In this example, the Day enum has a name field, a constructor that takes a name parameter, and
a getName method that returns the name field. Enums are a powerful feature of Java that can
make your code more readable and maintainable by restricting the values that a variable can
have, and by providing a type-safe way to represent a fixed set of constants.
Here's an example of how to take user input in Java using the Scanner class:
import java.util.Scanner;
1007
In this example, we use the Scanner class to read user input from the console. We first create
a Scanner object and pass in System.in as the argument, which represents the standard input
stream (i.e., the console). We then prompt the user to enter their name using the
System.out.print() method, and read their input as a String using the nextLine() method
of the Scanner object. We do the same for the user's age, but read the input as an integer using
the nextInt() method. Finally, we print out the user's name and age using the
System.out.println() method, and remember to close the Scanner object using the
close() method.
In Java, ArrayList is a class that provides a resizable array implementation. Unlike regular
arrays, ArrayList can dynamically grow or shrink its size as needed, making it more flexible
and convenient to use in certain scenarios. Here's an example of how to create and use an
ArrayList in Java:
import java.util.ArrayList;
1008
// get the size of the list
int size = numbers.size();
System.out.println("The size of the list is " + size);
// output: The size of the list is 4
1009
In this example, we first create an empty ArrayList of integers by using the
ArrayList<Integer> syntax. We then add some numbers to the list using the add() method,
and print out the entire list using the System.out.println() method. We then demonstrate
some common methods of ArrayList, including getting the size of the list using the size()
method, accessing an element by index using the get() method, modifying an element by index
using the set() method, removing an element by index using the remove() method, checking
if an element is in the list using the contains() method, and iterating through the list using a
for-each loop. Note that ArrayList can also store objects of other types besides integers, such
as strings or custom objects, by simply changing the type parameter in the ArrayList<>
syntax.
In Java, HashMap is a class that provides a hash table implementation of the Map interface. A
HashMap stores key-value pairs, where each key is unique and maps to a corresponding value.
HashMap provides fast lookup and insertion operations, making it useful in many applications.
Here's an example of how to create and use a HashMap in Java:
import java.util.HashMap;
// create an empty HashMap with keys of type String and values of type Integer
HashMap<String, Integer> scores = new HashMap<>();
1010
System.out.println("Alice's score is " + aliceScore); // output: Alice's score is 80
In this example, we first create an empty HashMap with keys of type String and values of type
Integer by using the HashMap<String, Integer> syntax. We then add some key-value
pairs to the map using the put() method, and retrieve a value for a specific key using the get()
method. We then demonstrate some common methods of HashMap, including checking if a key
is in the map using the containsKey() method, updating the value for a key using the put()
method, removing a key-value pair from the map using the remove() method, and iterating
through the keys in the map using the keySet() method and a for-each loop. Note that
1011
HashMap can also store objects of other types besides strings and integers, such as custom
objects, by simply changing the type parameters in the HashMap<> syntax.
In Java, HashSet is a class that provides a hash table implementation of the Set interface. A
HashSet stores a collection of unique elements, where the order of the elements is not
guaranteed. HashSet provides fast insertion and lookup operations, making it useful in many
applications where uniqueness of elements is a requirement. Here's an example of how to create
and use a HashSet in Java:
import java.util.HashSet;
1012
// check if an element is in the set
boolean containsBob = names.contains("Bob");
System.out.println("Does the set contain Bob? " + containsBob);
// output: Does the set contain Bob? true
In this example, we first create an empty HashSet of strings by using the HashSet<String>
syntax. We then add some names to the set using the add() method, including a duplicate name
to demonstrate that HashSet only stores unique elements. We print out the entire set using the
System.out.println() method, which shows that the order of the elements is not
guaranteed. We then demonstrate some common methods of HashSet, including getting the size
of the set using the size() method, checking if an element is in the set using the contains()
method, removing an element from the set using the remove() method, and iterating through
the set using a for-each loop. Note that HashSet can also store objects of other types besides
strings, such as integers or custom objects, by simply changing the type parameter in the
HashSet<> syntax.
In Java, Iterator is an interface that provides a way to traverse a collection of elements, such
as an ArrayList or a HashSet. An Iterator allows you to sequentially access the elements
1013
in a collection, one at a time, without exposing the underlying implementation of the collection.
Here's an example of how to use an Iterator in Java:
import java.util.ArrayList;
import java.util.Iterator;
In this example, we first create an ArrayList of integers and add some elements to it. We then
create an Iterator for the ArrayList using the iterator() method. We iterate through the
ArrayList using the hasNext() and next() methods of the Iterator interface, which
allow us to check if there are more elements in the collection and retrieve the next element,
respectively. The output of this program would be:
1014
1
Note that the Iterator interface also provides a remove() method, which allows you to
remove the current element from the collection while iterating through it. This method should
only be used when iterating through a collection using an Iterator, as it may cause unexpected
behavior when used with other types of loops.
In Java, wrapper classes are classes that provide a way to represent primitive data types
(such as int, double, boolean, etc.) as objects. This is useful when you need to treat primitive
types as objects, for example when you need to pass them to methods that require objects as
arguments. Here is a list of the eight wrapper classes in Java:
1015
In this example, we create an Integer object myInt that wraps the int value 42. We then use
the toString() method of the Integer class to convert the value to a string and print it out.
Wrapper classes also provide useful methods for converting between primitive types and
objects, and for performing arithmetic and comparison operations on objects. For example:
Integer x = 5;
int y = x.intValue(); // convert Integer to int
Integer z = Integer.valueOf(y); // convert int to Integer
System.out.println(x.compareTo(z)); // compare two Integer objects
In this example, we create an Integer object x with the value 5, and then use the intValue()
method to convert it to an int value y. We then use the valueOf() method of the Integer
class to convert y back to an Integer object z. Finally, we use the compareTo() method of
the Integer class to compare x and z and print out the result.
In Java, exceptions are a way to handle errors or unexpected situations that occur during the
execution of a program. The try-catch block is a mechanism in Java for handling exceptions.
It consists of two parts:
The try block, where the code that might throw an exception is placed.
The catch block(s), where the exception is caught and handled.
try {
// code that might throw an exception
} catch (ExceptionType1 e1) {
// code to handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// code to handle exception of type ExceptionType2
} finally {
// optional code that always executes, whether or not an exception is thrown
}
1016
When an exception is thrown within the try block, the catch block is executed. If the exception
matches the type of the first catch block, that block is executed. If not, the exception is passed to
the next catch block, and so on. If no catch block matches the exception type, the exception is
not caught and the program terminates. The finally block is optional and always executes,
whether or not an exception is thrown. This block is typically used to perform cleanup tasks,
such as closing files or releasing resources, which need to be done regardless of whether an
exception occurs. Here's an example of using a try-catch block in Java:
try {
int result = 10 / 0; // this will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This code always executes");
}
In this example, the try block performs a division by zero, which will throw an
ArithmeticException. The catch block catches the exception, prints an error message, and the
program continues to execute. The finally block prints a message indicating that it always
executes.
In Java, regular expressions are a powerful tool for searching, replacing, and
manipulating text. A regular expression, also known as regex, is a pattern that describes a set of
strings. Java provides the java.util.regex package for working with regular expressions.
The two main classes in this package are Pattern and Matcher.
1017
import java.util.regex.*;
In this example, we create a Pattern object using the compile() method of the Pattern class.
The argument to compile() is the regular expression we want to match, which in this case is
the string "fox". We then create a Matcher object using the matcher() method of the Pattern
class, passing in the input string we want to search. We call the find() method of the Matcher
object to search for the pattern within the input string. If the pattern is found, the find() method
returns true, and we print a message indicating that a match was found.
1018
There are many more syntax elements available for regular expressions in Java, including
character classes, quantifiers, and special characters. Regular expressions can be complex,
but they are a powerful tool for manipulating text in Java.
In Java, threads are a mechanism for running multiple tasks concurrently within a single
program. A thread is a lightweight sub-process that can run in parallel with other threads within
the same program. In Java, threads are implemented using the java.lang.Thread class. To
create a new thread, you can either extend the Thread class and override its run() method, or
implement the Runnable interface and pass an instance of that class to a Thread object. Here's
an example of creating a new thread by extending the Thread class:
In this example, we create a new thread by extending the Thread class and overriding its run()
method. We then create an instance of this class and call its start() method. This starts a new
thread, and the code within the run() method is executed concurrently with the main thread.
Java also provides the java.util.concurrent package for working with threads and
managing concurrent access to shared resources. This package includes classes such as
1019
Executor, ThreadPoolExecutor, and FutureTask, which can be used to create and
manage threads more easily and efficiently. When working with threads, it's important to be
aware of thread synchronization issues, such as race conditions and deadlocks. Java provides
synchronization mechanisms, such as synchronized blocks and methods, to help prevent these
issues. Here's an example of using a synchronized block in Java to prevent multiple threads
from accessing a shared resource at the same time:
1020
In this example, we create a new Runnable object that contains a counter variable. We then
create two Thread objects that share the same Runnable object, and start both threads. The code
within the run() method increments the counter variable using a synchronized block, which
ensures that only one thread can access the block at a time. Finally, we wait for both threads to
finish using the join() method, and print the final value of the counter variable.
In Java, the java.io package provides classes for working with files and directories. The File
class represents a file or directory on the file system, and provides methods for creating, deleting,
reading, and writing files. Here's an example of creating a new file and writing to it in Java:
import java.io.*;
In this example, we create a new File object called "myfile.txt" using the File constructor.
We then create a FileWriter object and pass in the File object to write to the file. We write the
string "Hello, world!" to the file using the write() method of the FileWriter object, and then
1021
close the writer using the close() method. Java also provides classes for reading from files,
such as FileReader and BufferedReader. Here's an example of reading from a file using
BufferedReader:
import java.io.*;
In this example, we create a new BufferedReader object that wraps a FileReader object.
We read each line from the file using the readLine() method of the BufferedReader
object, and print it to the console using System.out.println(). We continue reading lines
until we reach the end of the file, indicated by a null return value from readLine(). Finally, we
close the reader using the close() method. Other useful methods provided by the File class
include:
1022
delete() : deletes a file or directory
mkdir() : creates a new directory
list() : returns an array of the names of files and directories in a directory
These methods can be used to perform a wide range of file and directory operations in Java.
Java has several advantages that make it a popular programming language for developing a wide
range of applications. Some of these advantages include:
1023
Multithreading: Java provides built-in support for multithreading, which allows multiple
threads to run concurrently within the same program. This can help improve program
performance by allowing tasks to be executed in parallel, and can also make it easier to
write concurrent programs that handle multiple users or tasks. For example, a Java web
application can use multithreading to handle multiple requests from different users
simultaneously.
Overall, these advantages make Java a versatile and popular programming language that can be
used for a wide range of applications, from desktop and mobile applications to web and
enterprise applications. Using Java has certain drawbacks in addition to its many benefits. The
following are some of the primary drawbacks of Java:
1024
Overhead: Java requires a significant amount of memory to run, and it can be resource-
intensive. For example, if you are running multiple Java applications on a single
machine, it can consume a significant amount of resources and slow down the system.
It's important to note that many of these disadvantages can be mitigated through careful design
and optimization of your Java applications. Additionally, Java has many advantages, such
as its portability, that may make it a better choice for some projects than other programming
languages.
Java is known for its slogan "Write Once, Run Anywhere," but some developers
joke that it really means "Write Once, Debug Everywhere."
Java was originally called "Oak" because the developers liked the oak tree outside their
office. However, when they found out that name was already trademarked, they had to
change it to "Java."
The first version of Java was released in 1996, and it included a lot of bugs. One of the
bugs was so bad that it caused the program to crash if you typed in the word "true" as a
variable name.
Some developers refer to Java as "Just Another Vague Acronym" because of the
many different interpretations of what the name means.
Java has been the subject of many jokes and memes in the programming community,
including a popular meme that shows a picture of a coffee cup with the caption "I
drink Java for breakfast."
One of the features of Java is its ability to run code in a sandbox environment, which led
to the joke that "Java is to JavaScript as ham is to hamster."
While these may be funny, it's important to remember that Java is a powerful and widely-used
programming language that has many practical applications.
1025
Java is a versatile programming language with many practical applications in a wide range of
industries. Here are some examples of applications of Java:
These are just a few examples of the many applications of Java. Its flexibility and versatility
make it a popular choice for developers across many industries.
− James Gosling
1026
PYTHON − OVERVIEW
1027
Syntax: Python has a simple and easy-to-read syntax that emphasizes readability and reduces
the cost of program maintenance. Indentation is used to indicate block structure, and there are
no semicolons or curly braces to clutter the code.
Portability: Python code can be run on many different platforms, including Windows, Mac,
Linux, and Unix, making it a highly portable language.
Overall, Python's simplicity, versatility, and ease of use make it a great choice for a wide range of
programming tasks.
print("Hello, World!")
When you run this program, it will output the message "Hello, World!" to the console. This is a
simple example of how to use the print function in Python to output text.
In Python, you can add comments to your code to make it more readable and to explain what the
code is doing. Comments are ignored by the Python interpreter, so they do not affect the
behavior of your program. Here are some examples of Python comments:
Single-line comments:
In this example, the # character indicates that the rest of the line is a comment. Anything
following the # character on the same line will be ignored by the Python interpreter.
Multi-line comments:
"""
This is a multi-line comment in Python.
It can span multiple lines and is enclosed in triple quotes.
"""
1028
In this example, the comment is enclosed in triple quotes ("""). This allows the comment to
span multiple lines. However, multi-line comments are not commonly used in Python because
single-line comments are usually sufficient. Comments can also be used to temporarily disable
code, for testing or debugging purposes. Here's an example:
In this example, the print("Hello, World!") statement is commented out. This means that
it will not be executed when the program is run. However, if you later need to re-enable the code,
you can simply remove the # characters. Comments are an important tool for making your code
more readable and understandable, both for yourself and for others who may need to read or
modify your code. By adding comments, you can explain what your code is doing, why you
made certain design decisions, and any other important information that will help others
understand your code.
In Python, variables are used to store data values. They are like containers that hold values that
can be accessed and manipulated throughout the program. Here are some examples and
explanations of variables in Python:
Numeric Variables: Numeric variables are used to store numerical values such as
integers or floating-point numbers.
x = 10
y = 3.14
In this example, x is an integer variable that stores the value 10 and y is a floating-point variable
that stores the value 3.14.
1029
String Variables: String variables are used to store text values. They are enclosed in
either single quotes ('') or double quotes ("").
In this example, name is a string variable that stores the value "John Doe" and message is a
string variable that stores the value "Hello World!".
Boolean Variables: Boolean variables are used to store boolean values, which are either
True or False.
is_python_fun = True
is_coding_hard = False
In this example, is_python_fun is a boolean variable that stores the value True and is_coding_hard
is a boolean variable that stores the value False.
List Variables: List variables are used to store a collection of values, which can be of different
data types. Lists are created by enclosing the values in square brackets [] and separating them
with commas.
1030
In this example, fruits is a list variable that stores the values 'apple', 'banana', and 'orange' and
numbers is a list variable that stores the values 1, 2, 3, 4, and 5.
In Python, a dictionary is a collection of key-value pairs. It is a built-in data type that is commonly used
to store and manipulate data in a flexible and efficient way. Here are some examples of dictionary
variables in Python:
Output:
In this example, we're creating a dictionary variable called person that contains three key-
value pairs. The keys are "name", "age", and "city", and the corresponding values are "John
Doe", 30, and "New York".
Output:
John Doe
30
1031
In this example, we're accessing the values of the "name" and "age" keys in the person dictionary
using square bracket notation. The values are then printed to the console.
Output:
In this example, we're updating the value of the "age" key in the person dictionary from 30 to 31
using square bracket notation. The updated dictionary is then printed to the console.
Output:
{'name': 'John Doe', 'age': 30, 'city': 'New York', 'state': 'New York'}
In this example, we're adding a new key-value pair to the person dictionary using square bracket
notation. The new key is "state" and the value is "New York". The updated dictionary is then
printed to the console.
1032
Example 5: Deleting a Key-Value Pair from a Dictionary
Output:
In this example, we're deleting the key-value pair for the "city" key in the person dictionary
using the del statement. The updated dictionary without the "city" key is then printed to the
console. These are just a few examples of variables in Python. Variables can hold many
different types of values and can be manipulated in various ways throughout a program.
In Python, there are three main types of numerical data: integers, floating-point numbers, and
complex numbers.
1. Integers: Integers are whole numbers, which means they do not have decimal points.
They can be positive, negative, or zero. Integers in Python are of type 'int'. For
example:
x = 5
y = -10
z = 0
1033
a = 3.14
b = -2.5
c = 0.0
Complex numbers: Complex numbers are numbers with both real and imaginary parts. They are
expressed in the form a + bj, where a and b are real numbers and j is the imaginary unit (square
root of -1). Complex numbers in Python are of type 'complex'. For example:
d = 2 + 3j
e = -4j
f = 1.5 - 2j
Here are some examples of using these types of numerical data in Python:
# Integer arithmetic
x = 5
y = 3
print(x + y) # Output: 8
print(x - y) # Output: 2
print(x * y) # Output: 15
print(x / y) # Output: 1.6666666666666667
print(x // y) # Output: 1 (integer division)
print(x % y) # Output: 2 (modulus or remainder)
# Floating-point arithmetic
a = 3.14
b = 2.0
print(a + b) # Output: 5.14
print(a - b) # Output: 1.14
1034
print(a * b) # Output: 6.28
print(a / b) # Output: 1.57
# Complex arithmetic
d = 2 + 3j
e = -4j
print(d + e) # Output: (2-1j)
print(d - e) # Output: (2+5j)
print(d * e) # Output: (-12+8j)
print(d / e) # Output: (0.75-0.5j)
In addition to the basic arithmetic operations shown above, Python provides many built-in
functions for working with numerical data. Here are some commonly used functions:
print(abs(-5)) # Output: 5
print(abs(5)) # Output: 5
print(round(3.14159)) # Output: 3
print(round(3.14159, 2)) # Output: 3.14
1035
print(min(1, 2, 3)) # Output: 1
print(min(-1, -2, -3)) # Output: -3
import math
print(math.sqrt(16)) # Output: 4.0
import math
print(math.floor(3.7)) # Output: 3
import math
print(math.ceil(3.7)) # Output: 4
import random
print(random.random()) # Output: a random float between 0 and 1
1036
These are just a few examples of the many built-in functions available for working with
numerical data in Python.
In Python, casting refers to the process of converting one data type to another. Here are some
examples of casting in Python:
x = 5.7
print(int(x)) # Output: 5
x = 5
print(float(x)) # Output: 5.0
x = 5
print(str(x)) # Output: "5"
x = 0
print(bool(x)) # Output: False
x = (1, 2, 3)
print(list(x)) # Output: [1, 2, 3]
1037
tuple(): Converts a sequence to a tuple.
x = [1, 2, 3]
print(tuple(x)) # Output: (1, 2, 3)
x = [1, 2, 3, 2]
Casting is useful when you need to convert data from one type to another. For example, you
may need to convert a string input to a numeric type in order to perform mathematical operations
on it. Casting can also be used to convert data between Python's built-in data structures, such
as lists and tuples, or to convert data between different types of collections, such as converting a
sequence to a set.
In Python, a string is a sequence of characters enclosed in either single quotes (' ') or double
quotes (" "). Strings are a fundamental data type in Python and are widely used in
programming. Here are some examples of strings:
1038
In the examples above, string1 and string2 are string literals that contain alphanumeric
characters and punctuation. string3 is a string that contains only digits. Python strings support
several operations such as indexing, slicing, concatenation, repetition, and more. Let's discuss
some of these operations in more detail below:
Indexing
Indexing allows you to access individual characters in a string. The index of the first character is
0, and the index of the last character is -1. You can use square brackets to specify the index of
the character you want to access.
Slicing
Slicing allows you to extract a portion of a string. You can specify a range of indices to extract
using the start:end syntax. The start index is inclusive, and the end index is exclusive.
Concatenation
Concatenation allows you to join two or more strings together using the + operator.
1039
Repetition
Repetition allows you to repeat a string multiple times using the * operator.
Length
You can find the length of a string using the len() function.
Formatting
String formatting allows you to insert values into a string using placeholders. There are several
ways to do string formatting in Python, but the most common method is to use the .format()
method.
name = 'Alice'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))
# Output: 'My name is Alice and I am 25 years old.'
Overall, strings are a powerful and versatile data type in Python that can be used to
manipulate and store text data.
Python operators are special symbols that carry out operations on variables and values. Python
provides various types of operators, including arithmetic operators, comparison operators, logical
operators, and assignment operators. Here's a brief overview of Python operators:
1040
Arithmetic Operators: These are used to perform mathematical operations, such as
addition, subtraction, multiplication, division, modulus, exponentiation, and floor
division. Examples include +, -, *, /, %, **, and //.
Comparison Operators: These are used to compare two values and return a boolean
value (True or False). Examples include ==, !=, >, <, >=, and <=.
Logical Operators: These are used to combine or invert boolean expressions. Examples
include and, or, and not.
Assignment Operators: These are used to assign a value to a variable. Examples
include =, +=, -=, *=, /=, %=, and //=.
Bitwise Operators: These are used to perform bitwise operations on integers. Examples
include &, |, ^, ~, <<, and >>.
Membership Operators: These are used to test if a value is a member of a sequence.
Examples include in and not in.
Identity Operators: These are used to test if two variables point to the same object.
Examples include is and is not.
You can use these operators in your Python code to perform various operations on variables and
values. For example:
a = 5
b = 2
print(a + b) # Output: 7
print(a - b) # Output: 3
print(a * b) # Output: 10
print(a / b) # Output: 2.5
print(a % b) # Output: 1
print(a ** b) # Output: 25
print(a // b) # Output: 2
1041
a = 5
b = 2
a = 5
b = 2
c = 0
if 'pear' in fruits:
print("Yes, pear is in the fruits list.")
else:
print("No, pear is not in the fruits list.")
1042
# Using the `not in` operator
if 'pineapple' not in fruits:
print("Yes, pineapple is not in the fruits list.")
else:
print("No, pineapple is in the fruits list.")
In the first example, we check if 'banana' is in the fruits list using the in operator, and it
returns True. In the second example, we check if 'pear' is in the fruits list using the in
operator, and it returns False, so we print "No, pear is not in the fruits list." In the third example,
we check if 'pineapple' is not in the fruits list using the not in operator, and it returns True.
In the fourth example, we check if 'orange' is not in the fruits list using the not in operator,
and it returns False, so we print "No, orange is in the fruits list."
In Python, a list is an ordered collection of items or elements that can be of any data type. Lists
are defined using square brackets [ ] and each item in the list is separated by a comma. For
example:
my_list = [1, 2, 3, 4, 5]
1043
Lists are mutable, which means that their values can be changed after they are created. You can
add, remove, or modify items in a list. Here are some examples of common operations you
can perform on lists:
Accessing Elements: You can access individual elements of a list using their index,
which starts at 0. For example:
print(my_list[0]) # Output: 1
Slicing: You can also access a subset of elements in a list using slicing. Slicing uses a
colon (:) to separate the start and end indices. For example:
Appending Elements: You can add new elements to the end of a list using the
append() method. For example:
my_list.append(6)
Removing Elements: You can remove elements from a list using the remove() method.
For example:
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5, 6]
Checking if an Element is in a List: You can check if an element is in a list using the in
keyword. For example:
1044
Lists are a very powerful data structure in Python and are used extensively in many different
applications.
In Python, a tuple is an ordered, immutable collection of elements that can contain any type of
data. Tuples are created using parentheses () and each element is separated by a comma. Here
is an example of creating a tuple:
Tuples can also be created without parentheses, by simply separating the elements with commas:
Tuples are immutable, which means that once a tuple is created, its elements cannot be
changed. However, if a tuple contains mutable objects like lists, the objects inside the tuple can
be modified. Tuples can be accessed using indexing, which starts from 0. Here's an example
of accessing the first element of a tuple:
first_element = my_tuple[0]
Tuples also support slicing, which allows you to extract a portion of the tuple. Here's an
example of getting the first two elements of a tuple:
first_two_elements = my_tuple[:2]
1045
Tuples support several built-in methods like count() and index(). The count() method
returns the number of times a specified element appears in the tuple, while the index() method
returns the index of the first occurrence of a specified element in the tuple.
Tuples are often used to group related data together. For example, a tuple can be used to
represent a point in a 2D coordinate system:
point = (3, 4)
def get_name_and_age():
name = 'John'
age = 30
return name, age
In the above example, the function get_name_and_age() returns a tuple containing the name
and age. These values are then assigned to the variables name and age using tuple unpacking.
Python sets are a built-in data structure that allows you to store a collection of unique
elements. The elements of a set can be of any immutable data type, such as numbers, strings, or
tuples. The syntax for creating a set is to enclose a comma-separated list of elements in curly
braces ({}) or by using the set() constructor function. For example:
1046
# create a set using curly braces
my_set = {1, 2, 3, 4, 5}
Note that when creating an empty set, you must use the set() constructor, as {} creates an
empty dictionary in Python. Some of the key characteristics of sets are:
1. Sets only store unique elements: If you try to add an element to a set that already exists
in the set, it will be ignored.
2. Sets are unordered: Unlike lists and tuples, sets do not maintain any particular order for
their elements.
3. Sets are mutable: You can add and remove elements from a set after it has been created.
Here are some common operations you can perform with sets in Python:
Adding elements to a set: You can add elements to a set using the add() method.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # outputs {1, 2, 3, 4}
Removing elements from a set: You can remove elements from a set using the
remove() method.
my_set = {1, 2, 3, 4}
my_set.remove(4)
print(my_set) # outputs {1, 2, 3}
1047
Checking if an element is in a set: You can use the in keyword to check if an element
is in a set.
my_set = {1, 2, 3}
print(2 in my_set) # outputs True
print(4 in my_set) # outputs False
Combining sets: You can combine two sets using the union() method or the |
operator.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # outputs {1, 2, 3, 4, 5}
Finding the intersection of sets: You can find the common elements between two sets
using the intersection() method or the & operator.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # outputs {3}
1048
Finding the difference between sets: You can find the elements that are in one set but
not in the other using the difference() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # outputs {1, 2}
In this example, set1 contains the elements {1, 2, 3} and set2 contains the elements {3,
4, 5}. The difference() method is called on set1 with set2 passed as an argument. This
returns a new set containing the elements that are in set1 but not in set2, which in this case is
{1, 2}. Alternatively, you can use the - operator to find the difference between sets:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
In this example, the "-" operator is used to subtract set2 from set1, which produces the same
result as using the difference() method.
A dictionary in Python is a collection of key-value pairs, where each key is unique and
associated with a value. It is also known as an associative array, hash map or a hash table in
other programming languages. In Python, dictionaries are created using curly braces {} or the
dict() constructor function. The keys and values in a dictionary can be of any data type,
including strings, integers, floats, lists, or even other dictionaries. However, keys must be
1049
immutable types such as strings, numbers or tuples. Here's an example of how to create a
dictionary in Python:
To access a value in a dictionary, you can use the key inside square brackets:
# modify a value
my_dict['key2'] = 'new_value2'
Dictionaries also have several built-in methods to perform common operations, such as getting a
list of keys or values:
1050
# get a list of keys
my_dict.keys()
Overall, dictionaries are a powerful data structure in Python that allow you to store and
manipulate data in a flexible and efficient way.
In Python, if...else is a conditional statement that allows you to execute certain blocks of
code based on whether a condition is true or false. The basic syntax of an if...else statement
in Python is:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
The condition is a Boolean expression that evaluates to either True or False. If the
condition is True, the code block inside the if statement is executed, and if the condition
is False, the code block inside the else statement is executed. Here's an example:
age = 18
1051
In this example, if the value of age is greater than or equal to 18, the message "You are an
adult." will be printed to the console. Otherwise, the message "You are not an adult yet." will be
printed. You can also add more conditions to your if...else statement using elif (short for
"else if"):
age = 18
In this example, if the value of age is less than 18, the message "You are not an adult yet." will
be printed. If age is greater than or equal to 18 but less than 30, the message "You are a young
adult." will be printed. And if age is greater than or equal to 30, the message "You are an adult."
will be printed. if...else statements can also be nested inside other if...else statements to
create more complex conditions. However, it's important to keep the code readable and not to
create excessively nested statements. Overall, if...else statements are a fundamental control
structure in Python that allow you to make decisions based on conditions and execute code
accordingly.
In Python, loops are used to execute a block of code repeatedly, based on a specific condition
or range of values. There are two main types of loops in Python: for loops and while loops.
For Loops
A for loop is used to iterate over a sequence of values (such as a list, tuple or string) or a
range of numbers. The basic syntax of a for loop in Python is:
1052
for variable in sequence:
# code to execute
Here's an example of a for loop that iterates over a list of names and prints each name to the
console:
Alice
Bob
Charlie
You can also use the range() function to generate a sequence of numbers to iterate over:
for i in range(5):
print(i)
0
1
2
3
4
1053
While Loops
A while loop is used to execute a block of code repeatedly as long as a condition is true.
The basic syntax of a while loop in Python is:
while condition:
# code to execute
Here's an example of a while loop that counts from 0 to 4 and prints each number to the
console:
i = 0
while i < 5:
print(i)
i += 1
0
1
2
3
4
You need to be careful with while loops, because if the condition is never met, the loop will
continue to run indefinitely, causing what's known as an infinite loop. You can use break and
continue statements to control the flow of the loop and exit early if necessary.
In addition to break and continue, there are other loop control statements you can use in Python:
1054
break: exits the loop immediately, skipping any remaining iterations.
continue: skips the current iteration and goes to the next one.
pass: does nothing, used as a placeholder when a statement is required but you don't
want to execute any code.
for i in range(10):
if i == 5:
break
elif i % 2 == 0:
continue
else:
print(i)
The loop starts at 0 and goes up to 9. When i is equal to 5, the break statement is executed,
and the loop exits early. When i is even, the continue statement is executed, and the loop skips
the rest of the code and goes to the next iteration. Otherwise, the loop prints the value of i.
Overall, loops are a fundamental concept in programming that allows you to execute code
repeatedly and perform complex operations on large datasets.
1055
A function in Python is a self-contained block of code that performs a specific task. It takes
input(s) (if any), processes the input(s), and produces output(s) (if any). In Python, a function is
defined using the def keyword followed by the function name, input parameters (if any), and a
colon (:). The body of the function is indented and contains the code to be executed when the
function is called. Here is a simple example of a function that takes two input parameters,
adds them together, and returns the result:
In this example, add_numbers is the function name, x and y are the input parameters, result
is a variable that holds the sum of x and y, and return result specifies the output of the
function. To call this function, you simply provide values for x and y in the parentheses:
sum = add_numbers(5, 3)
print(sum) # Output: 8
This will call the add_numbers function with x = 5 and y = 3, and assign the result (8) to
the variable sum. The print statement will then output the value of sum. Functions can also
have optional parameters, default values, and can return multiple values using tuples. They
can also be used to encapsulate complex operations and simplify the code by breaking it down
into smaller, reusable components.
A lambda function in Python is a small anonymous function that can have any number of
parameters, but can only have one expression. The syntax for creating a lambda function is to use
the lambda keyword followed by the parameters (if any) separated by commas, followed by a
1056
colon, and then the expression. Here is a simple example of a lambda function that takes two
parameters and returns their sum:
sum = lambda x, y: x + y
In this example, lambda is the keyword used to define the function, x and y are the parameters,
and x + y is the expression that is evaluated when the function is called. Lambda functions
are often used as a way to define small, one-off functions that can be passed as arguments to
other functions. For example, you can use a lambda function to define the key parameter for
sorting a list:
numbers = [5, 1, 3, 6, 2, 8, 4]
sorted_numbers = sorted(numbers, key=lambda x: x)
print(sorted_numbers) # Output: [1, 2, 3, 4, 5, 6, 8]
In this example, the sorted function is called with numbers as the first argument and a
lambda function as the second argument. The lambda function takes a single parameter x and
returns x, which is used as the sorting key. Lambda functions are also used in functional
programming paradigms, where they can be used to define higher-order functions that take other
functions as parameters or return functions as values.
In Python, a class is a blueprint for creating objects. An object is an instance of a class that
contains data (attributes) and functions (methods). Here is an example of a class in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
1057
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
In this example, Person is the name of the class. The __init__ method is a special method
called the constructor, which is called when an object is created. The constructor takes two
parameters, name and age, which are used to initialize the name and age attributes of the
object. The greet method is a function that takes no parameters and prints a message that
includes the name and age attributes of the object. To create an object of the Person class, you
would use the following syntax:
This creates a new object of the Person class with the name attribute set to "Alice" and the age
attribute set to 25. You can access the attributes and methods of an object using the dot (.)
operator. For example:
In this example, the name attribute of the person object is accessed using the dot operator, and
the greet method is called on the person object. Classes and objects are a fundamental
concept in object-oriented programming (OOP), which is a programming paradigm that
emphasizes the use of classes and objects to model real-world entities and their relationships.
OOP provides a way to encapsulate data and behavior into reusable and modular components,
which makes it easier to write and maintain complex software systems.
1058
In Python, an iterator is an object that can be iterated (looped) upon. An iterator is an
implementation of the iterator protocol, which requires the iterator to have two methods:
__iter__() and __next__(). The __iter__() method returns the iterator object itself, and
the __next__() method returns the next value in the iteration sequence. When there are no
more items to return, the __next__() method should raise the StopIteration exception.
Here is an example of an iterator in Python:
class MyIterator:
def __init__(self):
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter < 5:
self.counter += 1
return self.counter
else:
raise StopIteration
In this example, MyIterator is a class that implements an iterator. The __init__() method
initializes the counter attribute of the iterator to 0. The __iter__() method returns the
iterator object itself, and the __next__() method returns the next value in the iteration
sequence. In this example, the iteration sequence consists of the numbers from 1 to 5. The
__next__() method checks if the counter attribute is less than 5. If it is, it increments the
counter attribute and returns its value. If the counter attribute is equal to or greater than 5, it
raises the StopIteration exception to indicate that there are no more items in the iteration
sequence. To use an iterator, you can use a for loop or the built-in next() function. For
example:
1059
my_iterator = MyIterator()
In this example, the MyIterator class is instantiated as my_iterator. The for loop and
next() function are used to iterate over the values returned by the MyIterator object.
Iterators are used extensively in Python, especially with built-in functions such as range(),
map(), and filter().
In Python, JSON (JavaScript Object Notation) is a popular data interchange format that is used to
represent data structures as text. JSON is a lightweight format that is easy for humans to read
and write, and easy for machines to parse and generate. The Python standard library provides
two modules for working with JSON:
json: This module provides methods for encoding Python objects as JSON strings and
decoding JSON strings into Python objects.
simplejson: This is a third-party module that provides a more feature-rich JSON
implementation than the built-in json module.
Here is an example of how to use the json module to encode and decode JSON data in Python:
1060
import json
In this example, the json.dumps() method is used to encode a Python dictionary as a JSON
string, and the json.loads() method is used to decode a JSON string into a Python
dictionary. JSON supports a limited set of data types, including strings, numbers, boolean
values, null, arrays, and objects. When encoding Python objects as JSON data, the json module
automatically converts compatible data types to their JSON equivalents. Here is an example of
encoding a Python object with the json module:
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
1061
In this example, a custom Python object of the Person class is created and encoded as a JSON
string using the json.dumps() method. The __dict__ attribute is used to convert the object's
attributes to a dictionary that can be encoded as JSON. JSON is commonly used in web
development for exchanging data between client and server, as well as in data storage and
transfer applications.
In Python, try and except are used for error handling. The basic idea is to try a block of code
that may raise an exception (i.e., an error), and then handle that exception if it occurs. Here's the
basic syntax:
try:
# code that may raise an exception
except ExceptionType:
# code to handle the exception
The try block contains the code that you want to execute, and the except block contains the
code that should be executed if an exception of type ExceptionType occurs. If an exception
occurs in the try block, Python will jump to the except block and execute its code. You can
use multiple except blocks to handle different types of exceptions. For example:
try:
# code that may raise an exception
except TypeError:
# code to handle a TypeError exception
except ValueError:
# code to handle a ValueError exception
1062
If the code in the try block raises a TypeError exception, the first except block will be
executed. If it raises a ValueError exception, the second except block will be executed. You
can also include a finally block, which will be executed regardless of whether an exception
occurred or not. For example:
try:
# code that may raise an exception
except ExceptionType:
# code to handle the exception
finally:
# code that should be executed regardless of whether an exception occurred or not
The finally block will be executed after the try and except blocks, regardless of whether an
exception occurred or not. This is useful for cleaning up resources or closing files, for example.
Overall, try and except are an important part of Python error handling, allowing you to
gracefully handle errors and prevent your code from crashing.
In Python, pip is a package manager used to install and manage software packages written in
Python. It makes it easy to install and uninstall Python packages, as well as manage
dependencies between packages. pip is included with most Python installations by default, and
can be accessed from the command line by typing pip followed by a command. Here are some
common pip commands:
pip install package_name: installs a package from the Python Package Index
(PyPI) or another package repository.
pip uninstall package_name: uninstalls a package.
pip list: lists all installed packages.
pip freeze: lists all installed packages in a format that can be used to
create a requirements.txt file, which is commonly used to specify the
dependencies of a Python project.
1063
pip search package_name: searches for a package on PyPI or another package
repository.
You can also use pip to install packages from a requirements.txt file using the following
command:
This will install all the packages listed in the requirements.txt file. In addition to the standard
pip command, there are several third-party tools and libraries that extend or enhance its
functionality, such as virtualenv and conda. These tools allow you to create isolated Python
environments with their own package installations, making it easy to manage dependencies
between projects and avoid conflicts between different packages.
In Python, file handling refers to the process of working with files on the file system, such
as reading from or writing to a file. Python provides a built-in open() function to work with
files. Here's how to open a file for reading:
f = open("filename.txt", "r")
This opens the file filename.txt in read mode. The open() function returns a file object,
which you can use to read data from the file. To read the entire contents of the file, you can use
the read() method:
data = f.read()
After you're done reading from the file, you should close it using the close() method:
f.close()
1064
Here's how to open a file for writing:
f = open("filename.txt", "w")
This opens the file filename.txt in write mode. To write data to the file, you can use the
write() method:
f.write("Hello, world!")
After you're done writing to the file, you should close it using the close() method:
f.close()
It's a good practice to always close files after you're done working with them. Alternatively, you
can use a "with" statement to automatically close the file when you're done with it:
This automatically closes the file after the "with" block is finished, even if an error occurs. In
addition to reading and writing files, you can also append to an existing file using the "a" mode,
or read and write to a file simultaneously using the "r+" or "w+" modes. For more information,
check out the Python documentation on file handling:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
Python is a popular programming language for data analysis and manipulation tasks. It provides
a variety of libraries and frameworks that can be used to work with different databases, including
MySQL. MySQL is an open-source relational database management system that is widely used in
web applications. It uses SQL (Structured Query Language) to interact with the database
1065
and perform various operations like insert, update, delete, and retrieve data. To work with
MySQL in Python, you can use a Python MySQL connector library like mysql-connector-
python, PyMySQL, or MySQLdb. These libraries provide a set of methods and classes to connect
to a MySQL database, execute SQL queries, and fetch data from the database. Here is a brief
overview of how to work with MySQL in Python:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
1066
result = mycursor.fetchall()
You can also perform other operations like insert, update, and delete data using SQL queries in Python.
Overall, Python provides an easy and flexible way to work with MySQL databases, making it a popular
choice for data analysis and web development tasks.
Python has become the go-to language for many data scientists due to its simplicity, versatility,
and powerful libraries and frameworks. Python provides a wide range of libraries and frameworks for
data analysis and manipulation, including NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Keras,
and many more. These libraries and frameworks provide various functionalities such as data
manipulation, visualization, statistical analysis, machine learning, and deep learning.
1067
TensorFlow supports various neural network architectures and allows efficient computation on
GPUs.
Keras is a high-level neural networks API built on top of TensorFlow. It provides a simplified
interface for building and training deep learning models, making it easy for beginners to get
started with deep learning.
Overall, Python provides a comprehensive set of libraries and tools for data science and analytics,
making it a popular choice for data scientists and analysts. With its simplicity, versatility, and powerful
libraries and frameworks, Python has become the go-to language for data science and analytics tasks.
Advantages of Python:
1. Easy to Learn and Use: Python has a simple and easy-to-read syntax, making it easy for
beginners to learn and write code. It has a large standard library and many third-party
libraries that can be easily installed and used in Python programs. Example: Here's a
simple Python program that prints "Hello, World!" to the console:
print("Hello, World!")
2. Versatility: Python is a versatile language that can be used for a wide range of tasks,
including web development, data analysis, machine learning, and more. Example: Here's
a simple Python program that calculates the sum of two numbers:
a = 2
b = 3
c = a + b
print(c)
3. Large Community: Python has a large and active community of developers, which
means there are plenty of resources, tutorials, and documentation available online.
Example: The Python community has developed many useful libraries and frameworks
1068
for various tasks, such as NumPy for numerical computing, Pandas for data analysis, and
Flask for web development.
4. Cross-platform: Python is a cross-platform language, which means it can run on
different operating systems like Windows, Mac, and Linux. Example: Here's a simple
Python program that prints the current time on different platforms:
import datetime
current_time = datetime.datetime.now()
print(current_time)
Disadvantages of Python:
1. Speed: Python is an interpreted language, which means it can be slower than compiled
languages like C++ or Java. Example: If you have a Python program that performs
complex mathematical operations on large datasets, it may take longer to execute than the
same program written in a compiled language.
2. Weak in Mobile Computing: Python is not well-suited for mobile computing, as it
requires a large runtime environment and may not be optimized for mobile devices.
Example: If you want to develop a mobile app that requires high performance and low
memory usage, you may want to consider using a different language like Swift or
Kotlin.
3. Not Ideal for Memory-intensive Tasks: Python is not ideal for memory-intensive tasks,
as it has limitations in managing memory efficiently. Example: If you want to develop a
program that requires large amounts of memory, like a video game or a scientific
simulation, you may want to consider using a different language like C++ or Fortran.
4. Not Ideal for Real-time Applications: Python is not ideal for real-time applications, as
it has limitations in handling time-critical tasks. Example: If you want to develop a
program that requires real-time performance, like a trading system or a control system,
you may want to consider using a different language like C or Rust.
1069
Here is a brief comparison of C, C++, Java, and Python:
C:
A low-level programming language used for system programming, embedded systems, and operating
systems.
Provides direct memory access and low-level control over hardware resources.
Does not support object-oriented programming (OOP) and automatic memory management.
C++:
Java:
Python:
In terms of performance, C and C++ are generally faster than Java and Python, but they require more manual
memory management and may have longer development times. Java and Python are generally easier to learn and
use, and are popular for their cross-platform capabilities and large communities of developers. Ultimately, the
choice of programming language depends on the specific project requirements, development resources, and
personal preferences of the developers involved.
Best Linux Books that Every Superuser Should Read:
Linux in a Nutshell
Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security
in Kali
Book by OccupyTheWeb
Linux Command Line and Shell Scripting Bible
Linux Administration: The Linux Operating System and Command Line Guide for
Linux Administrators
Linux Bible
Linux administration
Linux Essentials
example in the sense that it shows you can set people to work in
− James Surowiecki
Best Programming Books that Every Programmer Should Read:
C:
Head First C
Expert C Programming
Book by K. N King
Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep
Avoiding (Like C)
Let Us C
A Book on C: Programming in C
Extreme C: Taking You to the Limit in Concurrency, OOP, and the Most Advanced
Capabilities of C
Book by Kamran Amini
Let Us C Solutions
Introduction to C Programming
C - In Depth
C How to Program
Understanding Pointers In C & C++: Fully Working Examples and Applications of Pointers
C++:
C++ Primer
A Tour of C++
More Effective C++: 35 New Ways To Improve Your Programs And Designs
C++ Programming
Book by D. S. Malik
Professional C++
C++ High Performance: Master the Art of Optimizing the Functioning of Your C++ Code
Data Parallel C++: Mastering DPC++ for Programming of Heterogeneous Systems using
Book by James Brodman, Michael Kinsner, Xinmin Tian, Ben Ashbaugh, John Pennycook,
James Reinders
Modern CMake for C++: Discover a Better Approach to Building, Testing, and Packaging
Your Software
Expert C++: Become a Proficient Programmer by Learning Coding Best Practices with
Learn C++ Quickly: A Complete Beginner's Guide to Learning C++, Even If You're New to
Programming
Hands-On Design Patterns with C++: Solve Common C++ Problems with Modern Design
JAVA:
Effective Java
Thinking in Java
Book by Bruce Eckel
Core Java
Test Driven: Practical TDD and Acceptance TDD for Java Developers
Spring in Action
Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D
Java Performance: The Definitive Guide: Getting the Most Out of Your Code
OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
Java Performance
PYTHON:
Fluent Python
Learn Python the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful
Automate the Boring Stuff with Python: Practical Programming for Total Beginners
Book by Al Sweigart
Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython
Learning Python
Book by Al Sweigart
Python Data Science Handbook: Essential Tools for Working with Data
Python in a nutshell
Book by Al Sweigart
Python Programming for the Absolute Beginner
The Python Bible 7 in 1: Volumes One To Seven (Beginner, Intermediate, Data Science,
Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities
Learn More Python 3 the Hard Way: The Next Step for New Python Programmers
HTML:
Book by Jo Foster
Textbook by M. G. Martin
CSS:
CSS in Depth
CSS mastery
Learn CSS in One Day and Learn It Well: CSS for Beginners With Hands-On Project
CSS Master
JAVASCRIPT:
JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language
Programming JavaScript Applications: Robust Web Architecture with Node, HTML5, and
Modern JS Libraries
JavaScript Enlightenment
Beginning JavaScript
JavaScript Patterns
Object-Oriented JavaScript
Maintainable JavaScript
Book by Nicholas C. Zakas
DOM Enlightenment
Testable JavaScript
Book by Al Sweigart
The Road to Learn React: Your Journey to Master Plain Yet Pragmatic React. Js
Learning TypeScript
Functional Techniques
PHP:
The Joy of PHP: A Beginner's Guide to Programming Interactive Web Applications with
Learning PHP, MySQL, JavaScript, CSS and HTML5: A Step-by-Step Guide to Creating
Dynamic Websites
Programming PHP
Book by Rasmus Lerdorf
PHP and MySQL: Novice to Ninja: Get Up to Speed With PHP the Easy Way
Learning PHP, MySQL & JavaScript: With JQuery, CSS & HTML5
PHP and MySQL in easy steps, 2nd Edition: Updated to cover MySQL 8.0
Mastering PHP 7
PHP 8 Programming Tips, Tricks and Best Practices: A Practical Guide to PHP 8 Features,
PHP: Learn PHP in One Day and Learn It Well. PHP for Beginners with Hands-on Project
PHP Cookbook
Drupal 9 Module Development: Get Up and Running with Building Powerful Drupal
WordPress Complete
Learning PHP 7
Mastering The Faster Web with PHP, MySQL, and JavaScript: Develop State-of-the-art
PHP Microservices
Professional CodeIgniter
PHP Programming for Beginners: Key Programming Concepts. How to use PHP with
ALGORITHMS:
Introduction to Algorithms
Grokking Algorithms: An Illustrated Guide for Programmers and Other Curious People
Book by Aditya Bhargava
Algorithms
Algorithm Design
Algorithms in a nutshell
Data structures and algorithms made easy in Java: data structure and algorithmic puzzles
Programming Skills
Contests
Algorithms Unlocked
The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake
Our World
Spies, Lies, and Algorithms: The History and Future of American Intelligence
Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services
A Programmer's Guide to Computer Science: A virtual degree for the self-taught developer
Concrete Mathematics
Textbook by Donald Knuth, Oren Patashnik and Ronald Graham
DATA STRUCTURES:
Book by J. R Hubbard
Java Structures
LINUX:
Linux bible
Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali
Book by OccupyTheWeb
Linux Administration: The Linux Operating System and Command Line Guide for Linux
Administrators
Linux in a Nutshell
Learn Linux Quickly: A Beginner-friendly Guide to Getting Up and Running with the
World's Most Powerful Operating System
The Ultimate Kali Linux Book: Perform Advanced Penetration Testing Using Nmap,
Metasploit, Aircrack-Ng, and Empire
Programming
Linux Kernel Debugging: Leverage Proven Tools and Advanced Techniques to Effectively
Bash cookbook
Linux for Beginners: A Practical and Comprehensive Guide to Learn Linux Operating
Kali Linux Hacking: A Complete Step by Step Guide to Learn the Fundamentals of Cyber
Bash Pocket Reference: Help for Power Users and Sys Admins
DATABASE:
Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and
Maintainable Systems
Database Internals: A Deep Dive Into How Distributed Data Systems Work
Database Design and Relational Theory: Normal Forms and All That Jazz
Book by Christopher J. Date
Learning SQL
Foundations of databases
Pro SQL Server Relational Database Design and Implementation: Best Practices for
Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement
Refactoring databases
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and
SQL Cookbook
SQL Queries for Mere Mortals: A Hands-on Guide to Data Manipulation in SQL
Performance
build bigger and better idiot-proof programs, and the Universe trying to
− Andrew Hunt
One final thought:
If you feel that this information has been useful to you, please take a
moment to share it with your friends on LinkedIn, Facebook and
Twitter. Consider writing a brief review on Google Play Books if you
feel that this book has helped you in your programming career and you
have learned something worthwhile.
Thank you!