Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
447 views

Manjunath R. Linux Commands, C, C++, Java and Python Exercises For Beginners 2022

Uploaded by

Tica Bogdan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
447 views

Manjunath R. Linux Commands, C, C++, Java and Python Exercises For Beginners 2022

Uploaded by

Tica Bogdan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 931

LINUX COMMANDS, C, C++,

JAVA AND PYTHON EXERCISES


FOR DEGINNERS
MANJUNATH.R
Linux Commands, C, C++, Java and Python Exercises For Beginners

(Practical Exercises For Learners)

"The only true wisdom is in knowing you know nothing."

- Socrates

Manjunath.R

#16/1, 8th Main Road, Shivanagar, Rajajinagar, Bangalore560010, Karnataka, India

*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.

For any suggestions or concerns, please write to me: manjunath5496@gmail.com

© Copyright 2019 Manjunath.R

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike


4.0 International License.

(CC BY-NC-SA 4.0)

Under the terms of the cc-4.0-by license, you may:

• Share - copy and distribute the content in any form or media


• Remix, alter, and build upon the content for any non-commercial objective

As long as you comply by the conditions of the license, the licensor cannot revoke these rights.

You have to

• Provide proper recognition;


• Cite the license by including a link to it (https://creativecommons.org/licenses/by-nc-sa/4.0/);
and
• Specify whether (and if so, which) changes were made from the original.
Dedication

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:

• Making a file backup


• Get rid of the irritating emails
• Completing online forms

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.

• Educational institutions are teaching it


• Corporate societies are employing it
• Pupils need it
• (Pedagogues desire it... ;)
• (Coders perceive it... :)
Have Fun!

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:

• Linux version used: CentOS Linux release 7.3.1611 (Core)


• Python version used: 3.7.3
The Basic Programming Principles That Every Programmer Should Know:

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.
"The computer programmer is a creator of universes for which he alone is the lawgiver. No playwright,

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

Python Artificial Intelligence, Deep learning and Machine Learning


JavaScript Rich Interactive Web Development
Java Enterprise Application Development
R Data Analysis
C/C++ Operating Systems and System Tools
Golang Server-Side Programming
C# Application and Web Development Using .NET
PHP Web Development
SQL Database Management
Swift For Mobile Application Development on iOS
How much time does it take to become a good programmer?

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++ Exercises 446

Java Exercises 575

Python Exercises 721

"A language that doesn't affect the

way you think about programming

is not worth knowing."

— 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

• Principle of Modularity: A system should be composed of several components that are


joined, collaborate well, and have clearly defined functions
• Principle of Clarity: Clearness is better than smartness
• Principle of Composition: Create software that can communicate with other software
• Principle of Separation: Programming mechanisms and rules should be kept distinct.
Keep front-end interfaces and back-end engines separate
• Principle of Simplicity: Build for simplicity and only add complexity where necessary
• Principle of Parsimony: Only write a large program when it is clear by demonstration
that nothing else will work
• Principle of Transparency: Design with visibility in view to simplify analysis and
troubleshooting
• Principle of Robustness: Transparency and ease of use produce robustness
• Principle of Representation: Create programs easier to understand for any programmer
involved in the project so that it can be maintained

When offered the choice, programmers should choose to


complicate the data rather than the procedural logic of
the software because complex data is simpler for us to
understand than complex logic

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."

~ Unix for Dummies, 2nd Edition

Linux Commands

Description:

Display system date and time.

Command:

date

Description:

Display calendar.

Command:

cal

6
Description:

Display date, time and calendar.

Command:

date & cal

Description:

Display August month 2016 year calendar.

Command:

cal 8 2016

Description:

Used to clear the terminal window.

Command:

clear

Description:

Exit from the terminal window.

Command:

exit

7
Description:

Display free and used system memory.

Command:

free

Description:

Display free and used system memory in bytes.

Command:

free -b

Description:

Display free and used system memory in kilobytes.

Command:

free -k

Description:

Display free and used system memory in megabytes.

Command:

8
free -m

Description:

Change user password.

Command:

passwd

Description:

Power-off the machine.

Command:

shutdown

Description:

Power-off the machine immediately.

Command:

shutdown -h now

Description:

Power-off the machine after 10 minutes.

9
Command:

shutdown -h +10

Description:

Print current working directory.

Command:

echo $PWD

Description:

Print previous working directory.

Command:

echo $OLDPWD

Description:

Executes the 11th command in command history.

Command:

!11

10
Description:

Reveals your command history.

Command:

history

Description:

Power off or reboot the Operating system.

Command:

sudo reboot

Description:

Display the IP address of the host.

Command:

ip address

Description:

List the size of files and directories.

Command:

Is -s

11
Description:

View mounted file systems.

Command:

mount

Description:

Display the information of disk usage of files and directories.

Command:

du

Description:

Tells you how long the system has been running.

Command:

uptime

Description:

Set current date as 02 Nov 1988.

Command:

12
date --set 1998-11-02

Description:

Set current time as 12:11:02 IST.

Command:

date --set 12:11:02

Description:

View Specific Disk Partition in Linux.

Command:

fdisk -l /dev/sda

Description:

Lists all files and directories in the present working directory.

Command:

Is

Description:

Report the process information.

13
Command:

ps

Description:

Display disk usage.

Command:

df

Description:

Display disk usage in gigabytes, megabytes, or kilobytes.

Command:

df -H

Description:

Delete every file and every directory.

Command:

rm -r *

14
Description:

Provides a quick overview of the currently running processes.

Command:

top

Description:

The system performs an immediate reboot.

Command:

reboot

Description:

Terminate processes without having to log out or reboot.

Command:

kill

Description:

Change the current working directory.

Command:

cd

15
Description:

Create a new session on the system.

Command:

login

Description:

List open files.

Command:

Isof

Description:

List USB devices.

Command:

Isusb

Description:

Check the status of the network services.

Command:

16
service network status

Description:

Start the network service.

Command:

service network start

Description:

Stop the network service.

Command:

service network stop

Description:

Restart the network service.

Command:

service network restart

Description:

Report information about the users currently on the machine and their processes.

17
Command:

Description:

Display the current directory.

Command:

pwd

Description:

Displays CPU architecture information (such as number of CPUs, threads, cores, sockets, and
more).

Command:

Iscpu

Description:

Displays the number of processing units available to the current process.

Command:

nproc

18
Description:

The system performs an immediate reboot.

Command:

init 6

Description:

Power-off the machine.

Command:

init 0

Description:

List files by date.

Command:

Is -Irt

Description:

Report information about storage devices such as hard disks, flash drives etc.

Command:

lsblk

19
Description:

Show exit status of previous command.

Command:

echo $?

Description:

Lists a few useful info commands.

Command:

info

Description:

Prints current year's calendar.

Command:

cal -y

Description:

Check the status of all the services.

Command:

20
service --status-all

Description:

Display time in hh:mm:ss.

Command:

date +%T

Description:

Tells when the user last logged on and off and from where.

Command:

last -1 username

Description:

Sort files and directories by extension name.

Command:

Is -X

Description:

Display the manual for the pwd command.

21
Command:

man pwd

Description:

Displays information about running processes in the form of a tree.

Command:

pstree

Description:

Resets your terminal.

Command:

reset

Description:

Displays What date is it this Friday.

Command:

date -d fri

22
Description:

Displays the size of each individual file.

Command:

du -a

Description:

Display information about the Advanced configuration and power Interface.

Command:

acpi

Description:

Takes you two folders back.

Command:

cd ../..

Description:

Takes you to the previous directory.

Command:

cd -

23
Description:

Displays a list of shell built-in commands.

Command:

help

Description:

Lists your last logins.

Command:

last yourusername

Description:

Create a new directory called myfiles.

Command:

mkdir myfiles

Description:

Remove the directory myfiles.

Command:

24
rmdir myfiles

Description:

Disable password for a specific user "root1".

Command:

passwd -d rootl

Description:

Switch to user "root1".

Command:

sudo su rootl

Description:

Exit from the terminal window.

Command:

logout

Description:

Creates a user "root1".

25
Command:

useradd "rootl"

Description:

Assign password to user "root1".

Command:

passwd "rootl"

Description:

Repeats the last command.

Command:

Description:

Display Who you are logged in as.

Command:

whoami

26
Description:

Display the login name of the current user.

Command:

logname

Description:

Report the name of the kernel.

Command:

uname

Description:

Print the kernel version.

Command:

uname -v

Description:

Print the operating system.

Command:

uname -o

27
Description:

Report the machine hardware name.

Command:

uname -m

Description:

Print version information and exit.

Command:

uname --version

Description:

Print the kernel release.

Command:

uname -r

Description:

Report the network node hostname.

Command:

28
uname -n

Description:

Display all port connections (both TCP and UDP).

Command:

netstat -a

Description:

Display only TCP (Transmission Control Protocol) port connections.

Command:

netstat -at

Description:

Display only UDP (User Datagram Protocol) port connections.

Command:

netstat -au

Description:

Display all active listening ports.

29
Command:

netstat -I

Description:

Display all active listening TCP ports.

Command:

netstat -It

Description:

Display all active listening UDP ports.

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 rootl

Description:

Print the machine's architecture.

Command:

arch

Description:

Display the list of available fonts.

Command:

fc-list

Description:

Create two directories (myfiles, files).

Command:

mkdir myfiles files

31
Description:

install apache (CentOS).

Command:

yum install httpd

Description:

install apache (Ubuntu).

Command:

apt install httpd

Description:

upgrade apache (CentOS).

Command:

yum update httpd

Description:

upgrade apache (Ubuntu).

Command:

32
apt update httpd

Description:

uninstall apache (CentOS).

Command:

yum remove httpd

Description:

uninstall apache (Ubuntu).

Command:

apt remove httpd

Description:

Display usage summary for the command (date).

Command:

date --help

Description:

List active connections to/from system.

33
Command:

ss -tup

Description:

List internet services on a system.

Command:

ss -tupl

Description:

Display all active UNIX listening ports.

Command:

netstat -lx

Description:

Display all the active interfaces details.

Command:

ifconfig

34
Description:

Display information of all network interfaces.

Command:

ifconfig -a

Description:

Compare the contents of two files (1.txt, 2.txt).

Command:

diff 1.txt 2.txt

Description:

Tells you how many lines, words, and characters there are in a file (1.txt).

Command:

wc 1.txt

Description:

Compresses file (1.txt), so that it take up much less space.

Command:

gzip 1.txt

35
Description:

Uncompresses file (1.txt) compressed by gzip.

Command:

gunzip 1.txt

Description:

Examine the contents of the file (1.txt).

Command:

cat 1.txt

Description:

Display calendar.

Command:

ncal

Description:

Removes the file (1.txt).

Command:

36
rm 1.txt

Description:

Rename a file named 1.txt to 0.txt.

Command:

mv 1.txt 0.txt

Description:

Replace the contents of 0.txt with that of 1.txt.

Command:

cp 1.txt 0.txt

Description:

Create a empty file (test.txt).

Command:

touch test.txt

Description:

Print the last 10 lines of a file (1.txt).

37
Command:

tail 1.txt

Description:

Print N number of lines from the file (1.txt).

Command:

tail -n N 1.txt

Description:

Prints the number of words in a file (1.txt).

Command:

wc -w 1.txt

Description:

Prints the number of characters from a file (1.txt).

Command:

wc -m 1.txt

38
Description:

Prints the length of the longest line in a file (1.txt).

Command:

wc -L 1.txt

Description:

Print information about usb ports, graphics cards, network adapters etc.

Command:

Ispci

Description:

View contents of a file (1.txt).

Command:

less 1.txt

Description:

Display calendar (last month, current month, and next month).

Command:

cal -3

39
Description:

Compare the contents of three files (1.txt, 2.txt, 3.txt) line by line.

Command:

diff3 1.txt 2.txt 3.txt

Description:

Compare two files (1.txt, 2.txt) line-by-line.

Command:

comm 1.txt 2.txt

Description:

Perform byte-by-byte comparison of two files (1.txt, 2.txt).

Command:

cmp 1.txt 2.txt

Description:

Prints the CRC checksum and byte count for the file "myfiles.txt".

Command:

40
cksum myfiles.txt

Description:

Append contents of files (1.txt, 2.txt) into one file (0.txt).

Command:

cat 1.txt 2.txt > 0.txt

Description:

Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).

Command:

sed r 1.txt 2.txt 3.txt > 0.txt

Description:

Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).

Command:

sed h 1.txt 2.txt 3.txt > 0.txt

Description:

Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).

41
Command:

sed -n p 1.txt 2.txt 3.txt > 0.txt

Shortcuts:

| ctrl+c Halts the current command |


| ctrl+z Stops the current command |
1| 1|
| ctrl+d Logout the current session |
| ctrl+w Erases one word in the current line |
1| 1|
| ctrl+u Erases the whole line |
| ctrl+r Type to bring up a recent command |

Description:

Writes contents of a file (0.txt) to output, and prepends each line with line number.

Command:

nl 0.txt

Description:

Create a empty file (test1.txt) inside a directory (test).

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 Ishw

Description:

Gather information about file system partitions.

Command:

sudo fdisk -l

Description:

Displays the line (good morning) in which the string (good) is found in the file (1.txt).

Command:

grep good 1.txt

Description:

Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt) using for loop.

43
Command:

for i in {1..3}; do cat "$i.txt" >> 0.txt; done

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:

Displays status related to a file (1.txt).

Command:

stat 1.txt

###
| Command I Description
|:-----------------1------------- .
| vi | Open vi editor
| i | Goto 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:

Display host's numeric ID in hexadecimal format.

Command:

hostid

Description:

Display file type of the file (myfiles.txt).

Command:

file myfiles.txt

Description:

Create a file (myfiles.txt) containing a text (Hello World).

Command:

echo 'Hello World' > myfiles.txt

45
Description:

Create a file (myfiles.txt) containing a text (Hello World).

Command:

printf 'Hello World' > myfiles.txt

Description:

Display IP address of the hostname.

Command:

hostname -i

Description:

Add a new line of text to an existing file (1.txt).

Command:

echo "Hello world!" >> 1.txt


echo "this is 2nd line text" >> 1.txt
echo "last line!" >> 1.txt

Description:

Displays a single line description about a command (cal).

46
Command:

whatis cal

###
| Command I Description
|:-----------------1------------- :
| 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
|:-----------------1------------- .
| 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
| 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:

Find the location of source/binary file of a command (cal).

Command:

whereis cal

# Overwrite existing file


There are 2 ways to use the command: $ echo "Albert Einstein" > 1.txt
# Append a second line
$ echo "Alan Turing" >> 1.txt
• Numeric mode
• Symbolic mode

Numeric mode Permission Type Symbolic mode


0 No Permission —
1 Execute --x
2 Write -w-
3 Execute + Write -wx
4 Read r--
5 Read + Execute r-x
6 Read + Write rw-
7 Read + Write + Execute rwx

[manju@localhost ~]$ ps -ef | grep sshd


root 988 1 0 06:14 ? 00:00 00 /usr/sbin/sshd
manju 3501 3461 0 06:24 pts/0 00:00 00 grep --color=auto sshd

# Check if the SSH server (sshd) is running

48
cd /etc && Is

# Execute Is after cd /etc

Print 'success' if myfiles.txt is


rm myfiles.txt && echo success I I echo failed removed and print 'failed' if it is
not removed

[manju@localhost ~]$ echo This is the $SHELL shell

This is the /bin/bash shell

[manju@localhost ~]$ echo This is $SHELL on computer $HOSTNAME

This is /bin/bash on computer localhost.localdomain

[manju@localhost ~]$ echo The user ID of $USER is $UID

The user ID of manju is 1000

[manju@localhost ~]$ echo My home directory is $HOME

My home directory is /home/manju

[manju@localhost ~]$Bbash -c 'echo $SHELL $HOME $USER'

/bin/bash /home/manju manju


[manju@localhost ~]$lenv -i bash -c 'echo $SHELL $HOME $USER'

/bin/bash

env LANG=C bash -c 'ls test[a-z].txt'

testa.txt testb.txt testc.txt

env LANG=en US.UTF-8 bash -c 'ls test[a-z].txt'

testa.txt testA.txt testb.txt testc.txt testC.txt

49
/home/manju/.bash history Holds the name and location
of your Bash history file

50
echo $HISTFILESIZE

1000

How many commands can be stored in the .bash_history file

[manju@localhost ~]$ Is *ile1.txt

filel.txt

[manju@localhost ~]$ Is f*ile1.txt

filel.txt

[manju@localhost ~]$ ls f*1.txt

filel.txt

[manju@localhost ~]$ ls file?.txt

file1.txt file2.txt file3.txt

[manju@localhost ~]$ ls fil?1.txt

file1.txt

[manju@localhost ~]$ ls fil??.txt

file1.txt file2.txt file3.txt

[manju@localhost ~]$ ls file??.txt

file23.txt file34.txt

51
[manju@localhost ~]$ Is test[5A].txt

testA.txt

[manju@localhost ~]$ Is test[A5].txt

testA.txt

[manju@localhost ~]$ Is file[!5]*.txt

file123.txt file1.txt file23.txt file2.txt file34.txt file3.txt

[manju@localhost ~]$ ls file[!5]?.txt

file23.txt file34.txt

[manju@localhost ~]$ ls [a-z]ile?.txt

file1.txt file2.txt file3.txt

[manju@localhost ~]$ ls [A-Z]ile?.txt

file1.txt file2.txt file3.txt

[manju@localhost ~]$ echo \*

[manju@localhost ~]$ echo '*'

[manju@localhost ~]$ echo "*"

*
List all .txt files starting with a
[manju@localhost ~]$ ls [a-z]*[0-9].txt letter and ending in a number

file123.txt file1.txt file23.txt file2.txt file34.txt file3.txt

52
Is ?????

# List all files that have exactly five characters

Is [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"

[manju@localhost ~]$ echo Einstein2 | sed 's/2/36/'

Einstein36

[manju@localhost ~]$ echo Einstein36 | sed 's/Einstein/Hilbert/'

Hilbert3 6

[manju@localhost ~]$ echo Hawking6 Lucy8 | sed 's/Hawking/Lucy/'

Lucy6 Lucy8

[manju@localhost ~]$ echo Lucy3 Lucy6 | sed 's/Lucy/Hawking/g'

Hawking3 Hawking6

53
[manju@localhost ~]$ who | cut -d' ' -fl | sort
Display a sorted list
manj u of logged on users

manj u

Display a sorted
[manju@localhost ~]$ who | cut -d' ' -f1 | sort | uniq list of logged on

manj u users - but every


user only once

[manju@localhost ~]$ grep bash /etc/passwd

root:x:0:0:root:/root:/bin/bash

manj u:x:1000:1000:su,root,yopp,hhhhh:/home/manj u:/bin/bash

Display a list of all bash user accounts on this computer

grep bash /etc/passwd | cut -d: -fl | sort > bu.txt

# Place a sorted list of all bash users in bu.txt

who | cut -d' ' -f1 | sort > users.txt

# Place a sorted list of all logged on users in users.txt

ls /etc | grep conf

# List of all filenames in /etc that contain the string "conf" in their filename

Display a sorted list of all files in /etc


ls /etc | grep -i conf | sort
that contain the case insensitive string
"conf " in their filename

54
90% of the public cloud workload is run on Linux distros.

import subprocess import os


subprocess.call ('linux command') os.system('linux command')

All of the 500 fastest supercomputers run Linux.

import os

os.system('ls')

import subprocess List all the files and directories in the

current directory
subprocess.call ('ls')

Execution of the linux command "ls" using the python program

55
Command:

last reboot

Description:

Show system reboot history

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:

Display CPU information

56
Command:

cat /proc/meminfo

Description:

Display memory information

Command:

Ispci -tv

Description:

Display PCI (Peripheral Component Interconnect) devices

Command:

Isusb -tv

Description:

Display USB devices

57
Command:

free -h

Description:

Display free and used memory (-h for human readable, -m for MB, -g for GB)

Command:

mpstat 1

Description:

Display processor related statistics

Command:

vmstat 1

Description:

58
Display virtual memory statistics

Command:

iostat 1

Description:

Display Input / Output statistics

Command:

watch df -h

Description:

Execute "df -h" command, showing periodic updates

Command:

ps -ef

Description:

59
Display all the currently running processes on the system

Command:

ip a

Description:

Display all network interfaces and IP address

Command:

dig wikipedia.org

Description:

Display DNS information for domain (wikipedia.org)

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:

List all installed packages

Command:

yum list installed

Description:

List all installed packages (CentOS)

Command:

61
yum info httpd

Description:

Display description and summary information about package "httpd" (CentOS)

Command:

du -ah

Description:

Display disk usage for all files and directories in human readable format

Command:

du -sh

Description:

Display total disk usage off the current directory

Command:

62
cd /etc

Description:

Change to the /etc directory

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:

Compile the C program saved in Hello.c file

Command:

Description:

Compile the C++ program saved in Hello.cpp file

Command:

tty

Description:

Displays the file name of the terminal connected to standard input

64
Command:

public class MyClass {


public static void main(String [] args) {
System.out.println("Hello, World!"); < MyClass.java

}
}

javac MyClass.java

Description:

Compile the Java program saved in MyClass.java file using javac compiler

Command:

od -b myfiles.txt

Description:

Displays the contents of myfiles.txt file in octal format

Command:

od -c myfiles.txt

65
Description:

Displays the contents of myfiles.txt file in character format

Command:

od -An -c myfiles.txt

Description:

Displays the contents of myfiles.txt file in character format but with no offset
information

Command:

csplit myfiles.txt 13 62 101

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

lines 62-100, the xx03 file would contain lines 101-123

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:

Displays the content of myfiles.txt file

Command:

shalsum myfiles.txt

Description:

Prints SHA1 (160-bit) checksum of myfiles.txt file

SHA 1 ^ Secure Hash Algorithm 1

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:

Print the lines of myfile.txt in reverse (from last line to first)

68
Command:

uniq myfiles.txt

Description:

Delete repeated lines in the file (myfiles.txt).

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

Power-off the system


Description:

Open a file (myfiles.txt).

69
Command:

lastlog

Description:

Prints the details of the last login (login-name, port and last login time)

Command:

lastlog -t 1

Description:

Displays the login information (1 day ago)

Command:

lastlog -u manju

Description:

Display lastlog information for a particular user (manju)

70
Command:

cat /etc/passwd

more /etc/passwd

less /etc/passwd

getent passwd

Description:

List all users on Linux

Command:

tail -5 /etc/passwd

head -5 /etc/passwd

71
Description:

List last 5 users on Linux

List first 5 users on Linux

Command:

wall "The system will be shutdown in 10 minutes."

Description:

The message (The system will be shutdown in 10 minutes.) will be broadcasted to

all users that are currently logged in

Command:

chage -l manju

Description:

List the password and its related details for a user (manju)

72
Command:

chage -M 10 manju

Description:

Set Password Expiry Date for an user (manju)

Command:

chage -E "2020-07-30" manju

Description:

Set the Account Expiry Date for an User (manju)

Command:

chage -I 10 manju

Description:

Force the user (manju) account to be locked after 10 inactivity days

73
cat /etc/hostname

^ localhost.localdomain

Display the hostname of the system

hostname

^ localhost.localdomain

nmtui

# Configure a network interface IPv4 address

yum check-update

# Check whether any updates are available for your installed packages

yum search httpd

# Find any packages containing the specified keyword "httpd"

ls /etc

# List the contents of /etc

ls /bin /sbin

# List the contents of /bin and /sbin

ls -al ~

# List all thefiles (including hidden files) in the home directory

ls -lh /boot

# List the filesin /boot ina humanreadable format

74
mkdir ~/mydir

# Create a directory "mydir" under home directory

cd /etc ; mkdir ~/mydir


# Change to the /etc directory and create a directory "mydir" under home directory.

rm -i file.txt

rm: remove regular empty file ‘file.txt’

If we type "yes"

file.txt is removed

If we type "no"

file.txt is not removed

rename .txt .backup *.txt

# Renames all .txt files replacing.txt with .backup

ls

file.txt cod.txt conf.txt

file /bin/cat /etc/passwd /usr/bin/passwd


rename file FILE *
Display the type of file of /bin/cat, /etc/passwd and /usr/bin/passwd

ls

FILE.txt cod.txt conf.txt

75
Command:

ftp 192.168.42.77

Description:

Connect to an FTP server at remote server IP address " 192.168.42.77"

Command:

arp -a

Description:

Lists all the peers connected at various interfaces along with their MAC

Addresses and IP addresses

Command:

dnsdomainname

Description:

76
Display the system's DNS domain name

Command:

domainname

Description:

Display the name of the domain your machine belongs to

Command:

echo 'Hello World!' | base64

Output: SGVsbG8gV29ybGQhCg==

Description:

Encode text (Hello World!) to base64

Command:

echo 'SGVsbG8gV29ybGQhCg==' | base64 -d

Output: Hello World!

Description:

77
Decode (SGVsbG8gV29ybGQhCg==) to text (Hello World!)

Command:

fc-cache -f -v

Description:

Build font information cache files

Command:

cat 1.txt

Einstein
Newton
Albert

fmt 1.txt

Einstein Newton Albert

Description:

Formats text in a single line

78
df -h | sort -rnk 5 | head -3 | \

awk '{ print "Partition " $6 "\t: " $5 " full!" }'

Partition /boot : 51% full!

Partition / : 29% full!

Partition / run : 2% full!

awk 'BEGIN { FS=":" } { print $1 "\t" $5 }' /etc/passwd

# Display all the users on your system

Is *.xml

1.xml 2.xml

Is *.xml > list.txt

[manju@localhost ~]$ cat list.txt

1. xml

2 . xml

for i in 'cat list.txt'; do cp "$i" "$i".md ; done

[manju@localhost ~]$
12.txt 2.xml.md Documents file34.txt Music Pictures tree.cpio

13.txt 3.txt Downloads file3.txt mydi Public users.txt

145.txt all echo FILE.backup mydir SHOW Videos

1.txt allfiles.txt file file.md mydir1 Templates

bu.txt file123.txt first.bash myfiles.txt test

l.xml.md Desktop file1.txt first.txt myFILEs.txt.xz testA.txt

2.txt DICT file23.txt foo1.txt newdir testB.txt

dir file2.txt list.txt nohup.out text

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

# Display information about what kernel-modules are loaded on your system

[manju@localhost ~]$ free -tm

total used free shared buff/cache available

Mem: 999936 511156 73480 8572 415300 284236

Swap: 2097148 0 2097148


Display the memory usage including

totals in megabytes

[manju@localhost ~]$ date --date="3 months 1 day ago

Mon Jul 18 23:17:47 PDT 2022 Print the date 3 months and 1 day ago from the current date

[manju@localhost ~]$ date -d 3 days

Fri Apr 22 23:20:01 PDT 2022 Print the date 3 days in the future from now

[manju@localhost ~]$Bcat myfiles.txt

Hello World

[manju@localhost ~]$Bcat myfiles.txt | tr 'H' 'A' > myfilesB.txt

[manju@localhost ~]$Bcat myfilesB.txt

Aello World

80
[manju@localhost ~]$ fgrep 'He' myfiles.txt

Hello World
Look for the string "He" in the file "myfiles.txt"

Command:

lsattr

Description:

List the files in the current directory

Command:

cp {*.txt,*.md} ~

Description:

Copy the files ending with .txt or .md to the user's home directory

[manju@localhost ~]$ cat myfiles.txt

Hello World

[manju@localhost ~]$ grep --color -i Hello myfiles.txt

Hello World

Is file*

# List all files in the current directory starting with "file"

Is *file

# List all files in the current directory ending with "file"

81
cat 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
the theory of relativity, but he also made important contributions to the
development of the theory of quantum mechanics.

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

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
the theory of relativity, but he also made important contributions to the
development of the theory of quantum mechanics.

fold -w 20 phy.txt

Albert Einstein was

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 l.txt.gz

Einstein
Newton
Albert

Description:

View the contents of zipped file

Command:

zdiff l.txt.gz 2.txt.gz

Description:

Compare the contents of two zipped files (l.txt.gz, 2.txt.gz)

85
Command:

ss | less

Description:

List all connections

Command:

ss -aA tcp

Description:

Filter out TCP (Transmission Control Protocol) connections

Command:

ss -aA udp

Description:

Filter out UDP (User Datagram Protocol) connections

86
Command:

ss -Int

Description:

Display only listening sockets

Command:

ss -Itp

Description:

Print process name and PID

Command:

ss -s

Description:

Print summary statistics

87
Command:

ss -tl6

Description:

Display only IPv6 connections

Command:

ss -tl -f inet

Description:

Display only IPv4 socket connections

Command:

ss -t4 state established

Description:

Display all IPv4 TCP sockets that are in connected state

88
Command:

pmap 3244

Description:

View the memory map of a process with Process ID (3244)

Command:

apropos -r 'remove file'

Description:

Find command that removes file

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

would have a lot of suggestions to offer.

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

Output: display only 3 items per line

a b c
d e f

Command:

env

Description:

Print out a list of all environment variables

Command:

91
printenv HOME

Description:

Print HOME variable value

cat score.txt

Albert-30
John-50
William-80
Stephen-20
Justin-40

cut -d- -f2 score.txt

30
50
80
20
40

cut -d- -f1 score.txt

Albert
John
William
Stephen
Justin

92
cat 1.txt

Hello World

cat 2.txt

Computer Program

paste 1.txt 2.txt

Hello World Computer Program

cat 1.txt

Hello World

cat 2.txt

Computer Program

join 1.txt 2.txt

Hello World Computer Program

93
Command:

rev 1.txt

Description:

Reverse lines of a file (1.txt)

cat 3.txt

22
33
11
77
55

sort 3.txt

11
22 X- sorts numeric values in 3.txt file and displays sorted output
33
55
77 y

94
95
cat 6.txt

Einstein
Newton
Tesla

nl 6.txt

1 Einstein n numbers the lines in a file (6.txt)


2 Newton
3 Tesla

Command:

ls -l *.txt

Description:

Lists the files with .txt extension

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
Is /proc/bus/

# List the contents of the /proc/bus/ directory

Find irq's allocated at boot time


[manju@localhost ~]$ dmesg | grep "irq 1[45]"

[ 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

# List system's IO ports

echo Albert > 1.txt ; echo Einstein > 2.txt

cat 1.txt
[manju@localhost home]$Becho $­
Albert
himBH
cat 2.txt

Einstein

[manju@localhost ~]$ s=01234567890abcdefgh; echo ${s:7}

7 8 90abcdefgh

[manju@localhost ~]$ cd /home/manju; echo $PWD

/home/manj u

[manju@localhost ~]$ cd ..; pwd

/home

97
[manju@localhost home]$ w | cut -d -f 1 | grep -v USER | sort -u

manj u Users currently connected

[manju@localhost ~]$ echo "\\"

[manju@localhost ~]$ echo Al{ber,an,er}t

Albert Alant Alert

[manju@localhost ~]$ echo ${Albert:=Einstein}

Einstein

[manju@localhost ~]$ echo $[5*5]

25

[manju@localhost ~]$ Is

allfiles.txt echo file3.txt mydi Pictures text

bu.txt file FILE.backup mydir Public tree.cpio

Desktop file123.txt file.md mydir1 SHOW users.txt

DICT file1.txt first.bash myfiles.txt Templates Videos

dir file23.txt first.txt myFILEs.txt.xz test

Documents file2.txt foo1.txt newdir testA.txt

Downloads file34.txt Music nohup.out testB.txt

98
Is -Idh * | grep -v total | \
awk '{ print "Size is " $5 " bytes for " $9 }

Size is 135K bytes for 12.txt


Size is 0 bytes for file34.txt

Size is 13M bytes for 13.txt


Size is 0 bytes for file3.txt

Size is 0 bytes for 145.txt


Size is 0 bytes for FILE.backup

Size is 7 bytes for 1.txt


Size is 3 bytes for file.md

Size is 9 bytes for 2.txt


Size is 13 bytes for first.bash

Size is 8 bytes for 3.txt


Size is 13 bytes for first.txt

Size is 20 bytes for all


Size is 66 bytes for foo1.txt

Size is 13M bytes for allfiles.txt


Size is 6 bytes for Music

Size is 11 bytes for bu.txt


Size is 31 bytes for mydi

Size is 6 bytes for Desktop


Size is 6 bytes for newdir

Size is 0 bytes for DICT


Size is 148 bytes for nohup.out

Size is 6 bytes for dir


Size is 6 bytes for Pictures

Size is 6 bytes for Documents Size is 6 bytes for Public

Size is 6 bytes for Downloads


Size is 0 bytes for SHOW

Size is 0 bytes for echo


Size is 6 bytes for Templates

Size is 0 bytes for file


Size is 6 bytes for test

Size is 0 bytes for file123.txt


Size is 0 bytes for testA.txt

Size is 0 bytes for file1.txt


Size is 0 bytes for testB.txt

Size is 0 bytes for file23.txt


Size is 25 bytes for text

Size is 0 bytes for file2.txt


Size is 512 bytes for tree.cpio

Size is 45 bytes for mydir


Size is 12 bytes for users.txt

Size is 47 bytes for mydir1


Size is 6 bytes for Videos

Size is 12 bytes for myfiles.txt

Size is 68 bytes for myFILEs.txt.xz

99
Linux Unix

Free to use (open source) Licensed Operating System (closed source)


Linux is just the kernel Unix is a complete package of Operating System
Bash (Bourne Again SHell) is default shell for Linux Bourne Shell is default shell for Unix
Portable and is booted from a USB Stick Unportable

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:

Print the Default shell of user

Command:

echo $0

Description:

Display the name of the currently running process ($0 is the name of the running process).
If you useit 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:

Print all files and folders - similar to ls command

Command:

ps -p $$

Output:

PID TTY| TIME CMD


3352 pts/e| 00:00:00 bash

Description:

Print the process ID of the current shell ($$ is the process ID of the current shell)

sudo du -a Documents/ | sort -n -r | head -n 5

# List 5 biggest files from directory "Documents"

Command:

101
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:

Print your home folder path

102
bzip2 -k phy.txt

Description:

Compresses but does not deletes the original file

phy.txt ^ phy.txt.bz2

Command:

bzip2 -d phy.txt.bz2

Description:

Decompresses the compressed file (phy.txt.bz2)

phy.txt.bz2 ^ phy.txt

Command:

bzcat phy.txt.bz2

103
Description:

Display the contents of compressed file (phy.txt.bz2)

Command:

bunzip2 phy.txt.bz2

Description:

Decompresses the compressed file (phy.txt.bz2)

Command:

crontab -l

Description:

Display current logged-in user's crontab entries

cat /dev/null > phy.txt

104
cp /dev/null phy.txt

echo "" > phy.txt

echo > phy.txt

Description:

Empty the content of a file (phy.txt)

Command:

nohup ping google.com &

Description:

Ping google.com and send the process to the background

Command:

105
nohup ping google.com > log.txt &

Description:

Save the ping logs to log.txt

pgrep -a ping

Output:

3858 ping google.com


4200 ping google.com
4236 ping google.com

kill 3858

pgrep -a ping

Output:

4200 ping google.com


4236 ping google.com

Command:

ls -la /home

106
Description:

Display the contents of /home

Command:

sudo shutdown 2

Description:

Power-off the machine after 2 minutes

Command:

shutdown -c

Description:

Cancel the shutdown process

Command:

pr 36.txt

107
Description:

Display the contents of the file (36.txt) one page after the other

Command:

stty -a

Description:

Display all current terminal settings

Command:

Is -1

Description:

List files one per line

Command:

108
yes John

Description:

Outputs a string (John) repeatedly until killed

Command:

vdir

Description:

List files and directories in the current directory (one per line) with details

Command:

who -b

Description:

Print when the system was booted

# Open phy.txt with nano

109
Command:

Is -al *.txt
nano phy.txt

Description:

# Open phy.txt with vim Display all .txt files, including its individual

vim phy.txt

Command:

uname -i

Description:

Display the platform of hardware

Command:

uname -p

Description:

Display the type of processor

Command:

cat /proc/interrupts

Description:

Display the interrupts

w --ip-addr

110
# Displays information regarding the users currently on the machine, login time, IDLE time,
TTY and CPU time

Output:

11:12:10 up 1:29, 2 users, load average: 0.02, 0.04, 0.10


USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
manju :0 :0 02:43 ?xdm? 3:30 0.65s gdm-session-worker [pa
manju pts/0 :0 11:01 2.00s 0.10s 0.01s w --ip-addr

w -short
# Omits CPU time and login information
Output:

11:11:46 up 1:28, 2 users, load average: 0.02, 0.04, 0.11


USER TTY FROM IDLE WHAT
manju :0 :0 ?xdm? gdm-session-worker [pam/gdm-password]
manju pts/0 :0 2.00s w --short

Command:

findmnt

Description:

Display a list of currently mounted file systems

Command:

111
ip addr show

Description:

List IP addresses and network interfaces

Command:

netstat -pnltu

Description:

List active (listening) ports

Command:

journalctl

Description:

Display systemd, kernel and journal logs

Command:

112
sudo systemctl status network

Description:

Display the status of network service

Command:

sudo systemctl start network

Description:

Start the network service

Command:

sudo systemctl stop network

Description:

Stop the network service

Command:

113
sestatus -b

Description:

Display the current state of Booleans

Command:

getenforce

Description:

Reports whether SELinux is enforcing, permissive or disabled

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

• Enforcing - SELinux security policy is enforced.


• Permissive - SELinux prints warnings instead of enforcing.
• Disabled - No SELinux policy is loaded.

115
[manju@localhost ~]$ let a="36 + 5" ; echo $a

41

[manju@localhost ~]$ let a="20 + 50/10" ; echo $a

25

[manju@localhost ~]$ let a="20 - 50/10" ; echo $a

15

[manju@localhost ~]$ let a="20 * 50/10" ; echo $a

100

[manju@localhost ~]$ grep APASS /etc/login.defs

PASS_MAX_DAYS 99999

PASS_MIN_DAYS 0

PASS_MIN_LEN 5

PASS_WARN_AGE 7

[manju@localhost ~]$ grep PASS /etc/login.defs

# PASS_MAX_ DAYS Maximum number of days a password may be used.

# PASS_MIN_ DAYS Minimum number of days allowed between. password changes

# PASS_MIN_ LEN Minimum acceptable password length.

# PASS_WARN _AGE Number of days warning given before a password expires.

PASS _MAX_DAYS 99999

PASS _MIN_DAYS 0

PASS _MIN_LEN 5

PASS _WARN_AGE 7

116
Command:

cut -d: -fl /etc/passwd | column

Description:

List all local user accounts in column

Command:

mkdir ~/mydir1 ; touch ~/mydir1/myfiles1.txt

Description:

Create a directory "mydir1" and create a file "myfiles1.txt" in it

Command:

echo hi > file.md ; chmod 744 file.md

Description:

Create a file "file.md" and give only read access to others

[manju@localhost ~]$ ls -l $(which sudo)

-- s--x--x. 1 root root 130776 Nov 5 2016 /bin/sudo

117
Command:

sestatus

Description:

Display the current status of the SELinux that is running on your system

Command:

ps -aef

Description:

Display full listing of processes on your system

Command:

sar

Description:

118
Display System Activity Report

Command:

ulimit

Description:

Report the resource limit of the current user

Output:

Unlimited The current user can consume all the resources the current system supports

2 types of resource limitation:

• 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:

Report all the resource limits for the current user

Command:

ulimit -s

Description:

Check the maximum stack size of the current user

Command:

ulimit -e

Description:

Check out the max scheduling priority of the current user

120
Command:

ulimit -u

Description:

Display the maximum number of user processes

Command:

ulimit -v

Description:

Check out the size of virtual memory

Command:

ulimit -n

Description:

Check out how many file descriptors a process can have

121
Command:

man limits.conf

Description:

Display the in-depth information on the limits.conf configuration file

Command:

sar -V

Description:

Display the sar version

Command:

sar -u 2 5

Description:

Report CPU details total 5 times with the interval of 2 seconds

122
Command:

sar -n DEV 1 3 | egrep -v lo

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:

Report statistics about swapping

123
Command

sar -b 1 3

Description

Report details about I/O operations like transaction per second, read per second, write per second

Command

sudo systemctl status firewalld

Description

Display the status of the firewalld

Command:

sudo systemctl start firewalld

Description:

Start the firewalld service

124
firewalld is a firewall management tool for Linux operating systems

Command:

firewall-config

Description:

Start the graphical firewall configuration tool

firewall-cmd

Command:

firewall-cmd --list-all-zones

Description:

List all zones

Command:

125
firewall-cmd --get-default-zone

Description:

Check the currently set default zone

Command:

firewall-cmd --list-services

Description:

Display currently allowed service on your system

Command:

firewall-cmd --list-ports

Description:

List the ports that are open on your system

Command:

126
firewall-cmd --zone=work --list-services

Description:

List services that are allowed for the public zone

Command:

mtr --report google.com

Description:

Provides information about the route that Internet traffic takes between the local
system and a remote host (google.com)

Command:

sudo yum install samba

Description:

install Samba (CentOS)

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:

sudo firewall-cmd --add-service samba -permanent

Description:

Add Samba service to firewalld

Command:

zip q.zip q.txt

Description:

Create a zip file (q.zip)

Command:

128
unzip q.zip

Description:

Unzip a zip file (q.zip)

zipcloak q.zip

# zipcloak prompts you for a password, and then ask you to confirm it:

Enter password:
Verify password:

...if the passwords match, it encrypts q.zip file

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:

zipsplit -n 1048576 q.zip

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:

cat q*.zip > w.zip

130
Command:

mtr google.com

Description:

Test the route and connection quality of traffic to the destination host google.com

Command:

route

Description:

Display IP routing table of a Linux system

Command:

nmcli dev status

131
Description:

View all your network devices

Command:

nmcli con show

Description:

Check network connections on your system

Command:

ss -ta

Description:

List all TCP ports (sockets) that are open on a server

Command:

132
ss -to

Description:

Display all active TCP connections together with their timers

Command:

type -a alias

Description:

Check Bash Aliases in Linux

# Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year.

echo "We are in the year = $(date +%Y)"

echo "We are in the year = $(date +%y)"

# Difference between %B and %b is, %B will print full month name while %b will print abbreviated month
name.

echo "We are in the month = $(date +%b)"

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.

echo "Current Day of the week = $(date +%A)"


echo "Current Day of the week = $(date +%a)"

echo "Date using %D = $(date +%D)"

echo "Date using %F = $(date +%F)"

Date using %D = 08/15/21

Date using %F = 2021-08-15

echo "current time in 24 hour format = $(date +%T)"

current time in 24 hour format = 01:27:46

echo "current time in 12 hour format = $(date +%r)"

current time in 12 hour format = 01:27:47 AM

# Print yesterday's date and time.


echo "Yesterday = $(date -d "Yesterday")"

# Print Tomorrow date and time.

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")"

# Find last month and next month


echo "Last month = $(date -d "last month" "%B")"
echo "Next month = $(date -d "next month" "%B")"

# Find last year and next year


echo "Last Year = $(date -d "last year" "+%Y")"
echo "Next Year = $(date -d "next year" "+%Y")"

Command:

ls -lai /

Description:

Get the number of inodes of files in a directory (root directory)

Command:

sudo du --inode /

Description:

135
Get the total number of inodes in the root directory

Command:

ss -o state established '( sport = :http or sport = :https )'

Description:

Get the list of all clients connected to HTTP (Port 80) or HTTPS (Port 443)

Command:

ss -tn src :80 or src :443

Description:

List the numerical port numbers

Command:

sudo yum install putty

Description:

136
Install PuTTy on CentOS

Command:

sudo watch netstat -tulpn

Description:

Watch TCP and UDP Open Ports in Real-Time

Command:

sudo watch ss -tulpn

Description:

Watch TCP and UDP Open Ports in Real-Time

Command:

timeout 5s ping google.com

137
Description:

Timeout a ping command after 5 seconds

Command:

yum install curl

Description:

Install curl on CentOS

Command:

ss -ua

Description:

List all UDP Connections

Command:

138
ss -lu

Description:

List all Listening UDP Connections

Command:

ss -p

Description:

Display the Process IDs related to socket connections

Command:

ss -4

Description:

Display IPv4 and IPv6 Socket Connections

139
Command:

ss -6

Description:

Display IPv6 connections

Command:

ss -at '( dport = :22 or sport = :22 )'

Description:

Filter Connections by Port Number

"The only way to learn a new programming language is by writing


programs in it."

- Dennis Ritchie

140
[manju@localhost ~]$ echo {a..z}

a b c d e f g h ij k l mn o p q r s t u v w x y z

[manju@localhost ~]$ echo {z..a}

z y x w v u t s rq p o nm l k j i h g f e d c b a

[manju@localhost ~]$ echo {005..10}

[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}

# Create directories to group files by month and year


[manju@localhost ~]$ echo {12..5}

12 11 10 9 8 7 6 5

[manju@localhost ~]$ echo {12..05}

12 11 10 09 08 07 06 05

[manju@localhost ~]$ echo {x..z}{1..3}

x1 x2 x3 y1 y2 y3 z1 z2 z3

[manju@localhost ~]$ echo {0..10..2}

0 2 4 6 8 10

[manju@localhost ~]$ for i in {a..z..5}; do echo -n $i; done

afkpuz

141
[manju@localhost ~]$ Is *.txt; echo $_

12.txt 1.txt 2.txt abc.txt my.txt phy.txt

13.txt 24.txt 3.txt marks.txt names.txt mphy.txt

[manju@localhost ~]$ cut -d, -f2,1 <<<'Albert,Bob,John'

Albert,Bob

[manju@localhost ~]$ cut -d, -f2,2 <<<'Albert,Bob,John'

Bob

[manju@localhost ~]$ cut -d, -f2,3 <<<'Albert,Bob,John'

Bob,John

[manju@localhost ~]$ x="W X Y Z"; echo "$x"

W X Y Z

[manju@localhost ~]$ x="W X Y Z"; echo $x

W X Y Z

echo $x and echo "$x" yield different results

Quoting a variable preserves whitespace

142
[manju@localhost ~]$ let x=20+7; echo "The value of \"x\" is $x."

The value of "x" is 27.

[manju@localhost ~]$ x=100; let "x += 1"; echo "x = $x"

x = 101

[manju@localhost ~]$ x="a+b+c"; IFS=+; echo $x

The "+" sign will be interpreted as a separator

[manju@localhost ~]$ x="a-b-c"; IFS=-; echo $x

The "- " sign will be interpreted as a separator

[manju@localhost ~]$ x="a,b,c"; IFS=,; echo $x

The "comma" will be interpreted as a separator

free | grep Mem | awk '{ print $4 }'

# Display the unused RAM memory

[manju@localhost ~]$ expr 5 \* 2 + 3


du -ach
13 # 10 + 3

# Display (disk) file usage [manju@localhost ~]$ expr 5 \* \( 2 + 3 \)

25 # 5 * 5

readelf -h /bin/bash

# Display information and statistics about a designated elf binary

143
[manju@localhost ~]$ echo -e "\033[4mAlbert Einstein.\033[0m"

Albert Einstein.

[manju@localhost ~]$ echo -e "\033[1mAlbert Einstein.\033[0m"

Albert Einstein.

[manju@localhost ~]$ echo -e '\E[34;47mAlbert Einstein'; tput sgr0

Albert Einstein

[manju@localhost ~]$ echo -e '\E[33;44m'"Albert Einstein"; tput sgr0

Albert Einstein

[manju@localhost ~]$ echo -e '\E[1;33;44m'"Albert Einstein"; tput sgr0

Albert Einstein

[manju@localhost ~]$ x=2; y=3; echo $((2*$x + 3*$y))

13

[manju@localhost ~]$ x=2; y=3; echo $((2*x + 3*y))

13

[manju@localhost ~]$ let x=2+3 y=3+2; echo $x $y

5 5

144
Command:

sdiff phy.txt score.txt

Description:

Show Difference between Two Files (phy.txt and score.txt)

Command:

history -c

Description:

Delete or clear all the entries from bash history

Command

ping -c 5 www.google.com

Description:

The ping test will stop after sending 5 packets

145
# count number of lines in each .txt file

Is *.txt | xargs wc -l

# count number of words in each .txt file

Is *.txt | xargs wc -w

# count number of characters in each .txt file

Is *.txt | xargs wc -c

# count lines, words and characters in each .txt file

Is *.txt | xargs wc

Command:

Islogins -u

Description:

Displays user accounts

146
Command:

systemctl list-units --type=service

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:

systemctl list-units --type=service --state=active

147
Description:

List all loaded but active services

Command:

systemctl --type=service --state=active

Description:

List all loaded but active services

Command:

systemctl list-units --type=service --state=running

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)

#scan a single port

nc -v -w 2 z 192.168.56.1 22

# scan multiple ports

nc -v -w 2 z 192.168.56.1 22 80

# scan range of ports

nc -v -w 2 z 192.168.56.1 20-25

Command:

cat /etc/resolv.conf

Description:

Find out your DNS Server IP address

149
Command:

less /etc/resolv.conf

Description:

Find out your DNS Server IP address

Command:

findmnt --poll --mountpoint /mnt/test

Description:

Monitor mount, unmount, remount and move actions on a directory (i.e., on /mnt/test)

Command:

uptime -p

Description:

Check Linux Server Uptime

150
Command:

uptime —s

Description:

Check Linux Server Starting Time

Command:

uptime -h

Description:

Display uptime's version information

Command:

grep -o -i Justin score.txt | wc -l

Description:

Count the number of times "Justin" appears in the file (score.txt)

151
Command:

crontab -r

Description:

Delete all crontab jobs

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:

expr length "This is myw3schools.com "

Description:

Find the length of a string (This is myw3schools.com)

echo '3+5' | bc
8

awk 'BEGIN { a = 6; b = 2; print "(a + b) = ", (a + b) }'

(a + b) = 8

Command:

factor 10

Description:

Decompose an integer (10) into prime factors

153
Command:

ps -e

Description:

Display every active process on a Linux system

Command:

ps -x

Description:

Display User Running Processes

Command:

ps -fU manju

Description:

154
Display a user's processes by user name (manju)

Command:

ps -fu 1000

Description:

Display a user's processes by real user ID (RUID)

Command:

ps -U root -u root

Description:

Display every process running with root user privileges (real and effective ID)

echo -e "The following users are logged on the system:\n\n $(who)"

manju :0 Aug 15 03:31 (:0)

manju pts/1 Aug 15 03:32 (:0)

155
date +%d\-%m\-%Y

# Display the current date in DD-MM-YY format

date +%m\/%d\/%Y

# Display the current date in MM/DD/YYYY format

date -d "-7 days"

# Display the date 7 days before current date

date -d "7 days"

# Display the date 7 days after current date

ls -a ~/

# Display all files - including the hidden files

[manju@localhost ~]$ gnome-calculator -s 23500*10%

2350
10
23500 x — = 2350

shuf -i 1-5 -n 5

This command produces numbers, in this case


will generate 5 numbers between 1 and 5.

156
[manju@localhost ~]$ shuf -i 1-5 -n 5 | awk '{ sum+=$1;print $1} END {print "Sum";print sum}'

Sum

15

[manju@localhost ~]$ find ./ -name "*.zip" -type f

./1.zip
Find File with .zip extension
./—encrypt.zip

./my.zip

find -type f -mtime 0

# Find files updated in the last 24 hours

find -type f -newermt 'date +%F'

# Find files updated today

find -type f -newermt 'date +%F -d yesterday

# Find files modified by yesterday

find -type f -mtime -3

# Find files updated in the last 72 hours

157
find -type f -newermt 2021-03-01

# Find files modified after March 1, 2021

find -type f -newermt 'date +%F -d -3hours

# Find files updated in the last 3 hours

find -type f -mmin -180

Shell Scripting

if [ 15 -gt 25 ]

then

echo "True" # Output:

else False

echo "False"

fi

for i in 1 2 3 4 5 # Output:

do Albert

echo "Albert" Albert

done Albert

Albert

158
if test 5 -eq 6

then

echo "True" # Output:

False
else

echo "False"

fi

yum deplist httpd

# List dependencies of a package "apache"

yum reinstall httpd

# Reinstall (corrupted) package "apache"

[manju@localhost ~]$ echo "i=3;++i" | bc

[manju@localhost ~]$ echo "i=3;--i" | bc

[manju@localhost ~]$ echo "i=4;i" | bc

help cd

# Display the complete information about the cd command

help -d cd Display the short description about the cd command

159
help -s cd

# Display the syntax of the cd command

mkdir -m a=rwx myfiles

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*

# Display the use of all commands which start with make

who -d -H

# Print out the list of all dead processes

finger -s manju

# Display login details and IDLE status about an user "manju"

last -F

# Display the login and logout time including the dates

locate --regex -i "(\.mp3|\.txt)"

# Search for all .mp3 and .txt files on your system and ignore case

160
systemctl -l -t service | less

# List all Systemd services

locate "*.txt" -n 20

# Display 20 results for the searching of file ending with .txt

locate -c [.txt]*

# Count files ending with .txt and display the result

ls -l . | egrep -c 'A-'

# Count the number of files within a current directory

du -kx | egrep -v "\./.+/" | sort -n

# Search for the largest directories

ls -al --time-style=+%D | grep 'date +%D'

# List today's files only

find . -name '*.gz'

# Find all the gzip archives in the present working directory

du -hsx * | sort -rh | head -10

# Check the top 10 files that are eating out your space

161
mpstat

# Display processor and CPU statistics

mpstat -P ALL

# Display processor number of all CPUs

mpstat 1 5 ---------- 1

This command will print 5 reports with 1 second time interval

[manju@localhost ~]$ printf "%s\n" "Albert Einstein"

Albert Einstein

Extract the substring


find . -size 0k

# Find all empty files in current directory x=HelloWorld;


echo 'expr substr $x 6 10

ls -F | grep / | wc -l # Output: World

# Count the number of directories in a directory

fdisk -s /dev/sda

# Display the size of the disk partition in Linux

162
Command:

sh <(curl https://nixos.org/nix/install ) --daemon

Description:

Install Nix Package Manager in Linux

Command:

locale

Description:

View System Locale in Linux

Command:

locale -a

Description:

163
Display a list of all available locales

cat score.txt

Justin-40

cat score.txt | tr [:lower:] [:upper:]

JUSTIN-40

cat score.txt | tr [a-z] [A-Z] >output.txt


cat output.txt

JUSTIN-40

cat domainnames.txt

www. google. com


www. fb. com
www. mactech. com
Remove the
cat domainnames.txt | tr -d '' spaces in the
www.google.com domain names
www.fb.com
www.mactech.com

164
cat domainnames.txt

www.google.....com
www.fb.com
www.mactech.Com

cat domainnames.txt | tr -s ''


www.google.com
www.fb.com
www.mactech.Com

echo "My UID is $UID"

My UID is 0

echo "My UID is $UID" | tr...... \n"

My
UID
is
0

A space into a " : " character

echo "myw3schools.com =>Linux-Books,Src,Tutorials" | tr ..... :"

myw3schools.com:=>Linux-Books,Src,Tutorials

Command:

165
!sud

Description:

Re-execute previously used command

Command:

!sudo

Description:

Re-execute previously used command

Command:

cut -d: -fl < /etc/passwd | sort | xargs

Description:

166
Generate a compact list of all Linux user accounts on the system

Command:

zcat phy.txt.gz myfiles.txt.gz

Description:

View multiple compressed files (phy.txt.gz and myfiles.txt.gz)

Command:

find . -type f -name "*.php"

Description:

Find all php files in a directory

mkdir /tmp/DOCUMENTS ◄--------------------------------

# Create a directory 'DOCUMENTS' under "/tmp" directory

Command:

167
find . -type f -perm 0777 -print

Description:

Find all the files whose permissions are 777

Command:

find / -type f ! -perm 777

Description:

Find all the files without permission 777

Command:

find / -perm /g=s

Description:

Find all SGID set files

Command:

168
find / -perm /u=r

Description:

Find all Read-Only files

Command:

find / -perm /a=x

Description:

Find all Executable files

[manju@localhost ~]$ echo "ALBERT" | awk '{print tolower($0)}'

albert
Convert text from upper case to lower case

Command:

169
find . -type f -name "phy.txt" -exec rm -f {} \;

Description:

Find and remove phy.txt File

[manju@localhost ~]$ echo "Phone number: 55602369" | tr -cd [:digit:]


Command: 55602369
Get the digits from string

find . -type f -name "*.txt" -exec rm -f {} \;

Description:

To find and remove multiple .txt files

Command:

find . -type f -name "*.mp3" -exec rm -f {} \;

Description:

170
To find and remove multiple .mp3 files

Command

find /tmp -type d -empty

Description:

Find all Empty Directories

Command:

find /tmp -type f -name ".*"

Description:

File all Hidden Files

[manju@localhost ~]$ echo "Phone number: 55602369" | tr -d [:digit:]

Phone number:
Remove all digits from string

Command:

171
find / -mtime 50

Description:

Find Last 50 Days Modified Files

Command:

find / -atime 50

Description:

Find Last 50 Days Accessed Files

Command:

find / -cmin -60

Description:

172
Find Changed Files in Last 1 Hour

Command:

find / -mmin -60

Description:

Find Modified Files in Last 1 Hour

Command:

find / -amin -60

Description:

Find Accessed Files in Last 1 Hour

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:

Find all 50MB files

Command:

find / -type f -size +100M -exec rm -f {} \;

Description:

Find and Delete 100MB Files

Command:

find / -type f -name *.mp3 -size +10M -exec rm {} \;

Description:

Find all .mp3 files with more than 10MB and delete them

174
Is -l --color

# List the files in current directory (with colorized output)

info df

# Loads the "df"info page

ls /usr/include

# List the Header files for compiling C programs

ls /usr/local

# List the Locally installed files

ls /usr/bin/d*

# List all files whose names begin with the letter "d" in the /usr/bin directory

[manju@localhost ~]$Bls .b*

.bash history .bash logout .bash profile .bashrc

[manju@localhost ~]$ ls [a-h]*

all DICT filel file2 file34.txt file.md fool.txt

allfiles.txt echo file123.txt file23.txt file3.txt first.bash

bu.txt file filel.txt file2.txt FILE.backup first.txt

[manju@localhost ~]$ touch hello.cpp; touch hello.f99

[manju@localhost ~]$ ls *.?[9p]?

hello.cpp hello.f99

175
Is /usr

# List the /usr directory

Is ~ /usr

# List the user's home directory and the /usr directory

[manju@localhost ~]$ echo f* Display any file beginning with "f"

file file1 file123.txt file1.txt file2 file23.txt file2.txt file34.txt file3.txt


file.md first.bash first.txt foo1.txt

Display any file beginning with "f" followed by


[manju@localhost ~]$ echo f*.txt any characters and ending with ".txt"

file123.txt file1.txt file23.txt file2.txt file34.txt file3.txt first.txt foo1.txt

sudo vim myfiles.txt

# Open a file "myfiles.txt" using Vim editor

[manju@localhost ~]$ for ((i=0;i<8;i++)); do echo $((i)); done

176
Command:

cat /proc/sys/fs/file-max

Description:

Find Linux Open File Limit

Command:

ulimit -Hn

Description:

Check Hard Limit in Linux

Command:

ulimit -Sn

Description:

Check Soft Limits in Linux

177
Command:

timedatectl status

Description:

Display the current time and date on your system

Command:

timedatectl list-timezones

Description:

View all available timezones

Command:

timedatectl list-timezones | egrep -o "Asia/B.*"


timedatectl list-timezones | egrep -o "Europe/L.*
timedatectl list-timezones | egrep -o "America/N.

178
Description:

Find the local timezone according to your location

Command:

timedatectl set-timezone "Asia/Kolkata"

Description:

Set your local timezone in Linux

Command:

swapon --summary

Description:

View a summary of swap space usage by device

Command:

179
cat /proc/swaps

Description:

Check swap usage information

# start recording of Linux terminal

script history log.txt

Script started, file is history_log.txt

exit

Script done, file is history_log.txt

Command:

dir -shl

Description:

180
List files and their allocated sizes in blocks

Command:

less /proc/sys/dev/cdrom/info

Description:

Display information about CD-ROM

while true; do date >> date.txt ; sleep 5 ; done &

cat date.txt

Mon Aug 16 03:05:36 PDT 2021


Mon Aug 16 03:05:41 PDT 2021
Mon Aug 16 03:05:46 PDT 2021
Mon Aug 16 03:05:51 PDT 2021

"Don't write better error messages, write code that doesn't need them."

- Jason C. McDonald

181
[manju@localhost ~]$ echo hello > 1.txt

[manju@localhost ~]$ echo world > 2.txt

[manju@localhost ~]$ echo program > 3.txt

[manju@localhost ~]$ cat 1.txt

hello

[manju@localhost ~]$ cat 2.txt

world

[manju@localhost ~]$ cat 3.txt

program

[manju@localhost ~]$ cat 1.txt 2.txt 3.txt

hello

world

program

[manju@localhost ~]$ cat 1.txt 2.txt 3.txt >all

[manju@localhost ~]$ cat all

hello

world

program

strings /usr/bin/passwd

# Display the readable character strings from the /usr/bin/passwd

Is -IrS /etc

# List the biggest file in /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

[manju@localhost ~ ]$ ls /etc/* . conf

/etc/asound .conf /etc/kdump .conf /etc/radvd .conf

/etc/autofs .conf /etc/krb5.conf /etc/request-key.conf

/etc/autofs ldap auth.conf /etc/ksmtuned.conf /etc/resolv.conf

/etc/brltty.conf /etc/ld.so.conf /etc/rsyncd.conf

/etc/cgconfig.conf /etc/libaudit.conf /etc/rsyslog.conf

/etc/cgrules .conf /etc/libuser.conf /etc/sestatus.conf

/etc/cgsnapshot bl acklist.conf /etc/locale.conf /etc/sos.conf

/etc/chrony.conf /etc/logrotate.conf /etc/sudo.conf

/etc/dleyna-server -service.conf /etc/man db.conf /etc/sudo-ldap.conf

/etc/dnsmasq .conf /etc/mke2fs.conf /etc/sysctl.conf

/etc/dracut .conf /etc/mtools.conf /etc/tcsd.conf

/etc/e2fsck.conf /etc/nfsmount.conf /etc/updatedb.conf

/etc/fprintd.conf /etc/nsswitch.conf /etc/usb modeswitch.conf

/etc/fuse.conf /etc/ntp.conf /etc/vconsole.conf

/etc/GeoIP.conf /etc/numad.conf /etc/wvdial .conf

/etc/host.conf /etc/oddj obd.conf /etc/yum.conf

/etc/idmapd .conf /etc/pbm2ppa.conf

/etc/ipsec.conf /etc/pnm2ppa.conf

Display configuration files located in /etc

ls /dev/sd*

/dev/sda /dev/sda1 /dev/sda2 /dev/sda3 Display SATA device files

183
echo \$USER

# $USER

echo -e "2+2\t=4" ; echo -e "12+12\t=24"

2 +2 =4
echo Hello && echo World
12 + 12 =24
Hello

World
echo Hello ; echo World

Hello

World

echo Hello || echo Hi ; echo World

Hello

World

rm myfiles.txt && echo It worked! || echo It failed!

It worked!

rm files.txt && echo It worked! || echo It failed!

rm: cannot remove ‘files.txt’: No such file or directory

It failed!

pwd ; pwd

/home/manj u Execute the pwd command twice

/home/manj u

184
a=$(pwd)
echo "Current working directory is : $a"

/home/manju

Command:

echo *.jpeg

Description:

Print all .jpeg files

Command:

echo 'linux' | fold -w1

Description:

Break down a word (linux) into individual

185
l

n
u
x

Command:

find . -user root

Description:

Output the files with respect of the user (root) owned files in the current directory

Command:

strace pwd

Description:

Trace a command (pwd) execution

186
Command:

top -u manju

Description:

Display specific User (manju) process details

3 characteristics of big data:

• Volume — How much data is there?

• Variety — How diverse is different types of data?

• Velocity — At what speed is new data generated?

[manju@localhost ~]$ netstat -plunt ------

# print all listening ports _____________

[manju@localhost ~]$ netstat -plunt | grep 8080 ---

# check if server is listening on port 8080 or not •<

[manju@localhost ~]$ netstat -s ------------

# list statistics of all ports ____________

187
[manju@localhost ~]$ cat myfiles.txt

Hello World

[manju@localhost ~]$ cat myfiles.txt | tr ' ' '\n'

Hello

World

find . -name "*.txt"

# Find files that end in .txt in the current directory and all subdirectories

find /etc > 12.txt

# Find all files in /etc and place the list in 12.txt

find . -newer file1.txt

# Find files that is newer than file1.txt

[manju@localhost ~]$ date +'%A %d-%m-%Y'

Tuesday 19-04-2022

[manju@localhost ~]$ date -d '2022-04-01 + 2000000000 seconds'

Thu Aug 16 03:33:20 PDT 2085

find /etc -type f -name '*.txt' | wc -l

# Print the number of .txt files in /etc and all its subdirectories

[manju@localhost ~]$ cat myfiles.txt

Hello World

[manju@localhost ~]$ grep -E 'o*' myfiles.txt

Hello World

[manju@localhost ~]$ grep -E 'o+' myfiles.txt

Hello World

188
[manju@localhost ~]$ echo Albert Einstein | sed 's/Albert/&&/'

AlbertAlbert Einstein

[manju@localhost ~]$ echo Albert Einstein | sed 's/Einstein/&&/'

Albert EinsteinEinstein

[manju@localhost ~]$ echo Albert | sed 's \(Alb\) \1ert '

Albertert

[manju@localhost ~]$ echo Albert | sed 's \(Alb\) \1ert \1 '

Albert Albert

[manju@localhost ~]$ echo -e ' Albert\tis\tScientist'

Albert is Scientist

[manju@localhost ~]$ echo -e 'Albert\tis\tScientist' | sed 's_\s___ g'

Albert is Scientist

[manju@localhost ~]$ cat myfiles.txt

Hello World

[manju@localhost ~]$ cat myfiles.txt | sed 's/ll\?/A/'

HeAo World

189
[manju@localhost ~]$ cat myfiles.txt

Hello World

[manju@localhost ~]$ cat myfiles.txt | sed 's/l\{2\}/A/'

HeAo World

echo Albert 'echo -n Einstein'

[manju@localhost ~]$ test 50 -gt 15 ; echo $

0
True: 50 is greater than 15

[manju@localhost ~]$ test 5 -gt 15 ; echo $

1
False: 5 is not greater than 15

[manju@localhost ~]$ test 5 -lt 15 ; echo $

0
True: 5 is lesser than 15

[manju@localhost ~]$ test 50 -gt 15 && echo true || echo false

true

[manju@localhost ~]$ test 5 -gt 15 && echo true || echo false

false

190
[manju@localhost ~]$ [ 50 -gt 15 ] && echo true || echo false

true

[manju@localhost ~]$ [ 5 -gt 15 ] && echo true || echo false

false

[manju@localhost ~]$ [ 100 -gt 10 -a 100 -It 150 ] && echo true || echo false

true

[manju@localhost ~]$ [ 100 -gt 10 -a 100 -lt 15 ] && echo true || echo false

false

[manju@localhost ~]$ a=2; b=a; eval c=\$$b; echo $c

[manju@localhost ~]$ date

Tue Apr 19 02:55:39 PDT 2022

[manju@localhost ~]$ date --date="1 week ago"

Tue Apr 12 02:55:05 PDT 2022

191
Command:

uname -or

Description:

Find Out Linux Kernel Version

Command:

uname -a

Description:

Print linux system information

Command:

cat /proc/version

Description:

Display some of your system information including the Linux kernel version

192
Command:

cat /etc/centos-release

Description:

Find Out Linux Distribution Name and Release Version

Command:

fuser .

Description:

Displays the PIDs of processes currently accessing your current working directory

Command:

193
fuser -v -m .bashrc

Description:

Determine which processes are accessing your ~.bashrc file

Command:

sudo fuser --list-signals

Description:

Displays all the possible signals that can be used with the fuser tool

Command:

sudo fuser -k -HUP /boot

Description:

Sends the HUP signal to all processes that have your /boot directory open

194
Command:

Is -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:

# Everyone can now read the file


echo "shutdown -h now" | at -m 23:55

chmod a+r myfiles.txt

Description: # Everyone can now read and write the file

chmod a+rw myfiles.txt

Shutdown the system at 23:55 today


# Others (not the owner, not in the same group of the
file) cannot read, write or execute the file

Command: chmod o-rwx myfiles.txt


echo "updatedb" | at -m 23.55

Description: Creates and updates the database of file


names used by locate

Run updatedb at 23:55 today

195
Command:

echo $(ls -al)

Description:

Execute command "ls -al" and print the result to the standard output

Command:

top -b -o +%MEM | head -n 22

Description:

Display the top 15 processes sorted by memory use in descending order

Command:

top -b -o +%MEM | head -n 22 > report.txt

Description:

Redirect the output to a file (report.txt) for later inspection

196
Command:

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head

Description:

Check Top Processes sorted by RAM or CPU Usage in Linux

Command:

find . -type f \( -name "*.sh" -o -name "*.txt" \)

Description:

Find all files in the current directory with .sh and .txt file extensions

Command:

find . -type f \( -name "*.sh" -o -name "*.txt" -o -name "*.c" \)

Description:

Find all files in the current directory with .sh, .c and .txt file extensions

197
Description:

Find files edited more than 3 days ago.

Command:

find . -type f -mtime +3

Description:

Find files edited in the last 24 hours.

Command:

find . -type f -mtime -1

Description:

Find files that have more than 100 characters (bytes) in them.

Command:

find . -type f -size +100c

198
Description:

Find files bigger than 100 KB but smaller than 1 MB.

Command:

find . -type f -size +100k -size -1M

Description:

Deletes all the files edited in the last 24 hours.

Command:

find . -type f -mtime -1 -delete

Description:

List all files including hidden files.

Command:

199
Is -a

Description:

List Files and Directories with "/" Character at the End.

Command:

Is -F

Description:

List Files in Reverse Order.

Command:

Is -r

Description:

Sort Files by File Size.

200
Command:

Is -IS

Description

List Files with an inode number.

Command:

Is -i

Description:

Check the version of the ls command.

Command:

Is --version

Description:

List files under directory /tmp.

201
Command:

Is -l /tmp

Description:

Display UID and GID of files and directories.

Command:

Is -n

Description

Find all 30 MB files.

Command:

find / -size 30M

202
Description:

Find files with sizes between 100 - 200MB.

Command:

find / -size +100M -size -200M

Description:

List directories larger than 20 KB.

Command:

find / -type d -size +20k

Description:

Find empty files and directories.

Command:

find ./ -type f -size 0

203
Description:

List files modified within the last 17 hours.

Command:

find . -mtime -17 -type f

Description:

*** List directories modified within the last 10 days.***

Command:

find . -mtime -10 -type d

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:

Display files with permission 777.

Command:

find -perm 777

Description:

List files owned by a user (manju).

Command:

find /home -user manju

Description:

Find all text files owned by user "manju".

205
Command:

find /home -user manju -iname "*.txt"

Description:

Find and list files and directories together with their permissions.

Command:

find -name "*.conf" | Is -l

Description:

List directories only.

Command:

Is -d */

Description:

List multiple files on a single line.

206
Command:

Is --format=comma

Description:

View the process of a specific user "manju".

Command:

ps -u manju

Description:

Execute a previous command starting with a specific letter "c".

Command:

207
Description:

Display BIOS information (You need elevated permissions to run this).

Command:

dmidecode -t 0

Description:

Display CPU information (You need elevated permissions to run this).

Command:

dmidecode -t 4

Description:

View all the system logs.

Command:

gnome-system-log

208
Description:

Identify SSH Client Version.

Command:

ssh -V

Description:

Display total connect time of users.

Command:

ac -d

Description:

Display connect time for all the users.

Command:

209
ac -p

Description:

Diaplay connect time report for a specific user "manju".

Command:

ac -d manju

Description:

Display the modules compiled inside Apache.

Command:

httpd -l

Description:

*** View Processes Owned by Current User.***

210
Command:

ps U $USER

Description:

Display the information about the filesystem Type.

Command:

df -Tha

Description:

Display Active Connections with Process ID and Program Name.

Command:

netstat -tap

Description:

Display RAW network statistics.

211
Command:

netstat --statistics --raw

Linux User Mode

Graphical user interface


Command Line Interface

212
[manju@localhost ~]$ PS1="Please enter a command: "

Please enter a command: date

Thu Apr 21 20:51:19 PDT 2022

Please enter a command: cal

April 2022

Su Mo Tu We Th Fr Sa Ps -aux | greP 'httPd'

-^2 # Check for the httpd process

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

Please enter a command:

/var/spool holds spooled files such as those


generated for printing jobs and network transfers
[manju@localhost ~]$ ls /var/spool

abrt abrt-upload anacron at cron cups lpd mail plymouth postfix

[manju@localhost ~]$ ls ^/usr/shaBe/ma^^M /usr/share/man holds the online Man files

ca en hu ko man1x man3p man5 man7 man9 pl ro tr zh_TW

cs es id man0p man2 man3x man5x man7x man9x pt ru uk

da fr it man1 man2x man4 man6 man8 mann pt BR sk zh

de hr ja man1p man3 man4x man6x man8x overrides pt PT sv zh CN

213
[manju@localhost ~]$ Is /etc/gdm List the contents of GDM configuration directory

custom.conf Init PostLogin PostSession PreSession Xsession

Is /etc/gconf

# List the GConf configuration files

ls /usr/share/gnome

# List the files used by GNOME applications

[manju@localhost ~]$ ls /etc/sysconfig List the system configuration files

atd firewalld libvirt-guests qemu-ga samba

authconfig grub man-db radvd saslauthd

autofs init modules raid-check selinux

cbq ip6tables-config netconsole rdisc smartmontools

cgred iptables-config network readonly-root sshd

console irqbalance network-scripts rpcbind sysstat

cpupower kdump nfs rpc-rquotad sysstat.ioconf

crond kernel ntpd rsyncd virtlockd

ebtables-config ksm ntpdate rsyslog virtlogd

fcoe libvirtd pluto run-parts wpa_supplicant

ls /etc/rc.d

# List the system startup and shutdown files

/etc/init.d holds network scripts to start up


[manju@localhost ~]$ ls /etc/init.d network connections

functions netconsole network README

214
Important features of Linux Operating System

• Free and Open Source


• Portable and More secure
• Robust and Adaptable

Linux Kernel

The core interface between a computer's


hardware and its processes

Manage RAM memory.

Manage the processor time.

Manage access and use of the various peripherals that are connected to the computer.

A space on a hard disk that is used when the amount of


Swap space
physical memory (RAM) is full

215
[manju@localhost ~]$ cd /etc

[manju@localhost etc]$ pwd

/ etc

[manju@localhost etc] $ cat /etc/hosts /etc/hosts contains hostnames with their ip address

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4

::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

chmod u+w myfiles.txt

# Add user write privileges

chmod u-w myfiles.txt

# Remove user write privileges

chmod go-r myfiles.txt


chmod g+w myfiles.txt

# Add group write privileges

chmod g=r myfiles.txt

# Allow only the group read privileges

chmod o+x myfiles.txt

# Add execute privileges for others

chmod a+x myfiles.txt

# Add execute privileges for everyone

chmod a=xr myfiles.txt

# Allow read and execute only to everyone

216
ps -L 3315

# List all threads for a particular process (with process ID 3315)

ps aux --sort pmem

# Check the memory status

awk '/Hello/' myfiles.txt

# Find "Hello" in myfiles.txt

awk -F: '{ print $1 }' /etc/passwd | sort

# Display a sorted list of the login names of all users

awk 'END { print NR }' myfiles.txt

# Counts lines in myfiles.txt

[manju@localhost ~]$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24 _______________________ _____________________________ J

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

Process States in Linux:

• Ready: a new process is created and is ready to run.


• Running: The process is being executed.
• Wait: The process is waiting for input from the user.
• Completed: The process has completed the execution.
• Zombie: The process is terminated but information regarding the process still exists
and is available in the process table.

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:

View system defined cron jobs

Command:

netstat --listen

218
Description:

Check which ports are in listening in Linux Server

Network Interface Card teaming is the process of combining


multiple network cards together for performance, load balancing
and to increase uptime.

Service Default Port


DNS 53
SMTP 25
FTP 20 (Data transfer), 21 (Connection established)
SSH 22
DHCP 67/UDP (dhcp server), 68/UDP (dhcp client)
squid 3128

Hard Link Soft Link

y ▼
A mirror copy of the original file A symbolic link to the original file

Contains the original content Does not contain the actual


of the file content but contains the location
of the original file

219
Is /bin

# List the binaries and other executable programs

Is /boot

# List the files needed to boot the operating system

Is /dev

# List the device files - typically controlled by the operating system and the system administrators

ls /etc

# List the System configuration files

ls /lib

# List the System Libraries

ls /lib64

# List the System Libraries (64 bit)

ls /proc

# List the information about running processes

ls /sbin

# List the System administration binaries

ls /var/log

# List the Log files

220
[manju@localhost ~]$ Is -l myfiles.txt

-rw-r--r--. 1 manju nath 12 Apr 19 20:22 myfiles.txt

Display the permissions for the file "myfiles.txt"

find . -mtime +1 -mtime -3

# Display files that are more than 1 day old - but less than 3 days old in the current directory

find . -name "s*" -ls

# Find files that start with the letter "s"and perform the command "ls" on them

find . -size +3M

# Find files that is larger than 3 megabytes

[manju@localhost ~]$ cat myfile. txt

ffff
[manju@localhost ~]$Btouch file1; touch file2

b [manju@localhost ~]$lls file{1,2}

eee
file1 file2

cc

[manju@localhost ~]$ cat myfile. txt | sort

b
[manju@localhost ~]$HNUMLOGINS=$(who | grep $USER | wc -l)
cc
[manju@localhost ~]$Becho You have $NUMLOGINS login sessions
eee
You have 2 login sessions
ffff

221
Command:

chmod go-rwx myfiles.txt

Description:

Remove read write and execute permissions on the file "myfiles.txt" for the group and others

Command:

chmod a+rw myfiles.txt

Description:

Give read and write permissions on the file "myfiles.txt" to all

Command:

-3

Description:

Repeats the third most recent command

[manju@localhost ~]$ echo $OSTYPE

linux-gnu
The current operating system you are using

222
Command:

df -i /dev/sdal

Description:

Check Inodes on File system

Command:

Is -il myfiles.txt

Description:

Find Inode number of File (myfiles.txt)

Command:

getfacl myfiles.txt

Description:

Check ACL (Access control list) configured on a file (myfiles.txt)

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:

Check information of disk usage of files and directories on a machine.

Command

Idd /bin/cp

224
Description:

Display dependencies of the "cp" command.

Command:

Idd -v /bin/cp

Description:

Display dependencies of the "cp" command with details.

Command:

Idd -u /bin/cp

Description:

Display unused direct dependencies of the "cp" command.

225
[manju@localhost ~]$ date; cal

Thu Apr 21 19:44:12 PDT 2022

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

10 11 12 13 14 15 16

17 18 19 20 21 22 23

24 25 26 27 28 29 30

[manju@localhost ~]$ date && cal

Thu Apr 21 19:44:21 PDT 2022

April 2022

Su Mo Tu We Th Fr Sa cal command is executed


only if the date command is
1 2
successfully executed
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

[manju@localhost ~]$ ls *.c


[manju@localhost ~]$Bls *.[co]
hello.c vim.c hello.c hello.o vim.c

226
[manju@localhost ~]$ a='ls *.c'; echo $a

hello.c main.c vim.c

[manju@localhost ~]$ test 50 -ge 15 && echo true | | echo false

true

[manju@localhost ~]$ test 50 -ge 50 && echo true | | echo false

true

[manju@localhost ~]$ test 20 -le 50 && echo true | | echo false

true

[manju@localhost ~]$ test 20 -le 20 && echo true | | echo false

true

[manju@localhost ~]$ test 30 -eq 30 && echo true | | echo false

true

[manju@localhost ~]$ test 320 -eq 30 && echo true | | echo false

false

[manju@localhost ~]$ test 30 -ne 30 && echo true | | echo false

false

[manju@localhost ~]$ test 320 -ne 30 && echo true | | echo false

true

227
Command:

cat /proc/net/dev

Description:

Display network adapters and statistics

Command:

cat /proc/mounts

Description:

Display the mounted file system

Command:

telinit 0

Description:

Shutdown the system

cd /home

# Takes you to the home directory

cd ..

# Takes you one folder back

Display the files and folders that contain numbers 0 to 9


ls * [0-9]

228
iconv -l

# Display the lists of known ciphers

Is -iSr | more

# Display the size of the files and directories ordered by size

du -sk * | sort -rn

# Display the size of the files and directories ordered by size

Command:

ls -lh

Description:

Display permissions

Command:

yum list

Description:

List all packages installed on the system

Command:

yum clean packages

Description:

Clean all the saved packages

229
Command:

yum clean headers

Description:

Clean package headers

Command:

yum clean all

Description:

Clean all cached information

Command:

yum clean metadata

Description:

Clean Metadata

ip link show

# Display the link status of all interfaces

ps -eafw

# Display Linux tasks

lsof -p $$

# Display a list of files opened by processes

230
Command:

find /var -atime -90

Description:

Find files in the /var directory that have not been accessed in the last 90 days

Command:

find / -name core -exec rm {} \;

Description:

Search for core files in the entire directory tree and delete them as found without
prompting for confirmation

Command:

who -r

Description:

Check current run level of a Linux server

231
Bash script:

for i in *linux*; do rm $i; done

Description:

Delete all the files in the current directory that contains the word "linux"

Command:

awk '{print}' myfiles.txt

Description:

Display the content of file (myfiles.txt)

# Wait for 5 seconds

sleep 5s

# Wait for 5 minutes

sleep 5m Sleep commands used to introduce


wait time in scripts
# Wait for 5 hours

sleep 5h

# Wait for 5 days

sleep 5d

232
Command:

In myfiles.txt hardFl

Description:

Create hard-link to myfiles.txt

Command:

cat hardFl

Description:

Check content of the hard link - hardF1

Command:

In myfiles.txt softFl

Description:

Create Soft-link to myfiles.txt

Command:

cat softFl

Description:

Check content of the soft link - softF1

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:

Display information about the process with process ID - 13

Command:

ulimit -f 100

Description:

Set the file size limit to 51,200 bytes

Command:

Ismod

Description:

234
Find out what kernel modules are currently loaded

Absolute path Relative path

The path of a file or directory from the The path of a file or directory from the
root directory. present working directory.

Command:

sudo yum install php

Description:

Install php version 7.2

Command:

php -r 'echo "Hello World\r\n";'

Description:

Run a PHP statement from the command line without creating a file

Command:

php -a

Description:

Start a PHP interactive shell

235
Command:

du -h -d 1 /

Description:

Display disk usage of all top-level directories

Command:

yum install man

Description:

Install man package in Centos

Command:

man -f Is

Description:

Display man Pages and Print Short Description of the ls command

man -a Is

# Display all man Pages of the Is command

man -k ls

# Allows users to search the short command descriptions and manual page names for ls command

man -w ls

# Displays the location of the manual page of the ls command

236
cat /etc/redhat-release

# Display Linux distribution name and version

Is ~

# Display the contents of the home directory

ls ../

# Display the contents of the parent directory

Command:

ps -U root -u root

Description:

Display all process running under the root user account

Command:

cal -1

Description:

Display current month calendar

Command:

cal -j

Description:

Print the calendar in day numbers

237
Command:

su

Description:

Used to switch from one account to another

Command:

nmcli connection show

Description:

Display what are the network connection connected in our system

Command:

ps aux | grep 'telnet'

Description:

Searches for the id of the process 'telnet'

ps r

# List only running processes on Linux

ps T

# List all processes on this current terminal

ps -f

# List processes along with the parent process ID associated with the current Terminal

238
ps -x

# View all processes owned by you

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem

# Display the processes using highest memory

sudo yum list --installed | more

# Lists installed packages on CentOS

Command:

sudo rpm -qa

sudo rpm -qa | more

Description:

Get a list of all installed packages with rpm command

Command:

sudo rpm -q nginx

Description:

Check whether nginx package installed or not

239
Command:

sudo rpm -q bash

Description:

Check whether bash package installed or not

Command:

sudo yum history

Description:

List all installed packages with yum on CentOS history command

Command:

sudo yum history info 2

Description:

Examine history entries in detail using transaction ID [2]

Command:

file /etc/passwd

Description:

Displays the file type of a given file

[root@localhost manju]# file /etc/passwd

/etc/passwd: ASCII text

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:

grep root: /etc/passwd

Description:

Display all lines from /etc/passwd containing the string "root"

Command:

grep -n root /etc/passwd

Description:

Display all lines from /etc/passwd containing the string "root" with line numbers

Command:

grep -c false /etc/passwd

Description:

Display the number of accounts that have /bin/false as their shell

241
Command:

grep Aroot: /etc/passwd

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

(Display the top 10 lines only)

lastb

# Display the last unsuccessful login attempts

du /etc/passwd

# Display the disk usage of a /etc/passwd file

killall proc

# Kill all the process named proc

wget https://repo.mysql.com/mysql80-community-release-el8-1.noarch.rpm

# Download the RPM file to install

sudo yum localinstall mysql80-community-release-el8-1.noarch.rpm

# Install the RPM file

242
sudo yum localinstall https://repo.mysql.com/mysql80-community-release-el7-1.noarch.rpm

# Install the RPM package via URL

curl --version

# Display curl Version

curl -O http://website.com/myfiles.tar.gz

# Download the file (myfiles.tar.gz) from url "http://website.com/myfiles.tar.gz"

# Saved as myfiles.tar.gz

curl -o files.tar.gz http://website.com/myfiles.tar.gz

# Download the file (myfiles.tar.gz) from url "http://website.com/myfiles.tar.gz"

# Saved as files.tar.gz

echo 'https://repo.mysql.com/mysql80-community-release-el8-1.noarch.rpm' > urls.txt

xargs -n 1 curl -O < urls.txt

# Download files from a list of URLs in "urls.txt" file

exit 110

# Exit from the terminal window

sudo -l

# know which commands are permitted and not permitted on the current host

243
Command:
echo -e "\thello\nworld"

hello
world

history | grep cd | head -12

Searches history of first 12 commands which have cd word match

• Difficulty to use
Disadvantages of Open Source Operating System:
• Compatibility Issues

Command:

rpm -qa | grep ftp

Description:

Check all installed packages of ftp

Command:

find /home -mtime +120

Description:

Find files in the /home directory which were modified more than 120 days ago

244
Samba enables Linux / UNIX machines to communicate with

Windows machines in a network.

• The /etc directory contains configuration files in Linux.


• The Network File System (NFS) is a mechanism for storing files on a network.
• "init" is the first process in linux which is started by the kernel and its process id is 1.

egrep "Hello|Einstein" file.txt

Returns line with Hello or Einstein in the file.txt

date "+%s'

Prints the date in seconds

cat file.txt | uniq

Display duplicate record only once

245
Command

cd ../../

Takes you three folders back

Command:

ps -ef | grep xlogo

Description:

List all the processes on the system containing the string 'xlogo'

echo -n "abc";echo "def"

abcdef

Is -Itr /etc List the files in / etc in order of last modification

246
Command:

Is -Rlh /var | grep [0-9]M

Description:

List the files in /var larger than 1 megabyte but less than 1 gigabyte

Command:

Is -IhS

Description:

List files by size

cat /etc/passwd /etc/group

# Display the contents of multiple files (/etc/passwd and /etc/group)

find /tmp -name *.txt -exec rm -f {} \;

# Searches for all files in the /tmp directory named *.txt and deletes them

echo "use" "of" "Linux"

use of Linux

247
watch -n 5 tail -n 3 /etc/passwd

# Display the end of the /etc/passwd file every 5 seconds

watch -n 1 'ls -l | wc -l'

# Monitor the number of files in a folder

watch -t -n 1 date

# Display the clock

find / -name "*.txt"

# Search all files with .txt extension

find . -name "*file*"

# Search all files containing "file" in the name

find /home -name "*file*"

# Search all files in /home containing "file" in the name

grep -nre "hello computer" ./*

# Search for files containing the string "hello computer" in the current directory

248
Command:

free -t -m

Display free memory size in MB

Command:

gnome-system-monitor

Description:

Displays what programs are running and how much processor time, memory and disk space are being used

lsblk -m

Display device permissions and ownership

lsblk -S

Display SCSI (Small Computer Systems Interface) devices

lsblk -n List devices without the header

249
Command:

Is -l ~

Description:

Check the file and folder permissions

Command:

Is ./Documents

Description:

Display the list of files that reside in the Documents folder

Is -R

# List out all the contents of subdirectories

compgen -c

# Displays the list of all commands which we can use in the command-line interface

• pwd -L ^ Prints a symbolic path

• pwd -P ^ Prints the actual full path

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

find . -iname "*.jpg"

Find files by case-insensitive extension (ex: .jpg, .JPG, .jpG)

find . -type f -perm 777

Find files by octal permission

cd logs; ls -lt | head; du -sh ; df -h


Concatenating all of the above tasks in a
single line using the ";" operator

251
{ echo "Albert Einstein"; pwd; uptime; date; }

1 Albert Einstein

/ home / manj u

00:26:53 up 28 min, 2 users, load average: 0.00, 0.01, 0.05


1 Tue Mar 29 00:26:53 PDT 2022

shutdown -r

# Kicks off a reboot

shutdown +0

# Shuts down the system immediately

shutdown -r +5

# Begins a reboot of the system in five minutes

252
Command:

kill 12838

Terminate the process with process ID 12838

shutdown -Fr now


Command:

ss -t -r state established
Force the file system check during
Description: reboot

List all the established ports

ss -t -r state listening

List all sockets in listening state

253
ls -al --time-style =+%D | grep 'date +%D'

mpstat -P 0

# Print processor statistics and helps to monitor CPU utilization on the system

chmod 777 myfiles.txt

# Assign (read, write and execute) permission to everyone

chmod 766 myfiles.txt

# Assign full permission to the owner and read and write permission to group and others

chmod -x myfiles.txt

# Remove the execution permission of myfiles.txt file

history 30

# List the last 30 commands we have entered on the system

find ~ -empty

# Find all empty files in home directory

gzip -l *.gz

# Display compression ratio of the compressed file

254
Command:

ps -efH | more

View current running processes in a tree structure

Command:

df -t

Description:

Display what type of file system

mkdir ~/temp

Creates a directory called temp under home directory

Is *py

# List all Python files

chsh -l

# Display the list of all shells

ipcs -a

# Display details about message queue, semaphore and shared memory

255
ipcs -q

Lists only message queues for which the current process has read access

ipcs -s

# List the accessible semaphores

ipcs -m

# List all the Shared Memory

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

# Display kernel slab cache information in real-time

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

# Display the DMA channels currently used

cat /proc/filesystems

# Display the file systems configured into the kernel

cat /proc/kmsg

# Display the messages generated by the kernel

cat /proc/loadavg

# Display the system load average

ls /proc/net

# List the network protocols

ls /etc/udev

# List the contents of udev configuration directory

cat /proc/stat

# Display the system operating statistics

cat /proc/uptime

# Display the time the system has been up

257
Command:

poweroff -i -f

Shutdown the system

[2 = 2 ] ; echo $?

# 0 (logically TRUE)

[ 2 = 6 ] ; echo $?

# 1 (logically FALSE)

type echo

# echo is a shell builtin

find /usr -print


systemctl list-timers
# Find and print all files under "/usr1
# List all timer units in memory

systemctl list-units --type=target


systemctl list-dependencies --all
# List all target unit configuration
# List dependency of all unit services

systemctl list-units --type=service


systemctl poweroff
# List all service unit configuration
# Shut down the system

systemctl list-sockets

# List all socket units in memory

258
systemctl reboot

# Shut down and reboot the system

netstat -ln --tcp


systemctl suspend
# Find listening TCP ports (numeric)
# Suspend the system

systemctl hibernate

# Hibernate the system

loginctl user-status

# Display terse runtime status information of the user of the caller's session

loginctl session-status

# Display terse runtime status information of the caller's session

ip route show

# Display all the routing table in numerical addresses

ip neigh

# Display the current content of the ARP (Address Resolution Protocol) cache tables

netstat -l --inet

# Find listening ports

259
Command:

atq

Lists the user's pending jobs

Isof | grep deleted

# Print all deleted files which are claiming disk space

echo $$

# Display the Process ID of the current process

echo $!

# Display the Process ID of most recently started background job

date --date="yesterday"

# Display yesterday 's date sudo parted -l

# Lists out the partition details

date --date="10 days ago"

# Display date 10 days ago df -h | grep A/dev

# Filter out real hard disk partitions/file systems

Is / | wc -w

# List the number of directories in Ithe root directory

sudo sfdisk -l -uM

# Display the size of each partition in MB

260
sudo blkid

# Displays information about available block devices

export NAME="Albert Einstein"


Is / > info.txt Albert Einstein
echo $NAME
cat info.txt

bin

boot TZ=US/Pacific date


dev # Display the current date/time in US/Pacific time zone

etc

home

lib ls -l /etc/shadow

lib64 # Display the user password stored in an encrypted form and the password expiry data

media

mnt sudo journalctl --since yesterday


opt
# Display all the logs since yesterday
proc

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

var # Display the total size of the journal logs

261
Command:

ls -m

Prints out directories and files separated by a comma

ls -Q

# Add quotation marks to all directories and files

ss -f unix echo *.desktop

# List Unix Sockets # Lists all of the .desktop files in the current directory

ss --raw

# List Raw Sockets

tracepath www.google.com

# Traces a path to a network host (www.google.com) discovering MTU along the path

echo -e "123\b4" 124 3 is over-written by 4

echo -e "123\r456 456


p 123 is overwritten by 456

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.'

► I'm a Linux Learner.

echo $USER

# Print the name of the currently logged in user

echo -e "\033[0;32mGREEN"

GREEN

echo -e "\033[0;31mRED"

echo -e 'Hello, \vWorld

1r

Hello,

World!

echo "This is the list of directories and files on this system: $(ls)"

This is the list of directories and files on this system: Desktop

Documents

Downloads

Music \

Pictures

Public

Templates

Videos

263
echo *s

# Print all files and folders that end by letter "s"

echo [[:upper:]]*

# Print all files and folders that start by upper case character

echo $((2 + 3))

^ 5

echo $(($((2**2)) * 3))

^ 12

echo Four divided by two equals $((4/2))

^ Four divided by two equals 2

echo Capital-{A,B,C}-Letter

^ Capital-A-Letter Capital-B-Letter Capital-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

^ xP1y xP2y xQ3y xQ4y

264
echo The total price is $500.00

— The total price is 00.00

echo -e "\aMy Laptop shut \"down\"."

echo "$USER $((3*2)) $(cal)" -My Laptop shut "down".

manju 6 March 2022 echo -e "C:\\WIK2N\\LINUX_OS.EXE"

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

echo "$(cal)" 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

echo The total price is \$500.00

-The total price is $500.00

265
sudo Isof -i -P -n | grep LISTEN
Check ports in use
sudo netstat -tulpn | grep LISTEN

sudo ss -tulw

# Check what ports are open

netstat -ap | grep ssh

# Find out on which port a program is running

[root@localhost manju]# ipcs -m -l


Lists the Limits for Inter-process
----- Shared Memory Limits-------- . . . .
Communication facility
max number of segments = 4096

max seg size (kbytes) = 18014398509465599

max total shared memory (kbytes) = 18014398442373116

min seg size (bytes) = 1

[root@localhost manju]# ipcs -m -p

Shared Memory Creator/Last-op PIDs

shmid owner cpid lpid


Display the process ids that accessed
131072 manju 2998 3135 Inter-process Communication facility
recently
163841 manju 2998 3135

327682 manju 3277 6920

360451 manju 2827 1406

266
[root@localhost manju]# ipcs -u

----- Messages Status -------

allocated queues = 0

used headers = 0 Display the status of current usage


of Inter-process Communication facility
used space = 0 bytes

----- Shared Memory Status ---

segments allocated 4

pages allocated 2432

pages resident 319

pages swapped 0

Swap performance: 0 attempts 0 successes

----- Semaphore Status -------

used arrays = 0

allocated semaphores = 0

dmidecode -t 16

# Display the maximum RAM supported by the system

dmidecode -t baseboard

# Display all the system baseboard related information

dmidecode -t bios

# Display the BIOS information

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

# Display the active network connections

netstat -r

# Display the kernel routing table

yum install nmap

# Install nmap on CentOS

nmap google.com

# Scan a hostname

nmap 193.169.1.1

# Scan a ip address

nmap --iflist

# Display host interfaces and routes

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*

# Print all files and folders beginning with "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

# Display the download status of active connections

netstat -x

# Display Information about all connections, listeners and shared endpoints for Network Direct

netstat -n

# Numerical display of addresses and port numbers

echo $LANG

# Display the language of a Linux system

echo "AAA" | grep AAA


echo "BBB" | grep -E 'AAA|BBB'
^ AAA
^ BBB

echo "AAA" | grep BBB

echo "AAA" | grep -E 'AAA| BBB'

^ AAA

270
echo "albert einstein" | tr a-z A-Z

^ ALBERT EINSTEIN

echo "albert einstein" | tr [:lower:] E

^ EEEEEE EEEEEEEE

echo " Albert Einstein was a German-born theoretical physicist." | fold -w 12

Albert Eins

tein was a G

erman-born t

heoretical p

hysicist.

echo " Albert Einstein was a German-born theoretical physicist." | fold -w 12 -s

Albert

Einstein

was a

German-born

theoretical

physicist.

printf "English theoretical physicist: %s\n" Hawking

- > English theoretical physicist: Hawking

271
Is /usr/bin | pr -3 -w 65 | head

# Display a directory listing of /usr/bin in a paginated, three-column output format

for i in A B C D; do echo $i; done

B Scientists=("Einstein" "Hawking" "Darwin"); for i


in ${Scientists[*]}; do echo $i; done
C

D Einstein

Hawking

Darwin
for i in {A..D}; do echo $i; done

B Scientists=("Einstein" "Hawking" "Darwin"); for i


in "${Scientists[*]}"; do echo $i; done
C

D Einstein Hawking Darwin

for i in file*.txt; 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

# Check the file system space Display disk space in


df -h
human-readable format

ls -alh

# List all folders in directory with details

find /home -name file.txt

# Check all files in /home directory with the name file.txt

find /home -iname File.txt

# Search all files in /home directory irrespective to case sensitive

find / -ctime +90

# Search for the files which were modified more than 90 days back

find / -size 0c

# Search all empty files

find / -size +1G

# Search all files and folders which are more than 1GB

df -a

# Display the file system's complete disk usage

df -i

# Display used and free inodes

273
du -ch *.png

# Display the size of each png file in the current directory

du -a /etc/ | sort -n -r | head -n 10

# List top 10 directories consuming disk space in /etc/

ac

# Display the total amount of time users are connected to the system

ac --individual-totals

# Display a report on login times for individual users

cancel

# Cancels print jobs

yum install finger

# Install finger tool (CentOS)

finger manju

# Display the details of a user "manju"

chfn

# Allows you to modify user's information

finger -s manju

# Display idle status and login details of a user "manju"

274
groups

# List all Groups the Current User is a Member of

id -nG

# List all Groups the Current User is a Member of

groupadd mygroup

# Create a new group named "mygroup"

groupdel mygroup

# Delete a group named "mygroup"

less /etc/group

# List all Groups

getent group

# List all Groups

usermod -a -G mygroup manju

# Add an existing user "manju" to a group "mygroup"

userdel manju

# Delete a user "manju"

chgrp mygroup test.txt

# 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

dmesg > kernel_messages.txt

# Read all messages from kernel ring buffer to a file "kernel_messages.txt"

dmesg | grep -i memory

# Display the kernel messages which relate to memory usage

egrep -c 'AHello|World$' myfiles.txt

# Count the number of lines in myfiles.txt which begin with the word 'Hello' or end with the word 'World'

ex myfiles.txt

# Edits the file myfiles.txt

expand myfiles.txt

# Expand the file myfiles.txt - changing tabs to spaces - and display on standard output

expand --tabs=10 myfiles.txt > myfiles0.txt

# 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

# Lists the history of commands

!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

# Display a reformatted version of the file "myfiles.txt "

fmt < myfiles.txt > myfiles0.txt

# Reformat "myfiles.txt" and write the output to the file "myfiles0.txt"

finger -p manju

# Display information about the user "manju"

fold -w5 myfiles.txt > myfiles0.txt

# Wrap thelines ofmyfiles.txt to a width of 5characters and writes the outputto myfiles0.txt

for file in *.txt ; do wc -l $file ; done

# Performs a wordcount of all files in the currentdirectory withthe .txt extension

277
grep manju /etc/passwd

# Search /etc/passwd for user "manju"

groupmod -n group mygroup

# Change the group "mygroup" to "group"

head myfiles.txt

# Display the first 10 lines of "myfiles.txt"

head -15 myfiles.txt

# Display the first 15 lines of "myfiles.txt"

head myfiles.txt myfiles0.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

# Display the first 5,000 lines of "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 operating system storage input and output statistics

last reboot | less

# Display listing of last logged in users and system last reboot time and date

278
last -x | less

# Display last shutdown date and time

last shutdown

# Display last shutdown date and time

ldd /bin/bash

# Display the shared library dependencies of the program /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 / List only open IPv6


network files
# List the contents of root directory

ls [aeiou]*

# List only files that begin with a vowel (a, e, i, o and u)

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

# Compress the file "myfiles.txt" into "myfiles.txt.xz"

xz -dk myfiles.txt.xz

# Decompress "myfiles.txt.xz" into "myfiles.txt"

mkdir -m a=rwx dir

# 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 line 3

more +/"Hello" 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

# Print netstat information every few second

netstat -natp

# Display statistics about active Internet connections

280
netstat -rn

# Display the routing table for all IP addresses bound to the server

netstat -an

# Display information about all active connections to the server

od -b myfiles.txt

# Display the contents of "myfiles.txt" in octal format

od -Ax -c myfiles.txt

# Display the contents of "myfiles.txt" in ASCII character format - with byte offsets displayed as hexadecimal

trap -l

# Display a list of signal names and their corresponding numbers

trap

# Display a list of the currently-set signal traps

yum list openssh

# Search for a package with a name "OpenSSH"

yum grouplist

# List all available Group Packages

yum repolist

# List all enabled Yum repositories

281
yum repolist all

# List all Enabled and Disabled Yum Repositories

paste 1.txt 2.txt

# Display the contents of 1.txt and 2.txt side-by-side

ls -a | pr -n -h "Files in $(pwd)" > dc.txt

cat dc.txt

2022-04-02 01:10 Files in /home/manju Page 1

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

^ Hi, I'm manju.

printf "%.*s" 6 "abcdefg"

^ abcdef

ps -eLf

# Get information about threads

ps axms

# Get information about threads

283
ip route list

# List current routing table

route -n

# Display routing table for all IPs bound to the server

script -c 'echo "Hello, World!"' hello.txt

Script started, file is hello.txt

Hello, World!

Script done, file is hello.txt

cat hello.txt

Script started on Sat 02 Apr 2022 03:24:52 AM PDT

Hello, World!

Script done on Sat 02 Apr 2022 03:24:52 AM PDT

sfdisk -s

# List the sizes of all disks

ls -d ~/.ssh

# Check if the .ssh directory exists or not

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

# Schedule the system to shut down at 8 A.M

shutdown 20:00

# Schedule the system to shut down at 8 P.M

shutdown +15 "The system will be shutdown in 15 minutes."

# Schedule the system to shut down in 15 minutes with the normal message alerting users that the system is shutting down

shutdown -P now

# Power off the system immediately

sleep 10

# Delay for 10 seconds

startx -- -depth 16

# Start an X session at 16 bits color depth

285
time cal

# Reports how long it took for the "cal" command to complete

tr "[:lower:]" "[:upper:]" < myfiles.txt

# Translate the contents of "myfiles.txt" to uppercase

tr -cd "[:print:]" < myfiles.txt

# Remove all non-printable characters from "myfiles.txt"

cat myfiles.txt xlsfonts

Hello World # Lists all fonts available to the default X server and display

tr -cs "[:alpha:]" "\n" < myfiles.txt

xset q
Hello

World

Display the values of all current X Window


uncompress myfiles.txt.xz
System preferences
# Uncompress the file "myfiles.txt.xz"

yes | rm -i *.txt
w manju

# Display information for the user named "manju"

Remove all files with the extension .txt


write albert
from the current directory
# Write a message to the user "albert"

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.

Below are some examples of where Linux is being used today:

• Android phones and tablets


• Servers
• TV, Cameras, DVD players, etc.
• Amazon
• Google
• U.S. Postal service
• New York Stock Exchange

Linux Operating System has primarily three components:

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

System Utility programs are responsible to do specialized tasks.

Important features of Linux Operating System:

• 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 ~]$ echo al{an,bert,exander}

alan albert alexander

[manju@localhost ~]$ mkdir {txt,doc,pdf}files

[manju@localhost ~]$ Is

txtfiles docfiles pdffiles

[manju@localhost ~]$ x=Albert; y="$x won \$100.00"; echo $y

Albert won $100.00

[manju@localhost ~]$ x=5; test $x -eq 10; echo $

1 exit status of the test command is 1

[manju@localhost ~]$ x=5; test $x -eq 5; echo $

exit status of the test command is 0


0

cat /etc/profile

# Display System login initialization file

cat /etc/bashrc

# Display System BASH shell configuration file

cat .bash_profile

# Display Login initialization file

290
[manju@localhost ~]$ date

Wed Sep 28 08:14:17 PDT 2022

[manju@localhost ~]$ alias x=date

[manju@localhost ~]$ x

Wed Sep 28 08:14:27 PDT 2022

[manju@localhost ~]$ echo $BASH_VERSION

4.2.46(1)-release Display the current BASH version number

[manju@localhost ~]$ echo $HISTCMD

290 Display the number of the current command in the history list

[manju@localhost ~]$ echo $HOSTTYPE

x86_64 Display the type of machine the host runs on

[manju@localhost ~]$ echo $OSTYPE

linux-gnu Display the operating system in use

[manju@localhost ~]$ echo $PPID

3563 Display the process ID for shell's parent shell

[manju@localhost ~]$ echo $SHLVL

2 Display the current shell level

[manju@localhost ~]$ echo $TERM

xterm-256color Display the terminal type

[manju@localhost ~]$ echo $EUID

1000
Display the Effective user ID

291
[manju@localhost ~]$ PS1="\d" __________________

Sun Oct 02 # Display the Current date ----------

[manju@localhost ~]$ PS1="\h"-*------------

localhost # Display the Hostname ---------

[manju@localhost ~]$ PS1="\s" ___________________________

bash # Display the Shell type currently active ---------

[manju@localhost ~]$ PS1="\t" ___________________________________

18:42:10 # Display the Time of day in hours, minutes, and seconds

[manju@localhost ~]$ PS1="\u"^---------

manju # Display the Username ---------

[manju@localhost ~]$ PS1="\v" ◄----------

4.2 # Display the Shell version ---------

PS1="\w" Display the full pathname of the current working directory

PS1="\W" Display the name of the current working directory

[manju@localhost ~]$ PS1="Hello\n World"

Hello

World

[manju@localhost ~]$ PS1="Hello \\ World"

Hello \ World

292
Directory Function

/ The top-level directory of a Linux system that holds all files, device

information, and system information organized into directories

/home Holds users ' home directories

/bin Contains every essential command and utility program

/usr Contains the commands and files that the system uses

/usr/bin Include utility programs and user-friendly commands

/usr/sbin Holds commands for system administration

/usr/lib Contains programming language libraries

/usr/share/doc Contains documentation for Linux

/usr/share/man Contains the online "man" files

/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

/var Holds a variety of files, including mailbox files

/dev Holds file interfaces for devices like printers and terminals

/etc Holds all system files, including configuration files

find myfiles -name '*.c' -ls

Using the -Is command, all files in the "myfiles" directory


with the .c extension are searched and displayed

293
find / -user manju -print

Finds every file in a user's home directory and every


file that user owns in other user directories

ls /usr/share/X11

# List the system X11 configuration and support files

ls /etc/X11

# List the configuration files

ls /etc/gdm

# Display the contents of GDM configuration directory

ls /usr/share/gdm

# Display the contents of GDM configuration directory for default settings and themes

ls /etc/gconf

# List the GConf configuration files

ls /usr/share/gnome

# List the Files used by GNOME applications

ls /usr/share/doc/gnome*

# Display the contents of Documentation for various GNOME packages, including libraries

294
Is /usr/share/icons

# List the Icons used in KDE desktop and applications

rpm -qa | more

# Displays a list of all installed packages

Is /etc/cron.d

# List the directory with numerous crontab files that is only accessible to the root user

ls /etc/cron.hourly

# List the directory for tasks performed hourly

ls /etc/cron.daily

# List the directory for tasks performed daily

ls /etc/cron.weekly

# List the directory for tasks performed weekly

ls /etc/cron.monthly

# List the directory for tasks performed monthly

ls /etc/mtab

# List the currently mounted file systems

ls /etc/services

# List the services run on the system and the ports they use

295
Is /etc/cups

# List the CUPS printer configuration files

Is /proc/net

# List the Directory for network devices

free -s 3

# Display the current usage status of Memory continuously after regular interval

ls -lhR /var | grep \- | grep [1-9]*M

# List "/var" files larger than 1 MB but less than 1 GB

whereis -b ls

# Search only the binary file related to a command "ls"

whereis -m ls

# Searches only for man pages related to a command "ls"

whereis -s ls

# Searches only for source files related to a command "ls"

[manju@localhost ~]$ echo "Alan" "Mathison" "Turing"

Alan Mathison Turing

296
watch -t -n 1 date

# Display the date

[manju@localhost ~]$ echo "Albert" > 1.txt && cat 1.txt

Albert

du -sh * --time

# Check each file's size and the date and time it was last edited

dmidecode -s system-serial-number

# Display the serial number of Linux server

ls -aril

# Display all the files with sequence number

yum search mod_

# Display all the modules

du -sch *

# Display the sum of size of all files and folders in present directory

dmidecode | grep -A3 'ASystem Information'

# Display the server hardware name and model

dmesg | grep -i firmware

# Display all firmware error

297
cat /proc/cpuinfo | grep processor | wc -l

# Display the number of cores

netstat -ap | grep 80

# Display the process id which is using port number 80

dmidecode --type memory

# Display the physical memory attached to the Server

dirs

# Display the list of currently remembered directories

blkid -i /dev/sda
# Display information about available block devices

crontab -e <

This command runs crontab

[manju@localhost ~]$ df -h /home

Filesystem Size Used Avail Use% Mounted on

/dev/sda3 18G 5.2G 13G 29% /

Look for free disk space using the df command within


the /home directory

298
[manju@localhost ~]$ hostname -I

192.168.6.131 192.168.122.1

Display all local IP addresses of the host

badblocks -s /dev/sda

# Check for unreadable blocks on disk sda

tail -10 /var/log/messages

# Display the last10 syslog messages

lsof -u manju

# List files opened by the user "manju"

sudo shutdown -r 2

# Shuts down and reboots the machine in 2 minutes

[manju@localhost ~]$ cat 1.txt

albert

[manju@localhost ~]$ cat 1.txt | tr a-z A-Z > 2.txt

[manju@localhost ~]$ cat 2.txt

ALBERT

cat /etc/passwd | column -t -s :

# Display the contents of "/etc/passwd" in column

299
nmcli d

# Display the status of all network interfaces

grep "A[[:alnum:]]" myfiles.txt

# Search for a line which will start with alphanumeric characters in "myfiles.txt"

grep "A[[:alpha:]]" myfiles.txt

# Search for a line which will start with alpha characters in "myfiles.txt"

grep "A[[:blank:]]" myfiles.txt

# Search for a line which will start with blank characters in "myfiles.txt"

grep ”A[[:digit:]]” myfiles.txt

# Search for a line which will start with digit characters in "myfiles.txt"

grep "A[[:lower:]]" myfiles.txt

# Search for a line which will start with lowercase letters in "myfiles.txt"

grep "A[[:punct:]]" myfiles.txt

# Search for a line which will start with punctuation characters in "myfiles.txt"

grep "A[[:graph:]]" myfiles.txt

# Search for a line which will start with graphical characters in "myfiles.txt"

grep "A[[:print:]]" myfiles.txt

# Search for a line which will start with printable characters in "myfiles.txt"

300
grep "A[[:space:]]" myfiles.txt

# Search for a line which will start with space charactersin "myfiles.txt"

grep "A[[:upper:]]" myfiles.txt

# Search for a line which will start with uppercase letters in "myfiles.txt"

grep "A[[:xdigit:]]" myfiles.txt

# Search for a line which will start with hexadecimal digits in "myfiles.txt"

vmstat -a

# Display active and inactive system memory

vmstat -s

# Display memory and scheduling statistics

vmstat -f

# Display number of forks created since system boot

vmstat -D

# Display a quick summary statistic of all disk activity

vmstat -d

# Display a detailed statistic on each disk usage

This command is used to update the statistics every five


vmstat 5 -S M seconds and change the display units to megabytes

301
[manju@localhost ~]$ free -h --total

total used free shared buff/cache available

Mem: 976M 566M 75M 8.7M 334M 209M

Swap: 2.0G 84K 2.0G

Total: 3.0G 566M 2.1G

• hostname -s
Display the short version of the hostname
• hostname --short

hostname --all-ip-addresses

# Display All Network Addresses

date -r /etc/hosts

# Display Last Modified Timestamp of a Date File

[manju@localhost ~]$ cat 1.txt

Albert Einstein

[manju@localhost ~]$ cat 2.txt

Elsa Einstein

[manju@localhost ~]$ cat 1.txt > 2.txt

[manju@localhost ~]$ cat 2.txt

Albert Einstein

302
[manju@localhost ~]$ cat 12.txt

Albert Einstein

Elsa Einstein

[manju@localhost ~]$ cat -n 12.txt

1 Albert Einstein
2 Elsa Einstein

[manju@localhost ~]$ cat 1.txt

Albert Einstein

[manju@localhost ~]$ cat -e 1.txt

Albert Einstein$

sudo shutdown 08:00

# Shutdown the system at 8 AM in the morning

grep 'but\|is' phy.txt

# Search for the words "but" and "is" in the phy.txt file

grep 'is\|but\|of' phy.txt

# Search for the words "but", "is" and "of" in the phy.txt file

grep -e but -e is -e of phy.txt

303
echo "The system will be shutdown in 10 minutes." | wall
I_____________________


The message (The system will be shutdown in 10 minutes.) will
be broadcasted to all users that are currently logged in

[manju@localhost ~]$ echo -e 'Albert Einstein'

Albert Einstein

[manju@localhost ~]$ echo -e 'Albert \c Einstein'

Albert [manju@localhost ~]$

ss --all

# List all listening and non-listening connections

ss --listen

# List only listening sockets

ss -t state listening

# Find all listening TCP connections

[manju@localhost ~]$ hostname -I | awk '{print $1}'

192.168.6.131

System's IP address

304
yum erase httpd

# Uninstall apache

• read has the value of 4


• write has the value of 2
• execute has the value of 1
• no permission has the value of 0

chmod 644 1.txt

• User: 6 = 4 + 2 (read and write)


• Group: 4 = 4 + 0 + 0 (read)
• Others: 4 = 4 + 0 + 0 (read)

• 7 = 4 + 2 + 1 (read, write and execute)


• 6 = 4 + 2 + 0 (read and write)

• 5 = 4 + 0 + 1 (read and execute)

• 4 = 4 + 0 + 0 (read)

rpm -qi httpd

# Display information about a particular package (apache)

sudo rpm -qa | wc -l

# Display the total number of packages installed

sudo repoquery -a --installed

# List all installed packages with the repoquery command

305
cat /var/log/boot.log

# Display all information related to booting operations

cat /var/log/maillog

# Display all information related to mail servers and archiving emails

cat /var/log/yum.log

# Display Yum command logs

mkdir -m777 myfiles

# Create a directory "myfiles" with read, write and execute permissions

rpm -qa centos-release

# Display CentOS version

ps -AlFH

# Get information about threads (LWP and NLWP)

• ps -eM Get Security Information of Linux Process


• ps axZ

ps -auxf | sort -nr -k 4 | head -10

# Display the top 10 memory consuming process

306
ps -auxf | sort -nr -k 3 | head -10

# Display the top 10 CPU consuming process

sar -n DEV | more

# Monitor, collect and report Linux system activity

# create or overwrite "1.txt" file


echo "Albert Einstein" > 1.txt

# create or append to "1.txt" file


echo "Albert Einstein" >> 1.txt

grep -i "is" phy.txt

# Search for a given string in a file "phy.txt"

grep -A 3 -i "is" phy.txt

# Print the matched line and the following three lines

grep -r "is" *

# Recursively look for a given string in all files

export | grep ORACLE

# Display oracle related environment variables

307
chkconfig --list | grep network

# View the startup configuration of Linux network service

shutdown -r 18:30

# Shutdown the system immediately and reboot at 18:30

find /home -size +1024 -print

# Find files above 1MB in home directory

find /home -size +1024 -size -4096 -print

# Find files above 1Mb and below 4MB in home directory

netstat -ain

# Display the Kernel Interface table

sar -n SOCK | more

# Display networking Statistics

find /home -size +10000k

# Find files greater than 10000k in the home directory

ls -ld /home

# List information about the home directory instead of its contents

308
chmod go=+r 1.txt

# Add read permission for the owner and the group

I chown manju 1.txt


# Change ownership of a file "1.txt" to user "manju"
du -sh *

# Display the disk usages of the files in the current directory

du -sh .[!.]* *

# Display the disk usages of the files (including hidden files) in the current directory

du -sch .[!.]* *

Display the total disk usage of the files


(including hidden files) in the current directory

du --threshold=1G -sh .[!.]* *

Display only files with more than 1GB in size which


located under current directory

309
iostat -kx

# Display general information about the disk operations in real time

Parted is a well-known command line


netstat -ntlp
tool that allows us to easily manage
# Display open TCP sockets hard disk partitions

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

losetup
# Exit the parted shell
# Display information about all loop devices

310
sudo tcpdump -D

# List of all available network interfaces in the system

[manju@localhost ~]$ xz myfiles.txt

[manju@localhost ~]$ ls | grep myfiles


Compress a file "myfiles.txt"

myfiles using xz command

myfiles.txt.xz

[manju@localhost ~]$ free -t | awk 'NR == 2 {print $3/$2*100}'

61.852

[manju@localhost ~]$ free -t | awk 'FNR == 2 {print $3/$2*100}'

61.852

Display Memory Utilization

311
[manju@localhost ~]$ free -t | awk 'NR == 3 {print $3/$2*100}'

2.54155

[manju@localhost ~]$ free -t | awk 'FNR == 3 {print $3/$2*100}'

2.54155
Display Swap Utilization

[manju@localhost ~]$ free -t | awk 'FNR == 2 {printf("%.2f% \n"), $3/$2*100}'

61.86%

[manju@localhost ~]$ free -t | awk 'NR == 2 {printf("%.2f% \n"), $3/$2*100}'

61.86%

Display Memory Utilization with Percent Symbol and two decimal places

[manju@localhost ~]$ free -t | awk 'FNR == 3 {printf("%.2f% \n"), $3/$2*100}'

2.65%

[manju@localhost ~]$ free -t | awk 'NR == 3 {printf("%.2f% \n"), $3/$2*100}'

2.65%

Display Swap Utilization with Percent Symbol and two decimal places

312
[manju@localhost ~]$ top -b -n1 | grep A%Cpu | awk '{cpu+=$9}END{print 100-cpu/NR}'

100
Display CPU Utilization

[manju@localhost ~]$ top -b -n1 | grep A%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

# Print swap usage summaries

alias -p

# List all Aliases


swapon -a

# Activate all of swap space


lsof -i :8080

# Check which process is running on port 8080


swapoff -a

# Deactivate all of swap space

[manju@localhost ~]$ cat /etc/system-release <

CentOS Linux release 7.3.1611 (Core)

Display the version of CentOS

313
sudo netstat -anp | grep tcp | grep LISTEN

# Display the various in-use ports and the process using it

sudo netstat -anp | grep 8080

# Display the process listening on port 8080

printf "%s\n" *

# Prints the files and directories that are in the current directory

printf "%s\n" */

# Prints only the directories in the current directory

printf "%s\n" *.{gif,jpg,png}

# Lists only some image files

[manju@localhost ~]$ alias x='date' # create an alias

[manju@localhost ~]$ x # preview the alias

Fri Oct 7 03:51:39 PDT 2022

[manju@localhost ~]$ unalias x # remove the alias

[manju@localhost ~]$ x

bash: x: command not found...

314
[manju@localhost ~]$ x="alan"; printf '%s\n' "${xA}"

Alan

[manju@localhost ~]$ x="alan"; printf '%s\n' "${xaa}"

ALAN

[manju@localhost ~]$ x="alan"; declare -u name="$x"; echo "$name"

ALAN

find . -name "xyz[a-z][0-9]"

Find directories and files with names starting with "xyz" and
ending with an alpha character after a one-digit

find . -mmin -120

# Search for files changed duringthe previous two hours

find . -mmin +120

# Search for files thathaven'tbeen updatedin the past two hours

find . -mtime -3

# Find files that have been modifiedwithin the last 3days

find . -mtime +3

# Find files that have not beenmodified 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

[manju@localhost ~]$ awk '{print $2}' <<< "Alan Mathison Turing"

Mathison

[manju@localhost ~]$ awk '{print $1}' <<< "Alan Mathison Turing"

Alan

x='4 * 2'; echo "$x"

# prints 4 * 2

x='4 * 2'; echo $x

# prints 4, the list of files in the current directory, and 2

316
x='4 * 2'; echo "$(($x))"

# prints 8

[manju@localhost ~]$ x="ALAN"; printf '%s\n' "${x,}"

aLAN

[manju@localhost ~]$ x="ALAN"; printf '%s\n' "${x,,}"

alan

[manju@localhost ~]$ x="Alan"; echo "${x—}"

aLAN

[manju@localhost ~]$ x="Alan"; echo "${x~}"

alan

[manju@localhost ~]$ x='You are a genius'; echo "${x/a/A}"

You Are a genius

[manju@localhost ~]$ x='You are a genius'; echo "${x//a/A}"

You Are A genius

[manju@localhost ~]$ x='You are a genius'; echo "${x/%s/N}"

You are a geniuN

[manju@localhost ~]$ x='You are a genius'; echo "${x/s/}"

You are a geniu

317
[manju@localhost ~]$ x='You are a genius'; echo "${x#*a}"

re a genius

[manju@localhost ~]$ x='You are a genius'; echo "${x#*g}"

enius

[manju@localhost ~]$ foo=25; i=foo; echo ${i}

foo

[manju@localhost ~]$ foo=25; i=foo; echo ${!i}

25

[manju@localhost ~]$ x='You are a genius'; echo "${x%a*}"

You are

[manju@localhost ~]$ x='You are a genius'; echo "${x%%a*}"

You

[manju@localhost ~]$ x=Bob-Dev-Fox; echo ${x%%-*}

Bob

[manju@localhost ~]$ x=Bob-Dev-Fox; echo ${x%-*}

Bob-Dev

[manju@localhost ~]$ x=Bob-Dev-Fox; echo ${x##*-}

Fox

[manju@localhost ~]$ x=Bob-Dev-Fox; echo ${x#*-}

Dev-Fox

318
find . -type f -path '*/Documents/*'

# Find only files within a folder called Documents

find . -type f -path '*/Documents/*' -o -path '*/ Downloads/*'

# Find only files within a folder called Documents or Downloads

find . -type f -not -path '*/Documents/*'

# Find all files except the ones contained in a folder called Documents

find . -type f -not -path '*log' -not -path '*/Documents/*'

# Find all files except the ones contained in a folder called Documents or log files

[manju@localhost ~]$ find /dev -type b

/dev/sr0 [manju@localhost ~]$ echo '16 / 5' | bc


/dev/sda3
3
/dev/sda2 Block devices
[manju@localhost ~]$ echo '16 / 5' | bc -l
/dev/sda1
3.20000000000000000000
/dev/sda

find . -maxdepth 1 -type f -name "*.txt"

# Find every.txt file from the current directory alone

[manju@localhost ~]$ echo "$(printf "%04d" "${x}")"

0000

319
[manju@localhost ~]$ echo "$(printf "%05d" "${x}")"

00000

[manju@localhost ~]$ echo "\"'\""

[manju@localhost ~]$ echo '3 5 + p' | dc

[manju@localhost ~]$ dc <<< '3 5 + p'

[manju@localhost ~]$ echo '3 5 * p' | dc

15

[manju@localhost ~]$ dc <<< '3 5 * p'

15

[manju@localhost ~]$ expr 'Alan Turing' : 'Ala\(.*\)ring'

n Tu

[manju@localhost ~]$ echo '12 == 12 && 18 > 12' | bc

1 (True)

[manju@localhost ~]$ echo '12 == 13 && 18 > 12' | bc

0 (False)

320
[manju@localhost ~]$ expr PQRSTUVWXYZ : PQRS

4 Display the number of matching characters

Is -ral

# Listing of all files in reverse alphabetical order

• ls -tl
• ls -trl

# List the files such that the one that was most recently edited is at the top of the list

find . -regex ".*\(\.sh\|\.txt\)$"

# Find .sh or .txt files

[manju@localhost ~]$ find . -iregex ".*\(\.sh\|\.pdf\)$"

./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

[manju@localhost ~]$ cat 1.txt

albert

• ps -eLf --sort -nlwp | head


• ps -eLf

Display information about process threads

systemctl -l -t service | less

# List all Systemd services

[manju@localhost ~]$ echo -e "Albert\nTesla\nJohn"

Albert

Tesla

John

[manju@localhost ~]$ echo -e "Albert\nTesla\nJohn" | nl

1 Albert

2 Tesla

3 John

322
[manju@localhost ~]$ echo -e "Albert\nTesla\nJohn" | nl -s ": " -w 1

1: Albert

2: Tesla

3: John

whiptail --yesno "Do you wish to proceed?" 10 40

# Display a simple yes or no input box on the command-line with whiptail

du -h -d1

# Check only the current directory's file space usage.

sudo nmcli networking off Restart network service


using nmcli tools
sudo nmcli networking on

find / - manju

# Find files and directories owned by user "manju"

locate "*.png"

# Find all files containing '.png' in the name

find . -name '*.txt' -type f -delete

Find all files with '.txt' extension in the current


directory, including subdirectories and delete them

323
find . -type f -printf "\"%p\" " | xargs chmod 664

# Find all files in the current directory, including subfolders and assign rights 664

find . -type d -printf "\"%p\" " | xargs chmod 775

# Find all files in the current directory, including subfolders and assign rights 775

ll
ls -l
# List the files in current directory

sudo netstat -nltp

# Display all open ports by process

date +%j

# Convert current date into Julian format

date -d "2022/03/13" +%j

# Convert a specific date into Julian format

date +%Y%m%d

# Display current date in YYYYMMDD format

date +%d\/%m\/%Y

# Display current date in DD/MM/YYYY format

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:

Write a program to print Hello, World!.

#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:

Write a program to compute the perimeter and area of a rectangle.

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:

Write a program to compute the perimeter and area of a circle.

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;
}

Numerous additional programming languages,

including C++, Java, JavaScript, Go, C#, PHP, Python,

Perl, C-shell, and many others, are based on C.

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> "X
1
int main() { In C Language: if
the variable is not
int a;
Solution: assigned a value, it
printf("%d", a); takes a garbage
#include<stdio.h> return 0; value.
int main() {
} ->
int a, b, sum;
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
scanf("%d", &b);
sum = a + b;
printf("\nSum of the above two numbers is: %d", sum);
return 0;
}

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 main() { Output:
int a, b, mult;
printf("\nEnter the first number: "); Message();
Hello, World!
scanf("%d", &a); }
printf("\nEnter the second number: ");
scanf("%d", &b);
mult = a * b;
printf("\nProduct of the above two numbers is: %d", mult);
return 0;
}

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);

// if x is greater than both y and z, x is the largest


if (x >= y && x >= z)
printf("\n%d is the largest number.", x);

// if y is greater than both x and z, y is the largest


if (y >= x && y >= z)
printf("\n%d is the largest number.", y);

// if z is greater than both x and y, z is the largest


if (z >= x && z >= y)
printf("\n%d is the largest number.", 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>

int main() { int main() {


float x, y, z; Comments cann
printf("Hello World")
be nested.
printf("\nEnter the first number: ");
return 0;
scanf("%f", &x);
printf("\nEnter the second number: "); }

scanf("%f", &y);
printf("\nEnter the third number: "); Error
scanf("%f", &z);

if(x < (y+z) && y < (x+z) && z < (y+x)) {


printf("\nPerimeter of the triangle is: %f\n", x+y+z);
}
else {
printf("\nIt is impossible to form a triangle.");
}
return 0;
}

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:

Write a program to find the sum of two numbers.

As it only supports scalar operations, C is now

often regarded as a low level language among


Solution:
programmers, contrary to how it was once
#include<stdio.h> thought to be a high level language.
int main() {
int a, b, sum;

332
a=1;
b=2;
sum = a + b;
printf("The sum of a and b = %d", sum);
return 0;
}

Question 10

Question:

Write a program to find the square of a number.

Solution:

#include<stdio.h>
#include<stdio.h>
#include<math.h> extern int a;

int main() { int main()


int a, b;
{
a=2;
printf("a = %d", a);
b = pow((a), 2);
printf("The square of a = %d", b); }

return 0; int a = 1;

}
Output:

a = 1

333
Question 11

Question:

Write a program to find the greatest of two numbers.

Solution: #include<stdio.h>

#define merge(a, b) a##b


#include<stdio.h>
int main()
int main() {
int a, b; {

a = 2; printf("%d ", merge(12, 09));


b = 3; return 0;
if(a>b) {
}
printf("a is greater than b");
} Output:
else {
1209
printf("b is greater than a");
}
return 0;
}

Question 12

Question:

Write a program to print the average of the elements in the array.

334
Solution:

#include<stdio.h>
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;
}
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 14 The most widely used operating system,

Linux, has a C-based kernel.

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() {
}
char c = 'a';
return 0;
} 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;

for(a=1; a<=5; a++) {


Question 16
for(b=1; b<=a; b++)

printf("%d", b);
Output:
Question:
printf("\n");
1
Write a program: }
12
If you enter a character M return 0;

Output must be: ch = M. }


123

1234

12345
Solution:

337
#include<stdio.h> #include<stdio.h>

int main() { int main() {


char M; int x = 50, y, z;
printf("Enter any character: ");
if(x >= 50) {
scanf("%c", &M);
printf("ch = %c", M); y = 15;

return 0; z = 28;

} printf("\n%d %d", y, z);

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;

for(i=1; i<=5; i++) { }


printf("%d * %d = %d\n", n, i, n*i);
}
Output:
return 0;
} 12.750000

338
Question 18

Question:

Write a program to print the product of the first 10 digits.

The only ternary operator in


Solution:
the C language is "?:"
#include<stdio.h>
int main() {
int i, product = 1;
for(i=1; i<=10; i++) {
product = product * i;
}
printf("The product of the first 10 digits is: %d", product);
return 0;
}

Question 19

Question:

Write a program to print whether the given number is positive or negative.

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.

Solution: "sizeof" is the only operator

which is also a keyword.


#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);
c = a%b;
printf("\nThe remainder of %d and %d is: %d", a, b, c);
return 0;
}

341
Question 22

Question:

Write a program to print the characters from A to Z.

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:

Write a program to print the length of the entered string.

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.

Solution: In printf() and scanf(), f stands for


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.

Solution: There must be a function named

main() in every C program.


#include<stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
if(isupper(ch)) {
printf("The given character is a upper case letter");
}
else {
printf("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.

344
Solution:
In a C program, any number of functions can be written.

#include<stdio.h> In C, there are two different sorts of functions: user-


#include <ctype.h> defined functions and library functions.
int main() {
char ch = 'a';
char b = toupper(ch);
printf("Lower case letter '%c' is converted to Upper case letter '%c'", ch,
b);
return 0;
}

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) {

i = i - 3;
#include<stdio.h>
printf ("%d\n", i);
#define x 2.54
int main() {
double inch, cm; }
printf("Enter the distance in cm: ");
return 0;
scanf("%lf", &cm);
}

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() {

Question: const int i = 54;

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:

Write a program to print "Hello World" 10 times.

#include<stdio.h>

int main() {
Solution:

#include<stdio.h>
int main() {
for(int i=1; i<=10; i++) {
printf("Hello World \n");
}
return 0;
}

Question 30

Question:

Write a program to print first 5 numbers using do while loop statement.

Solution:

347
It -L. nr Vt X _» V Vt -LV<n « 11/
1 1 -L.1 i irlo/ctdi hs
#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++); 1
return 0; Output:
} while(i<=5);
return 0; } CProgram

Question 31

Question:

Write a program to check whether a character is an alphabet or not.

#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"

if(isalpha(a)) { };
printf("The character a is an alphabet");
int i;
}
for(i=0; i<SIZE; i++)
else {
puts(names[i]);
printf("The character a is not an alphabet");
} return 0;

return 0;
}
}

348
Question 32

Question:

Write a program to check whether a entered number is even or odd.

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:

Write a program to print the ASCII value of the given character.

349
Solution:

#include<stdio.h>
int main() {
char ch = 'A';
printf("The ASCII value of %c is: %d", ch, ch);
return 0;
}

Because it enables bit fields and dynamic

memory allocation, the C programming language


Question 34
helps with memory management.

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> "X
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:

Write a program to determine whether two numbers in a pair are in ascending or

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");

printf("\nEnter the second number: "); }


scanf("%d", &b);
return 0;
if(b != 0) {
}
c = (float)a/(float)b;
printf("\n%d/%d = %.1f", a, b, c);
Output:
}
else { a and b are equal
printf("\nDivision not possible.\n");
}
return 0;
}

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;

printf("Enter a number: "); c = a < 25;


scanf("%d", &x); printf ("\na = %d b = %d c = %d", a, b, c);
for(i=1; i<=50; i++) {
return 0;
if((i%x)==2 || (i%x) == 3) {
printf("%d\n", i); }

}
}
return 0;
}

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) {

sum += i; printf("Albert Einstein");

} }
}
else {
printf("\nSum: %d\n", sum);
printf("Elsa Einstein");
return 0;
} }

return 0; Output:

} Albert Einstein

Question 39

Question:

Write a program to calculate the value of x where x = 1 + 1/2 + 1/3 + ... + 1/50.

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.

Solution:

#include<stdio.h>
int main() {
int a, b, c, d, e, f;
a = 10;
b=12;
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:

Write a program to find square of a entered number using functions.

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>
}
int square() { int main() {

int x; int a = 6, b, c;
printf("Enter any number: ");
b = ++a;
scanf("%d", &x);
c = a++;
return x*x;
printf ("%d %d %d\n", a, b, c);
}
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() {
int p,r,t,SI;
printf("\nEnter the principal amount: ");
scanf("%d",&p);
printf("\nEnter the rate of interest: ");
scanf("%d",&r);
printf("\nEnter the time: ");
scanf("%d",&t);
SI=(p*r*t)/100;
printf("\nSimple interest is: %d", SI);
return 0;
}

Question 44

Question:

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) {

int main() { printf("a = b");


int x, y, *p, *q;
}
printf("Enter the value for x: ");
else if(a > b) {
scanf("%d", &x);
printf("a > b");
printf("Enter the value for y: ");
scanf("%d", &y); }

p = &x; else if(a < b) {


q = &y; printf("a < b");
if(*p>*q) {
}
printf("x is greater than y");
return 0;
} Output:
if(*q>*p) {
a< b
printf("y is greater than x");

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:

If purchase value is greater than 1000, 10% discount


If purchase value is greater than 5000, 20% discount
If purchase value is greater than 10000, 30% discount.

#include<stdio.h>

int main() {
Solution:
printf("%%15s = %15s\n", "albert");

#include<stdio.h> printf("%%14s = %14s\n", "albert");

int main() { printf("%%13s = %13s\n", "albert");


double PV;
printf("%%12s = %12s\n", "albert");
printf("Enter purchased value: ");
printf("%%11s = %11s\n", "albert");
scanf("%lf", &PV);
if(PV>1000) { printf("%%10s = %10s\n", "albert");

printf("\n Discount = %lf", PV* 0.1); printf(" %%9s = %9s\n", "albert");


printf("\n Total = %lf", PV - PV* 0.1); printf(" %%8s = %8s\n", "albert");
}
printf(" %%7s = %7s\n", "albert");
else if(PV>5000) {
printf(" %%6s = %6s\n", "albert");
printf("\n Discount = %lf", PV* 0.2);
printf("\n Total = %lf", PV - PV* 0.2); printf(" %%5s = %5s\n", "albert");

} printf(" %%4s = %4s\n", "albert");


else {
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) {

while (i<=10) { printf("\nHi");


printf("%d\n", i++); printf("\nEinstein");
}
}
return 0;
else {
}
printf( "Bye Elsa" ); Output:

} Hi
return 0;
Question 49 Einstein
}

Question:

Write a program to shift inputted data by two bits to the left.

362
Solution:

#include<stdio.h>
int main() {
int x;
printf("Enter the integer from keyboard: ");
scanf("%d",&x);
printf("\nEntered value: %d ",x);
printf("\nThe left shifted data is: %d ", x<<=2);
return 0;
}

Question 50

Question:

Write a program to shift inputted data by two bits to the Right.

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.

Because C is a structured (modular) programming


Solution:
language, programmers can divide their code into smaller
#include<stdlib.h> chunks to make it easier to comprehend and, as a result,
#include<stdio.h>
make their programs simpler and less redundant.
int main() {
int x;
printf("Enter the value for x: ");
scanf("%d",&x);
if(x<=21){
printf("%d", abs(x-21));
#include<stdio.h>
}
int main() {
else if(x>=21) {
printf("%d", abs(x-21)*3); int x = 25, y;

} x >= 16 ? (y = 25) : (y = 30);


return 0;
printf ("\n%d %d", x, y);
}
return 0;

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;

(x == 10 ? printf( "True" ) : printf( "False" ));

return 0;
Output:

True

365
Question 53

Question:

Write a program to print the output:


Name of the book = B

Price of the book = 135.00


Number of pages = 300
Edition of the book = 8

using structures.
#include<stdio.h>

int main() {
Output:
int num, x, y, z;
Solution:
printf("Enter a three digit number: ");
#include<stdio.h> 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;
bl.name = 'B';
bl.price = 135.00;
bl.pages = 300;
bl.edition = 8;
printf("\n Name of the book = %c", bl.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:

Write a program to convert Celsius into Fahrenheit.

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

is 50 or if their sum is 50.

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 {

if(x % 2 == 0) { printf("\nHi Albert!");


even++;
}
}
return 0; Output:
if(x % 2 != 0) {
odd++; } Albert
}
}
printf("\nNumber of even values: %d", even);
printf("\nNumber of odd values: %d", odd);
printf("\nNumber of positive values: %d", positive);
printf("\nNumber of negative values: %d", negative);
return 0;

#include<stdio.h>

int main() {

switch(printf("Albert Einstein")){}

return 0;
Output:
}
Albert Einstein

369
Question 57

Question:

Write a program to check whether the person is a senior citizen or not.

#include<stdio.h>

int main() {
Solution:
int x;

#include<stdio.h> printf("Enter any number: ");

int main() { scanf ("%d", &x);


int age;
if(x > 100) {
printf("Enter age: ");
printf ("\nAlbert");
scanf("%d", &age);
if(age>=60) { }

printf("Senior citizen"); else {

} if(x < 15)


else {
printf ("\nElsa");
printf("Not a senior citizen");
else
}
return 0; printf ("\nDavid");

} }

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:

What results would the following programs produce?

371
#include<stdio.h>
#include<stdio.h>
int main() {
for(int i=1; i<=5; i++) { int main() {

if(i==3) { int a = 15, b = 4;


break;
float c = (float)a/(float)b;
}
printf("%d/%d = %.2f\n", a, b, c);
printf("%d\n", i);
return 0;
}
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>
int main() { printf ("\n%d %d %d", a, b, c);

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;

This loop will run forever. }


This loop will run forever. Output:
This loop will run forever..........
4.700000

#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
printf("%d" }

return 0; else {

} printf("\n%d %d", a, b);

}
Output
}
35
return 0;

Solution: 26
}

1 7
10
08

-1 9

375
#include<stdio.h>
#include<stdio.h>
#define A 15 int main() {

int main() { int x = 0;

int x; for ( ; x ; )
x=A;
printf ("\nAlbert");
printf("%d", x);
return 0;
return 0;
} }

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;

b = fabs(a); float y = 2.0;


printf("|%.2lf| = %.2lf\n", a, b); switch (x = y + 3) {
return 0;
case 5:
}
printf("\nAlbert");

break;

default:

printf("\nElsa");
Solution:
}

|-2.50| = 2.50 return 0;

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 :

printf("%d\n", -(-x-y)); printf("\nMary");


return 0; default :
}
printf("\nJames");

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++) {

printf("\n%d", *(y + x));

}
Solution: Output:
return 0;

15 } 20

40

60

80
Question 60
100

Question:

Write a program to find the size of an array.

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() {

for(i=1; i<x; i++) { char i[2] = "B";


printf("%d+", i);
printf("\n%c", i[0]);
}
printf("\n%s", i);
printf("%d\n", i);
return 0;
}
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() {

int x = 53286, y=0, i;


Solution:
while(x!=0) {

#include<stdio.h> i=x%10;

int myfunc(); y=y*10+i;


int main() {
x/=10;
printf("%d", myfunc(3, 5));
}
printf("\n%d", myfunc(6, 6));
return 0; printf("%d", y);

} 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() {

float num[5] = { 11.5, 12.5, 13.5, 14.5, 15.5 };


Solution:
printf("%.1f\n", *(num+1));

#include<stdio.h> printf("%.1f\n", *(num+4));


int main() { return 0;
int mins, hrs;
}
printf("Input minutes: ");
scanf("%d",&mins);
hrs=mins/60;
15.5
mins=mins%60;
printf("\n%d Hours, %d Minutes.\n", hrs, mins);
return 0;
}

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;

scanf("%d", &x); int a = MULT(x++);


if(x % 3 == 0 || x % 5 == 0) { int b = MULT(++x);
printf("True");
printf("\n%d %d", a, b);
}
return 0;
else {
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

of 100 to 200 included.

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() {

printf("False"); char x[] = "Albert";


} int i = 0;
return 0;
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() {

printf("%-9s al\n", "alan");


Solution:
printf("%-8s al\n", "alan");

#include<stdio.h> printf("%-7s al\n", "alan");


int main() { printf("%-6s al\n", "alan");
int x;
printf("%-5s al\n", "alan");
printf("\nEnter a number: ");
printf("%-4s al\n", "alan");
scanf("%d", &x);
if(x % 3 == 0 A x % 5 == 0) { return 0;

printf("True"); } 2

}
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); }

if(abs(x % 10) == abs(y % 10)) { else {


printf("True"); putchar(tolower(x));
}
}
else {
return 0;
printf("False");
} }

return 0;
}

388
Question 71

Question:

Write a program to determine whether a given non-negative number is a multiple of 12 or

it is one more than a multiple of 12.

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() {

} printf("%f\n", (float)(int)10.5 / 4);


return 0; return 0;
}
}

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:

Write a program to calculate area of an ellipse.

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

first two values are equal.

Solution:

#include<stdio.h>
int myfunc();
int main() {
printf("\n%d", myfunc(11, 11, 11));
printf("\n%d", myfunc(11, 11, 16));
printf("\n%d", myfunc(18, 15, 10));
return 0;
}
int myfunc(int a, int b, int c) {
if (a == b && b == c) return 0;

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>

Write a program to convert bytes to kilobytes. int main() {

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;

printf("\nKilobytes: %.2lf", (bytes/1024)); }


return 0;
}

Output:

C language

394
Question 78

Question:

Write a program to convert megabytes to kilobytes.

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:

Write a program to count the number of even elements in an integer array.

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]);
}

for(i=0; i<arr_size; i++) {


if(array[i]%2==0) {
even++;
}
}
printf("Number of even elements: %d", even);
return 0;
}

Question 80

Question:

Write a program to count the number of odd elements in an integer array.

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);
printf("Enter the elements in array: \n");
for(i=0; i<arr_size; i++) {
scanf("%d",&array[i]);
}

for(i=0; i<arr_size; i++) {


if(array[i]%2!=0) {
odd++;
}
}
printf("Number of odd elements: %d", odd);
return 0;
}

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
printf("Input the values for x and y: \n");
scanf("%d %d", &x, &y);
if(x == y) {
printf("x and y are equal\n");
}
else {
printf("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<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:

Write a program to determine whether a particular year is a leap year or not.

Solution:

#include<stdio.h>
int main() {
int year;
printf("Enter the year: ");
scanf("%d", &year);
if((year % 400) == 0) {
printf("\n%d is a leap year.", year);
}
else if((year % 100) == 0) {
printf("\n%d is a not leap year.", year);
}
else if((year % 4) == 0) {
printf("\n%d is a leap year.", year);
}
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() {

char *x = "Albert Einstein\n";

while(putchar(*x++));
Output:
return 0;
Albert Einstein
}

400
Question 85

Question:

Write a program to Convert Yard to Foot.

Solution:

#include<stdio.h>
int main() {
float yard;
printf("\nEnter the Length in Yard : ");
scanf("%f", &yard);
printf("\n%f Yard in Foot is: %f", yard, (3*yard));
return 0;
}

Question 86

Question:

Write a program to convert gigabytes to megabytes.

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:

Write a program to Convert Kilogram to Pounds.

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:

Write a program to Convert Kilogram to Ounce.

Solution:

#include<stdio.h>
int main() {
float kg, ounce;
printf("\nEnter Weight in Kilogram: ");
scanf("%f", &kg);
ounce = kg*35.274;
printf("\n%f Kg = %f Ounce", kg, ounce);
return 0;
}

Question 89

Question:

Write a program to Convert Pounds to Grams.

Solution:

403
#include<stdio.h>
int main() {
float pound, gram;
printf("\nEnter Weight in Pounds: ");
scanf("%f", &pound);
gram = pound*453.592;
printf("\n%f Pound = %f Grams", pound, gram);
return 0;
}

Question 90

Question:

Write a program to verify whether a triangle is valid or not using angles.

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:

Write a program to verify if a character you entered is a vowel or a consonant.

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' ) {

printf("\n%c is a vowel", ch);


}
else {
printf("\n%c is a consonant", ch);
}
return 0;
}

406
Question 93

Question:
#include<stdio.h>

Write a program to find factorial of a number. #define x 2

int main() {

int i;

for(i=24; i<28; i++) {


Solution:
printf("%d %% %d = %d\n", i, x, i%x);
#include<stdio.h>
}
int main() {
return 0;
int i, fact=1, num;
printf("\nEnter a number: "); }
scanf("%d",&num); Output:
for(i=1; i<=num; i++) {
24 % 2 = 0
fact=fact*i;
25 % 2 = 1
}
printf("\nFactorial of %d is: %d", num, fact); 26 % 2 = 0
return 0;
27 % 2 = 1
}

Question 94

Question:

Write a program to print number of days in a month.

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",

Question: "James", Output:

"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:

Write a program to find maximum between two numbers.

#include<stdio.h>

int main() {
Solution:
for(int x=2; x<=25; x=x+2) {

#include<stdio.h> printf("%d\t", x);


int main() {
}
int a,b;
putchar('\n');
printf("Enter two numbers: \n");
return 0;
scanf("%d%d", &a, &b);
if(a>b) { }
printf("\n%d is a maximum number"
}
else {
printf("\n%d is a maximum number", b);
}

409
return 0;
}

Question 97 #include<stdio.h>

int main() {

Question: for(int x=3; x>=1; x--) {

for(int y=1; y<=x; y++) {


Write a program to compare two strings.
printf("%d ", y);

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", &dividend);
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;

for(i=-3; i<3; i++)


|printf("%d ", i);

Solution: for(; i>=-3; i--)


return
} 0;
printf("%d ", i);
#include<stdio.h>
int main() { putchar('\n');

int pwd, i;
while (i!=0) {
printf("\nEnter the password: ");
scanf("%d",&pwd);
if(pwd==1988) { Output:
printf("The password you entered is correct");
-3 -2 -1 0 1 2 3 2 1 0 -1 -2 -3
i=0;
}
else {
printf("Incorrect password, try again");
} #include<stdio.h>
printf("\n");
int main() {
}
int x, y;
return 0;
} printf("\nEnter the value for x: ");

scanf("%d", &x);

printf("\nEnter the value for y: ");

scanf("%d", &y);

(x>y)? printf("\nx is greater"): printf("\ny is greater");

return 0;

413
Question 102

Question:

Write a program to find absolute value of a number.

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>
}
else { int main() { Because the condition is

printf("Abnormal height.\n"); false, the value of "i" will


int i = 6;
be printed instead of the
} while(i==1) while loop being executed.
return 0;
}
printf("%d\n", i);

Question 104

Question:

Write a program to calculate the area of different geometric shapes using switch

statements.

Solution:

415
#include<stdio.h>
int main() {
int choice;
float r, l, w, b, h;
printf("\nEnter 1 for area of circle: ");
printf("\nEnter 2 for area of rectangle: ")
printf("\nEnter 3 for area of triangle: ");
printf("\nEnter your choice : ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter the radius of the circle: ");
scanf("%f", &r);
printf("\nArea of a circle is: %f", (3.14*r*r));
break;
case 2:
printf("Enter the length and width of the rectangle: \n");
scanf("%f%f", &l, &w);
printf("\nArea of a rectangle is: %f", (l*w));
break;
case 3:
printf("Enter the base and height of the triangle: \n");
scanf("%f%f", &b, &h);
printf("\nArea of a triangle is: %f", (0.5*b*h));
break;
default:
printf("\nPlease enter a number from 1 to 3.");
break;
}
return 0;
}

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>

ch = getchar (); int main() {


if(ch == 'y' || ch == 'Y') { int num[6] = {21, 22, 23, 24, 25, 26};
printf ("Yes\n");
for(int i = 0; i <= 7; i++) {
}
printf("\n%d", num[i]);
else { Output:
printf ("No\n"); }
21
} return 0;
return(0); 22
}
} 23

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--) {

#include<stdio.h> for(int y=1; y<=x; y++) {


int main() { printf("* ");
long x, y;
}
printf("Enter a integer: ");
printf("\n");
scanf("%ld", &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

printf("Enter a number: "); #define B 4


scanf("%d", &x);
int main() {
if((x != 0) && ((x &(x - 1)) == 0)) {
printf("A+B: %d\n", A+B);
printf("\n%d is a power of 2", x);
} printf("A-B: %d\n", A-B);
else { printf("AxB: %d\n", A*B);
printf("\n%d is not a power of 2", x);
printf("A/B: %d\n", A/B);
}
return 0; return 0;
Output:
} }
A+B: 20

A-B: 12

AXB: 64
Question 108
A/B: 4

Question:

Write a program to determine whether a triangle is scalene, isosceles, or equilateral.

Solution:

#include<stdio.h>
int main() {
int sidel, 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:

Write a program to find sum of even numbers between 1 to n.

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
Question 111

Question:

Write a program to find sum of odd numbers between 1 to n.

Solution:

#include<stdio.h>
int main() {
int i, num, sum=0;
printf("Enter a number: ");
scanf("%d", &num);
for(i=1; i<=num; i=i+2) {
sum = sum + i;
}
printf("\nSum of all odd number between 1 to %d is: %d", num, sum);
return 0;
}

Question 112

Question:

Write a program to find maximum number using switch case.

Solution:

422
#include<stdio.h>
int main() {
int x, y; #include<stdio.h>

printf("Enter any two numbers: \n"); int main() {


scanf("%d%d", &x, &y);
for(int i=5; i>=0; i=i-1) {
switch(x > y) {
printf("%d\n", i);
case 0: printf("%d is Maximum number", y);
break; }

case 1: printf("%d is Maximum number", x); return 0;


break; Output:
}
} 5
return 0;
4
}
3

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);
}
return 0;

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>

printf("%5d", x); int main() {


sum+=x;
int z[] = { 1, 40, 1, 80, 6 };
}
int y, *x;
}
printf("\nThe sum: %d", sum); x = z;

return 0; for(y = 0; y <= 4; y++) {


Output:
} printf("\n%d", *x);
1
x++;
40
}

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() {

printf("Enter a character: ");


Solution: int c = getchar();

#include<stdio.h> printf("You have entered the character '%c'.\n", c);

int myfunc(int x) { return 0;


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:

Write a program to find square root of an entered number.

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:

Write a program to find power of a entered number using library function.

Solution:

#include<stdio.h>

428
#include<math.h>
int main() {
int x, y;
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
printf("\n%dA%d = %ld", x, y, (long)pow(x,y));
return 0;
}

Question 120

Question:

Write a program to determine if the character entered is an alphabetic or numeric


character.

#include<stdio.h>

int main() {

Solution: printf("\"Hi,\" Albert, \"Elsa!\"\n");

return 0;
#include<stdio.h>
#include<ctype.h> }
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
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:

Write a program to determine whether the character entered is an alphanumeric character

or not.
#include<stdio.h>

int main() {

printf("The Sum is: %f\n",16.0+17);


Solution:
return 0;

#include<stdio.h> }
#include<ctype.h>
int main() {
char a;
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:

Write a program to determine whether the character entered is an punctuation character

or not.
#include<stdio.h>

#define SIZE 6

int main() {

Solution: char name[SIZE];

printf("Enter your name: ");


#include<stdio.h>
#include<ctype.h> fgets(name, SIZE, stdin);

int main() { printf("Pleased to meet you, %s.", name);


char a;
return 0;
printf("Enter a character: ");
}
scanf("%c", &a);
if(ispunct(a)) {
printf("\n%c is an punctuation character.", a);
}
else {
printf("\n%c is NOT an punctuation character.", a);
}
return 0;
}

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."
}
Output:
else {
printf("\n%c is NOT a graphic character." 0

} 0
return 0; #include<stdio.h>
}
int main() {

static int x[8];

for(int i = 0; i <= 7; i++) 0


F
printf("\n%d", x[i]);

return 0; _____________

432
Question 124

Question:

Write a program to list all printable characters using isprintO function.

#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 :

int main() { printf("\nAlan"); break;


int i; case 2.1 :
for(i = 1; i <= 127; i++)
printf("\nJohn"); break;
if(isprint(i)!= 0)
case 4.1 :
printf("%c ", i);
return 0; printf("\nMary"); break;

} case 6.1 :

printf("\nAlbert");

return 0;
Error
Question 125 } l

Question:

Write a program to check whether the entered character is a hexadecimal digit character

or not.

Solution:

433
#include<stdio.h>
#include<ctype.h>
int main() {
char a;
printf("Enter a character: ");
scanf("%c", &a);
if(isxdigit(a)) {
printf("\n%c is a hexadecimal digit character.", a);
}
else {
printf("\n%c is NOT a hexadecimal digit character.", a);
}
return 0;
}

Question 126

Question:

Write a program to print ASCII value of all control characters.

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:

Write a program to illustrate isprint() and iscntrl() functions.

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
}

Question 129 #include<stdio.h>

int main() {
Question:
char name[10];

Write a program to calculate surface area of cube. printf("Enter your name: ");

fgets(name,10,stdin);

printf("Pleased to meet you, %s.\n",name);

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:

Write a program to subtract 2 numbers without using subtraction operator.

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; }
printf("%d", x+(~y)+1) putchar('\n');
return 0;
return 0;
}
}

Output:

Question 131 12 13 14 15

Question:

Write a program to add 2 numbers without using addition operator.

#include<stdio.h>

int main() {
Solution: int i;

#include<stdio.h> for(i=0; i<5; i=i+1, printf("%d\n", i));

#include<stdlib.h> return(0);
int main() { Output:

int x =6, y=3; 1


printf("%d", x-(~y)-1);
2
return 0;
} 3

438
Question 132

Question:

Write a program to multiply a number by 2 without using multiplication operator.

#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;
}
}

Question 134

Question:

Write a program to divide a number by 2 without using division operator.

Solution:

#include<stdio.h>
int main() {
int x=12;
printf("%d", x>>1);

439
return 0;
}

Question 135

Question:

Write a program to calculate volume of sphere.

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() {

printf("Enter a character: ");

int c = getc(stdin);
Question 136
printf("You have entered the character '%c'.\n",c);

return 0;
Question:
}

Write a program to calculate volume of ellipsoid.

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>

long power = 1; int main() {


printf("\nEnter the value for x: ");
int x, y;
scanf("%d", &x);
x = 14;
printf("\nEnter the value for y: ");
scanf("%d", &y); y = x + 3;

for(int i=1; i<=y; i++) { if( x < y) {


power = power * x; printf("%d is greater than %d\n", x, y);
}
}
printf("%d A %d = %ld", x, y, power);
return(0);
return 0;
} }

Question 138

Question:

Write a program to read three numbers and find average of numbers.

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).

Solution:

#include<stdio.h>
#include<math.h>
int main() {
int n;
printf("\nEnter a number: ");
scanf("%d",&n);
printf("%f, %f, %f", pow(n, 1), pow(n, 2), pow(n, 3));
return 0;
}

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

does not exist then the new file will be created.

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>

using namespace std;

int main() {

int a = 15, b = 25;

printf("Value of a: %d", a);

printf("\n Value of b: %d", b);

swap(a, b);

printf("\n After swapping, the values are: a = %d, b = %d", a, b);

return 0;

Output:

Value of a: 15

Value of b: 25

After swapping, the values are: a = 25, b = 15

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

abilities, and learn more about the language.

446
Question 1

Question:

Write a program to print Hello, World!.

Solution: #include<iostream>

using namespace std;


#include<iostream>
int main() { int main() {

std::cout<<"Hello, World!"; cout << "Elsa Einstein \n";


return 0;
cout << "Albert Einstein" << endl;
}
return 0;
Output:
} Elsa Einstein

Albert Einstein

Question 2

Question:

Write a program to compute the perimeter and area of a rectangle.

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:

Write a program to compute the perimeter and area of a circle.

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>

using namespace std;

int main() {
Solution:
int x= 26; // Now x is 15

x = 56; // Now x is 10
#include<iostream>
using namespace std; cout << x;

int main() { // Output: 56


float a, b, sum;
return 0;
cout<<"\nEnter the first number: ";
cin>>a; }

cout<<"\nEnter the second number: ";


cin>>b;
sum = a+ b;
cout<<"\nSum of the above two numbers is: "<< sum;
return 0;
}

449
Question 5

Question:

Write a program that accepts two numbers from the user and calculate the product of the
two numbers.

Solution:

#include<iostream>
using namespace std;
int main() {
int a, b, mult;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
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
Solution:

#include<iostream>
using namespace std;
int main() {
int x, y, z;
cout<<"\nEnter the first number: ";
cin>>x;
cout<<"\nEnter the second number: ";
cin>>y;
cout<<"\nEnter the third number: ";
cin>>z;

// if x is greater than both y and z, x is the largest


if (x >= y && x >= z)
cout<<x<<" is the largest number.";

// if y is greater than both x and z, y is the largest


if (y >= x && y >= z)
cout<<y<<" is the largest number.";

// if z is greater than both x and y, z is the largest


if (z >= x && z >= y)
cout<<z<<" is the largest number.";

return 0;
}

451
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:

#include<iostream>
using namespace std;
int main() {
float x, y, z;
cout<<"\nEnter the first number: ";
cin>>x;
cout<<"\nEnter the second number: ";
cin>>y;
cout<<"\nEnter the third number: ";
cin>>z;

if(x < (y+z) && y < (x+z) && z < (y+x)) {


cout<<"\nPerimeter of the triangle is: " << x+y+z;
}
else {
cout<<"\nIt is impossible to form a triangle.";
}

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;
switch(day) {
case 1 : cout<<"Monday\n"; break;
case 2 : cout<<"Tuesday\n"; break;
case 3 : cout<<"Wednesday\n"; break;
case 4 : cout<<"Thursday\n"; break;
case 5 : cout<<"Friday\n"; break;
case 6 : cout<<"Saturday\n"; break;
case 7 : cout<<"Sunday\n"; break;
default : cout<<"Enter a number between 1 to 7.";
}
return 0;
}

453
Question 9

Question:

Write a program to find the sum of two numbers.

Solution: #include<iostream>

#include<iostream> using namespace std;

using namespace std; int main() {


int main() {
bool x = true;
int a, b, sum;
bool y = false;
a=1;
b=2; cout << x <<endl;
sum = a + b; // Output: 1
cout<<"The sum of a and b is: " << sum;
cout << y<<endl;
return 0;
// Output: 0
}
return 0;

Question 10

Question:

Write a program to find the square of a number.

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:

Write a program to find the greatest of two numbers.

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:

Write a program to print the average of the elements in the array.

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
#include <iostream>
using namespace std;
int main() {
cout<<"Odd numbers between 1 to 50:\n";
for(int i = 1; i <= 50; i++) {
if(i%2 != 0) {
cout<<i<<endl;
}
}
return 0;
}

Question 15

Question:

Write a program to print the first 10 numbers starting from one together with their

squares and cubes.

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>

using namespace std;


Question:
int main() {
Write a program:
cout << min(15, 60)<<endl;
If you enter a character M
// Output: 15
Output must be: ch = M.
cout << max(15, 60)<<endl;

// 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
Solution:

#include<iostream>
using namespace std;
int main() {
int n, i;
cout<<"Enter any number: ";
cin>>n;
for( i=1; i<=5; i++)
cout<< n <<" * "<< i <<" = "<< n*i <<endl;
return 0;
}

Question 18

Question:

Write a program to print the product of the first 10 digits.

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:

Write a program to print whether the given number is positive or negative.

Solution:

#include<iostream>
using namespace std;
#include<iostream>
int main() {
int a; #include<cmath>

a = -35; using namespace std;


if(a>0) {
int main() {
cout<<"Number is positive";
cout << sqrt(36) << endl;
}
else { // Output: 6
cout<<"Number is negative"; cout << round(6.68) << endl;
}
// Output: 7
return 0;
} cout << log(4) << endl;

// 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:

Write a program to print the characters from A to Z.

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: }

Write a program to print the length of the entered string.

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

Question:

Write a program to print the output:


Einstein [0] = E

Einstein [1] = I
Einstein [2] = N
Einstein [3] = S

Einstein [4] = T
Einstein [5] = E

Einstein [6] = I
Einstein [7] = N

Solution:

#include<iostream>
using namespace std;
int main() {
int i;
char name [8] = {'E' , 'I', 'N', 'S', 'T', 'E', 'I', 'N'};
for(i=0; i<8; i++)
cout<<"Einstein ["<< i <<" ] = "<< name[i] << endl;
return 0;
}

468
Question 29

Question:

Write a program to print "Hello World" 10 times.

Solution:

#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=10; i++) {
cout<< "Hello World"<< endl;
}
return 0;
}

Question 30

Question:

Write a program to print first 5 numbers using do while loop statement.

Solution:

#include<iostream>
using namespace std;

469
int main() {
int i =1;
do {
cout<<" \ni = "<< i++;
} while(i<=5);
return 0;
}

Question 31

Question:

Write a program to check whether a character is an alphabet or not.

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:

Write a program to check whether a entered number is even or odd.

Solution:

#include<iostream>
using namespace std;
int main() {
int a;
cout<<"Enter any number: ";
cin>>a;
if(a%2 == 0) {
cout<<"The entered number is even";
}
else {
cout<<"The entered number is odd";
}
return 0;
}

471
Question 33

Question:

Write a program to print the ASCII value of the entered character.

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>
using namespace std;
int main() {
int x, i;
cout<<"Enter a number: ";
cin>>x;
for(i=1; i<=50; i++) {
if((i%x)==2) {
cout<<i<<endl;
}
}
return 0;
}

Question 35

Question:

Write a program to determine whether two numbers in a pair are in ascending or

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

not possible" if that is not possible.

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:

#include<iostream>
using namespace std;
int main() {
int x =12, i, sum = 0;
for(i=1; i<=100; i++) {
if((i%x)!= 0) {
sum += i;
}
}
cout<<"\nSum: "<<sum;
return 0;
}

476
Question 39

Question:

Write a program to calculate the value of x where x = 1 + 1/2 + 1/3 + ... + 1/50.

Solution:

#include<iostream>
using namespace std;
int main() {
float x = 0;
for(int i=1; i<=50; i++) {
x += (float)1/i;
}
cout<<"Value of x: "<< x;
return 0;
}

Question 40

Question:

Write a program that reads a number and find all its divisor.

Solution:

477
#include<iostream>
using namespace std;
int main() {
int x, i;
cout<<"\nEnter a number: ";
cin>>x;
cout<<"All the divisor of "<<x<<" are: \n";
for(i = 1; i <= x; i++) {
if((x%i) == 0) {
cout<<i<<endl;
}
}
return 0;
}

Question 41

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:

Write a program to find square of a entered number using functions.

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;
cout<<"\nEnter the value for b: ";
cin>>b;
cout<<"\nBefore swapping: " <<a <<" "<<b;
a=a+b;
b=a-b;
a=a-b;
cout<<"\nAfter swapping: " <<a<<" "<<b;
return 0;
}

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;
p = &x;
q = &y;
if(*p>*q) {
cout<<"x is greater than y";
}
else {
cout<<"y is greater than x";
}
return 0;
}

482
Question 46

Question:

***Write a program to print the output:


body [b] = b

body [o] = o

body [d] = d
body [y] = y
***

Solution:

#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;
}

483
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


If purchase value is greater than 5000, 20% discount
If purchase value is greater than 10000, 30% discount.

Solution:

#include<iostream>
using namespace std;
int main() {
double PV;
cout<<"Enter purchased value: ";
cin>>PV;
if(PV>1000) {
cout<<"Discount = "<< PV * 0.1 << endl;
cout<<"Total= "<< PV - PV * 0.1 << endl;
}
else if(PV>5000) {
cout<<"Discount = "<< PV * 0.2 << endl;
cout<<"Total= "<< PV - PV * 0.2 << endl;
}
else {
cout<<"Discount = "<< PV * 0.3 << endl;
cout<<"Total= "<< PV - PV * 0.3 << endl;
}

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:

Write a program to shift inputted data by two bits to the left.

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:

Write a program to shift inputted data by two bits to the Right.

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>

using namespace std;


Solution:

#include<iostream> void myfunc() {


using namespace std;
cout << "Einstein"<<endl;
int main() {
int x; }
cout<<"Enter the value for x: ";
# Output:
cin>>x;
int main() {
if(x<=21){ Einstein
myfunc();
cout<<abs(x-21); Einstein
} myfunc();
Einstein
else if(x>=21) {
myfunc();
cout<<abs(x-21)*3;
return 0;
}
return 0; } i

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.

Solution:

#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the first number: ";
cin>>x;
cout<<"\nEnter the second number: ";
cin>>y;
if(x % y == 0) {
cout<<x<<" is a multiple of " <<y;
}
else {
cout<<x<<" is not a multiple of " <<y;
}
return 0;
}

488
Question 53

Question:

Write a program to print the output:


Name of the book = B

Price of the book = 135.00


#include<iostream>
Number of pages = 300
using namespace std;
Edition of the book = 8

using structures.
int myfunc(int x) {

return 15 + x;

}
Solution:

#include<iostream>
int main() {
using namespace std;
int main() { cout << myfunc(13);

struct book { return 0;


char name;
}
float price;
int pages;
int edition;
};
struct book b1= {'B', 135.00, 300, 8};
cout<<"Name of the book = "<< b1.name<< endl;
cout<<"Price of the book = "<< b1.price<<endl;
cout<<"Number of pages = "<< b1.pages<<endl;
cout<<"Edition of the book = "<< b1.edition<< endl;
return 0;
}

489
Question 54

Question:

Write a program to convert Celsius into Fahrenheit.

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:

Write a program to check whether the person is a senior citizen or not.

Solution:

#include<iostream>
using namespace std;
int main() {
int age;
cout<<"Enter age: ";
cin>>age;
if(age>=60) {
cout<<"Senior citizen";
}
else {
cout<<"Not a senior citizen";
}
return 0;
}

Question 58

Question:

Write a program that reads a student's three subject scores (0-100) and computes the

average of those scores.

493
Solution:

#include<iostream>
using namespace std;
int main() {
float score, total_score = 0;
int subject = 0;
cout<<"Enter three subject scores (0-100):\n";
while (subject != 3) {
cin>>score;
if(score < 0 || score > 100) {
cout<<"Please enter a valid score.\n";
}
else {
total_score += score;
subject++;
}
}
cout<<"Average score = "<< (total_score/3);
return 0;
}

Question 59

Question:

What results would the following programs produce?

494
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=5; i++) {
if(i==3) {
break;
}
cout<<"\n"<< i;
}
return 0;
}

Solution:

1
2

#include<iostream>
using namespace std;
int main() {
for(int i=1;i<=5;i++) {
if(i==3) {
goto HAI;
}
cout<<"\n "<<i;
}
HAI : cout<<"\n Linux";
}

495
Solution:

1
2
Linux

#include<iostream>
using namespace std;
int main() {
for( ; ; ) {
cout<<"This loop will run forever.\n";
}
return 0;
}

Solution:

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.

#include<iostream>

496
using namespace std;
int main() {
cout<<"Hello,world!";
return 0;
cout<<"Hello,world!";
}

Solution:

Hello,world

#include<iostream>
using namespace std;
int main () {
cout<<"linux\n";
exit (0);
cout<<"php\n";
return 0;
}

Solution:

linux

#include<iostream>

497
using namespace std;
int main() {
for(int i=1; i<=5; i++) {
if(i==3) {
continue;
}
cout<<"\n "<<i;
}
return 0;
}

Solution:

1
2
4
5

#include<iostream>
using namespace std;
int main() {
int a = 10, b = 20, c;
c = (a < b) ? a : b;
cout<<c;
return 0;
}

498
Solution:

10

#include<iostream>
using namespace std;
#define A 15
int main() {
int x;
x=A;
cout<<x;
return 0;
}

Solution:

15

#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x = 20;
cout<<"lnverse of tan x = "<< atan(x);

499
return 0;
}

Solution:

Inverse of tan x = 1.52084

#include<iostream>
#include<cmath>
using namespace std;
int main() {
double a, b;
a = -2.5;
b = fabs(a);
cout<<"|"<<a<<"|" << " = "<<b;
return 0;
}

Solution:

|-2.5| = 2.5

500
#include<iostream>
using namespace std;
int main() {
int x=12, y =3;
cout<<abs(-x-y);
return 0;
}

Solution:

15

#include<iostream>
using namespace std;
int main() {
int x=12, y =3;
cout<<-(-x-y);
return 0;
}

Solution:

15

501
#include <iostream>
using namespace std;
int main() {
int x=12, y =3;
cout<< x-(-y);
return 0;
}

Solution:

15

Question 60

Question:

Write a program to find the size of an array.

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;
}

507
Question 66

Question:

Write a program to determine whether a positive number entered by the user is a multiple
of three or five.

Solution:

#include<iostream>
using namespace std;
int main() {
int x;
cout<<"\nEnter a number: ";
cin>>x;
if(x % 3 == 0 || x % 5 == 0) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}

508
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:

#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";
}
else {
cout<<"False";
}
return 0;
}

509
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<iostream>
using namespace std;
int myfunc();
int myfunc(int a, int b) {
int x = abs(a - 100);
int y = abs(b - 100);
return x == y ? 0 : (x < y ? a : b);
}
int main() {
cout<<" "<< myfunc(86, 99);
cout<<"\n "<<myfunc(55, 55);
cout<<"\n "<<myfunc(65, 80);
return 0;
}

510
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:

#include<iostream>
using namespace std;
int main() {
int x;
cout<<"\nEnter a number: ";
cin>>x;
if(x % 3 == 0 A x % 5 == 0) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}

511
Question 70

Question:

Write a program to determine whether two entered non-negative numbers have the same
last digit.

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(abs(x % 10) == abs(y % 10)) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}

512
Question 71

Question:

Write a program to determine whether a given non-negative number is a multiple of 12 or


it is one more than a multiple of 12.

Solution:

#include<iostream>
using namespace std;
int main() {
int x = 43;
if(x % 12 == 0 || x % 12 == 1) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}

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.

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

integer from three entered integers.

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:

Write a program to calculate area of an ellipse.

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, 11); }


cout<<"\n"<<myfunc(11, 11, 16);
cout<<"\n"<<myfunc(18, 15, 10);
int main() {
return 0;
} myfunc();

return 0;

517
Question 77

Question:

Write a program to convert bytes to kilobytes.

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:

Write a program to convert megabytes to kilobytes.

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:

Write a program to count the number of even elements in an integer array.

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
}

for(i=0; i<arr_size; i++) {


if(array[i]%2==0) {
even++;
}
}
cout<<"Number of even elements: "<< even;
return 0;
}

Question 80

Question:

Write a program to count the number of odd elements in an integer array.

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
}

for(i=0; i<arr_size; i++) {


if(array[i]%2!=0) {
odd++;
}
}
cout<<"Number of odd elements: "<< odd;
return 0;
}

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<<"lnput 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:

Write a program to determine whether a particular year is a leap year or not.

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:

Write a program to Convert Yard to Foot.

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:

Write a program to convert gigabytes to megabytes.

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:

Write a program to Convert Kilogram to Pounds.

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:

Write a program to Convert Kilogram to Ounce.

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:

Write a program to Convert Pounds to Grams.

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:

Write a program to verify whether a triangle is valid or not using angles.

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 = anglel + 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 I 10;
}
cout<<"\nSum of digits of "<<x<<" is: "<<sum;
return 0;
}

Question 92

Question:

Write a program to verify if a character you entered is a vowel or a consonant.

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:

Write a program to find factorial of a number.

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:

Write a program to print number of days in a month.

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:

Write a program to concatenate two strings.

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:

Write a program to find maximum between two numbers.

533
Solution:

#include<iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter two numbers: \n";
cin>>a;
cin>>b;
if(a>b) {
cout<<a<<" is a maximum number";
}
else {
cout<<b<<" is a maximum number";
}
return 0;
}

Question 97

Question:

Write a program to compare two strings.

Solution:

#include<iostream>

534
#include<cstring>
using namespace std;
int main() {
char a[100], b[100];
cout<<"Enter the first string: \n";
cin>>a;
cout<<"Enter the second string: \n";
cin>>b;
if (strcmp(a,b) == 0) {
cout<<"The 2 strings are equal.\n";
}
else {
cout<<"The 2 strings are not equal.\n";
}
return 0;
}

Question 98

Question:

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 a entered dividend and divisor.

Solution:

#include<iostream>
using namespace std;
int main() {
int dividend, divisor;
cout<<"\nEnter dividend: ";
cin>>dividend;
cout<<"\nEnter divisor: ";
cin>>divisor;
cout<<"\nQuotient = "<< (dividend / divisor);
cout<<"\nRemainder = "<< (dividend % divisor);
return 0;
}

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:

Write a program to verify the password until it is correct.

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:

Write a program to find absolute value of a number.

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;
}
return 0;
}

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".

Solution:

#include<iostream>
using namespace std;
int main() {
char ch;
cout<<"Enter a character: ";
ch = getchar ();
if(ch == 'y' || ch == 'Y') {
cout<<"Yes\n";
}
else {
cout<<"No\n";
}
return(0);
}

Question 106

Question:

Write a program that uses bitwise operators to multiply an entered value by four.

542
Solution:

#include<iostream>
using namespace std;
int main() {
long x, y;
cout<<"Enter a integer: ";
cin>>x;
y = x;
x = x << 2;
cout<< y<<" x 4 = "<< 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:

#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter a number: ";

543
cin>>x;
if((x != 0) && ((x &(x - 1)) == 0)) {
cout<<x<<" is a power of 2";
}
else {
cout<<x<<" is not a power of 2";
}
return 0;
}

Question 108

Question:

Write a program to determine whether a triangle is scalene, isosceles, or equilateral.

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 == sidel) {
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:

Write a program to find sum of even numbers between 1 to n.

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:

Write a program to find sum of odd numbers between 1 to n.

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:

Write a program to find maximum number using switch case.

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

and calculate profit or loss.

Solution:

#include<iostream>

548
using namespace std;
int main() {
int cp, sp;
cout<<"\nlnput Cost Price: ";
cin>>cp;
cout<<"\nlnput Selling Price: ";
cin>>sp;
if(sp > cp) {
cout<<"Profit = "<< (sp - cp);
}
else if(cp > sp) {
cout<<"Loss = "<< (cp - sp);
}
else {
cout<<"No Profit No Loss.";
}
return 0;
}

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;
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++)
cout<<"*";
cout<<"\n";
}
return 0;
}

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:

Write a program to find square root of a entered number.

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:

Write a program to find power of a entered number using library function.

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<<"A"<<y<<" = " << (long)pow(x,y);
return 0;
}

Question 120

Question:

Write a program to determine if the character entered is an alphabetic or numeric

character.

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:

Write a program to determine whether the character entered is an alphanumeric character

or not.

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:

Write a program to determine whether the character entered is an punctuation character

or not.

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:

Write a program to list all printable characters using isprintO function.

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:

Write a program to print ASCII value of all control characters.

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"; ?
string* ptr = &x;

cout << ptr << endl;

cout << *ptr << endl;


Question 127
return 0;

}
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:

Write a program to illustrate isprint() and iscntrl() functions.

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:

Write a program to calculate surface area of cube.

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:

Write a program to subtract 2 numbers without using subtraction operator.

562
Solution:

#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x+(~y)+1;
return 0;
}

Question 131

Question:

Write a program to add 2 numbers without using addition operator.

Solution:

#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x-(~y)-1;
return 0;
}

563
Question 132

Question:

Write a program to multiply a number by 2 without using multiplication operator.

#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:

Write a program to divide a number by 2 without using division operator.

Solution:

#include<iostream>
using namespace std;
int main() {

564
int x=12;
cout<< (x>>1);
return 0;
}

Question 135

Question:

Write a program to calculate volume of sphere.

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:

Write a program to calculate volume of ellipsoid.

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>

using namespace std;

int main() {

string x[5] = {"Albert", "John", "Mary", "James", "Bob"};

for(int i = 0; i < 5; i++) { cout << x[i] << endl; }

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() {

power = power * x; string x = "Albert";


} string &y = x;
cout<<x<<"A"<<y<<" = "<<power;
cout << x << endl;
return 0;
} // Output: Albert

cout << y << endl;

// Output: Albert

return 0;

567
Question 138

Question:

Write a program to read three numbers and find average of numbers.

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 (n1, 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>

using namespace std; #include<iostream>

#include<cstring>
int main() {
using namespace std;
string i[2][4] = {

{ "A", "L", "B", "E" },


int main() {
{ "R", "T", "J", "H" } string x = "Albert";

}; cout << &x;

return 0;
cout << i[0][2];
}
// Output: B

return 0;

569
#include<iostream>

using namespace std;

int main() {

string x="C++ ";

string y="programming";

x.append(y);

cout<<" \n "<<x<<'\n';

return 0;

// Output: C++ programming

#include<iostream>

using namespace std; #include<iostream>

int main() { using namespace std;

string x="Albert"; int main() {

cout<<*x.begin(); string x = "C language

return 0; *x.begin()=' J';

// Output: A cout<<x;

} return 0;

// Output: J language

570
#include<iostream>

using namespace std;

int main() {

string x="This is a C++ Program.";

x.erase(8,1);

cout<<x;

// Output: This is C++ Program.

return 0;

#include<iostream>

#include<cstring>

using namespace std;

int main() {

string txt = "C++ Programming.";

cout << "The length of the text string is: " << txt.size();

// Output: The length of the text string is: 16

return 0;

571
#include<iostream>

#include<cstring>

using namespace std;

int main() {

string txt = "C++ Programming.";

cout << "The length of the text string is: " << txt.length();

// Output: The length of the text string is: 16

return 0;

#include<iostream>

using namespace std;

int main() {

string x="c++ programming";

x.erase(x.begin()+0);

cout<<x;

// Output: ++ programming

return 0;

C++ is an extension of C programming and the programs

written in C language can run in C++ compilers.

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

Java Development Kit Java Runtime Environment Java Virtual Machine

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

programs. program needs to run.

Inheritance Abstraction

A mechanism in which one class The methodology of hiding the

acquires the properties of another implementation details from the user and
only providing the functionality to the
users.

Encapsulation
Polymorphism

A process of wrapping code and data

together into a single unit The ability of any data to be

processed in more than one form

Collection is a framework that is designed to store the objects and manipulate

the design to store the objects.

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:

Write a program to print Hello, World!.

Solution:

public class MyClass {


public static void main(String[] args) {
System.out.print("Hello, World!");
}
}

Question 2

Question:

Write a program to compute the perimeter and area of a rectangle.

Solution:

public class MyClass {


public static void main(String[] args) {
int height = 8;
int width = 5;

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:

Write a program to compute the perimeter and area of a circle.

Solution:

public class MyClass {


public static void main(String[] args) {
int radius = 4;
float perimeter = (float)(2 * 3.14 * radius);
System.out.printf("Perimeter of the circle is: %f cm\n", perimeter);
float area = (float)(3.14 * radius * radius);
System.out.printf("Area of the circle is: %f square cm\n", area);
}
public class MyClass {
}
public static void main(String[] args) {

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;

public class MyClass {


public static void main(String[] args) {
int a, b, sum;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
sum = a + b;
System.out.print("\nSum of the above two numbers is: " + sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

public class MyClass {

public static void main(String[] args) {

String x = "Einstein";

System.out.println("Albert " + x);

}
// 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;

public class MyClass {


public static void main(String[] args) {
int a, b, mult;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
mult = a * b;
System.out.print("\nProduct of the above two numbers is: " + mult);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 6

Question:

Write a program that accepts three numbers and find the largest of three.

579
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x, y, z;
System.out.print("\nEnter the first number: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
y = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third number: ");
z = STDIN_SCANNER.nextInt();

// if x is greater than both y and z, x is the largest


if(x >= y && x >= z) {
System.out.print("\n" + x + " is the largest number.");
}

// if y is greater than both x and z, y is the largest


if(y >= x && y >= z) {
System.out.print("\n" + y + " is the largest number.");
}

// if z is greater than both x and y, z is the largest


if(z >= x && z >= y) {
System.out.print("\n" + z + " is the largest number.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
float x, y, z;
System.out.print("\nEnter the first number: ");
x = STDIN_SCANNER.nextFloat();
System.out.print("\nEnter the second number: ");
y = STDIN_SCANNER.nextFloat();
System.out.print("\nEnter the third number: ");
z = STDIN_SCANNER.nextFloat();

if(x < y + z && y < x + z && z < y + x) {


System.out.printf("\nPerimeter of the triangle is: %f\n", x + y + z);
} else {
System.out.print("\nIt is impossible to form a triangle.");

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;

public class MyClass {


public static void main(String[] args) {
int day;
System.out.print("\nEnter a number between 1 to 7 to get the day name: ");
day = STDIN_SCANNER.nextInt();
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");

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:

Write a program to find the sum of two numbers.

583
Solution:

public class MyClass {


public static void main(String[] args) {
int a, b, sum;
a = 1;
b = 2;
sum = a + b;
System.out.print("The sum of a and b = " + sum);
}
}

Question 10

Question:

Write a program to find the square of a number.

Solution:

public class MyClass {


public static void main(String[] args) {
int a, b;
a = 2;
b = (int)Math.pow(a, 2);
System.out.print("The square of a = " + b);
}
}

584
Question 11

Question:

Write a program to find the greatest of two numbers.

Solution:

public class MyClass {


public static void main(String[] args) {
int a, b;
a = 2;
b = 3;
if(a > b) {
System.out.print("a is greater than b");
} else {
System.out.print("b is greater than a");
}
}
}

Question 12

Question:

Write a program to print the average of the elements in the array.

585
Solution:

public class MyClass {


public static void main(String[] args) {
int avg = 0, sum = 0;
int[] num = {16, 18, 20, 25, 36};
for(int i = 0; i < 5; i++) {
sum = sum + num[i];
avg = sum / 5;
}
System.out.println("Sum of the Elements in the array is: " + sum);
System.out.println("Average of the elements in the array is: " + avg);
}
}

Question 13

Question:

Write a program that prints all even numbers between 1 and 25.

Solution:

public class MyClass {


public static void main(String[] args) {
System.out.println("Even numbers between 1 to 25:");
for(int i = 1; i <= 25; i++) {

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:

public class MyClass {


public static void main(String[] args) {
System.out.println("Odd numbers between 1 to 50:");
for(int i = 1; i <= 50; i++) {
if(i % 2 != 0) {
System.out.print(i + " ");
}
} public class MyClass {

} public static void main(String[] args) {


}
byte x = 100;

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:

public class MyClass {


public static void main(String[] args) {
for(int i = 1; i <= 10; i++) {
System.out.println("Number = " + i + " its square = " + (i * i) + " its cube
= " + (i * i * i));
}
}
}

Question 16

Question:

Write a program:
If you enter a character M

Output must be: ch = M.

588
Solution:

public class MyClass {


public static void main(String[] args) throws Exception {
char c;
System.out.print("Enter a character: ");
c = (char)System.in.read();
System.out.println("ch = " + c);
}
}

Question 17

Question:

Write a program to print the multiplication table of a number entered by the user.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int n;
System.out.print("Enter any number: ");
n = STDIN_SCANNER.nextInt();
for(int i = 1; i <= 5; i++) {
System.out.println(n + " * " + i + " = " + (n * i));
}

589
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 18

Question:

Write a program to print the product of the first 10 digits.

Solution:

public class MyClass {


public static void main(String[] args) {
int product = 1;
for(int i = 1; i <= 10; i++) {
product = product * i;
}
System.out.print("The product of the first 10 digits is: " + product);
}
}

Question 19

Question:

Write a program to print whether the given number is positive or negative.

590
Solution:

public class MyClass {


public static void main(String[] args) {
int a;
a = -35;
if(a > 0) {
System.out.print("Number is positive");
} else {
System.out.print("Number is negative");
}
}
}

Question 20

Question:

Write a program to check the equivalence of two numbers entered by the user.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x, y;

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;

public class MyClass {


public static void main(String[] args) {
int a, b, c;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");

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:

Write a program to print the characters from A to Z.

Solution:

public class MyClass {


public static void main(String[] args) {
for(byte i = 'A'; i <= 'Z'; i++) {
System.out.println((char)Byte.toUnsignedInt(i));
}
} public class MyClass {

} public static void main(String[] args) {

boolean x = true;

boolean y = false;

System.out.println(x); // Output: true

System.out.println(y); // Output: false

593
Question 23

Question:

Write a program to print the length of the entered string.

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:

public class MyClass {


public static void main(String[] args) {
char ch = 'A';
if(Character.isUpperCase(ch)) {
System.out.println("The given character is a upper case letter");
}
else {
System.out.println("The given character is a lower case letter");
}

595
}
}

Question 26

Question:

Write a program to convert the lower case string to upper case string.

Solution:

public class MyClass {


public static void main(String[] args) {
String a = "albert einstein";
System.out.println(a.toUpperCase());
}
}

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;

public class MyClass {


public final static double X = 2.54;
public static void main(String[] args) {
double inch, cm;
System.out.print("Enter the distance in cm: ");
cm = STDIN_SCANNER.nextDouble();
inch = cm / X;
System.out.printf("\nDistance of %.2f cms is equal to %.2f inches", cm,
inch);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 28

Question:

Write a program to print the output:

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 {


public static void main(String[] args) throws Exception{
int i;
char [] num = {'E' , 'I', 'N', 'S', 'T', 'E', 'I', 'N'};
for(i=0; i<8; i++)
System.out.println("Einstein [" + i + " ] = " + num[i]);
}
}

Question 29 public class MyClass {

static void myMethod(String x) {


Question:
System.out.println(x + " Einstein");

Write a program to print "Hello World" 10 times. }

public static void main(String[] args) {


Solution:
myMethod("David");

public class MyClass { myMethod("Albert");


public static void main(String[] args) {
,...ho.("Els,);
for(int i = 1; i <= 10; i++) {
System.out.println("Hello World "); } H

}
}
}

598
Question 30

Question:

Write a program to print first 5 numbers using do while loop statement.

Solution:

public class MyClass {


public static void main(String[] args) {
int i = 1;
do {
System.out.println(i++);
} while(i <= 5);
}
}

Question 31

Question:

Write a program to check whether a character is an alphabet or not.

Solution:

599
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any caracter: ");
char c = scanner.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
System.out.println(c + " is a Alphabet.");
} else {
System.out.println(c + " is not aAlphabet.");
}
}
}

Question 32

Question:

Write a program to check whether a entered number is even or odd.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int a;
System.out.print("Enter any number: ");

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:

Write a program to print the ASCII value of the given character.

Solution:

public class MyClass {


public static void main(String[] args) {
byte ch = 'A';
System.out.print("The ASCII value of " + ((char)Byte.toUnsignedInt(ch)) + "
is: " + ch);
}
}

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;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter a number: ");
x = STDIN_SCANNER.nextInt();
for(int i = 1; i <= 50; i++) {
if(i % x == 2) {
System.out.println(i);
}
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Pointers are not used in Java because doing so would

weaken the language's security and robustness and

make it more complicated.

602
Question 35

Question:

Write a program to determine whether two numbers in a pair are in ascending or


descending order.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int a, b;
System.out.print("\nEnter a pair of numbers (for example 22,12 | 12,22): ");
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
if(a > b) {
System.out.print("\nThe two numbers in a pair are in descending order.");
} else {
System.out.print("\nThe two numbers in a pair are in ascending order.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int a, b;
float c;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
if(b != 0) {
c = (float)a / (float)b;
System.out.printf("\n%d/%d = %.1f", a, b, c);
} else {
System.out.println("\nDivision not possible.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter a number: ");
x = STDIN_SCANNER.nextInt();
for(int i = 1; i <= 50; i++) {
if(i % x == 2 || i % x == 3) {
System.out.println(i);
}
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
public class MyClass {

public static void main(String[] args) {

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:

public class MyClass {


public static void main(String[] args) {
int x = 12, sum = 0;
for(int i = 1; i <= 100; i++) {
if(i % x != 0) {
sum += i;
}
}
System.out.println("\nSum: " + sum);
}
}

Question 39

Question:

Write a program to calculate the value of x where x = 1 + 1/2 + 1/3 + ... + 1/50.

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;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("\nEnter a number: ");
x = STDIN_SCANNER.nextInt();
System.out.print("All the divisor of " + x + " are: ");
for(int i = 1; i <= x; i++) {
if(x % i == 0) {
System.out.print("\n" + i);

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:

public class MyClass {


public static void main(String[] args) {
int a, b, c, d, e, f;
a = 10;
b = 12;
c = a + 1;
d = b + 1;
e = a - 1;
f = b - 1;
System.out.print("\nThe incremented value of a =" + c);
System.out.print("\nThe incremented value of b =" + d);
System.out.print("\nThe decremented value of a =" + e);
System.out.print("\nThe decremented value of b =" + f);
}
}

608
Question 42

Question:

Write a program to find square of a entered number using functions.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int answer;
answer = square();
System.out.print("The square of the entered number is: " + answer);
}

public static int square() {


int x;
System.out.print("Enter any number: ");
x = STDIN_SCANNER.nextInt();
return x * x;
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int p, r, t, SI;
System.out.print("\nEnter the principal amount: ");
p = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the rate of interest: ");
r = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the time: ");
t = STDIN_SCANNER.nextInt();
SI = (p * r * t) / 100;
System.out.print("\nSimple interest is: " + SI);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

610
Question 44

Question:

Write a program that swaps two numbers without using third variable.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int a, b;
System.out.print("\nEnter the value for a: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for b: ");
b = STDIN_SCANNER.nextInt();
System.out.print("\nBefore swapping: " + a + " " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.print("\nAfter swapping: " + a + " " + b);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

611
Question 45

Question:

Write a program to compute the area of a hexagon.

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:

Write a program to print the output:


body [b] = b

body [o] = o

612
body [d] = d

body [y] = y

Solution:

public class MyClass {


public static void main(String[] args) throws Exception{
int i;
char [] body = {'b', 'o', 'd', 'y'};
for(i=0; i<4; i++) {
System.out.println("body [" + body [i] + " ] = " + body [i]);
}
}
}

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
If purchase value is greater than 5000, 20% discount
If purchase value is greater than 10000, 30% 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:

public class MyClass {

614
public static void main(String[] args) { import java.util.ArrayList;

int i = 1; public class MyClass {


while(i <= 10) {
public static void main(String[] args) {
System.out.println(i++);
ArrayList<String> x = new ArrayList<String>();
}
x.add("Albert");
}
x.add("Joe");
}
x.add("Alan");

x.add("Mary");

System.out.println(x);
} u
Question 49

Question:

Write a program to shift inputted data by two bits to the left.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter the integer from keyboard: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEntered value: " + x + " ");
System.out.print("\nThe left shifted data is: " + (x <<= 2) + " ");
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

615
Question 50

Question:

Write a program to shift inputted data by two bits to the Right.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter the integer from keyboard: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEntered value: " + x + " ");
System.out.print("\nThe right shifted data is: " + (x >>= 2) + " ");
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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.

616
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter the value for x: ");
x = STDIN_SCANNER.nextInt();
if(x <= 21) {
System.out.print(Math.abs(x - 21));
} else if(x >= 21) {
System.out.print(Math.abs(x - 21) * 3);
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
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.println("\n" + x + " is a multiple of " + y + ".");
} else {
System.out.println("\n" + x + " is not a multiple of " + y + ".");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 53

Question:

Write a program to display the system time.

Solution:

public class MyClass {


public static void main(String[] args) {

618
System.out.format("\nCurrent Date time: %tc%n\n",
System.currentTimeMillis());
}
}

Question 54

Question:

Write a program to convert Celsius into Fahrenheit.

Solution:

public class MyClass {


public static void main(String[] args) {
float fahrenheit, celsius;
celsius = 36;
fahrenheit = (celsius * 9) / 5 + 32;
System.out.printf("\nTemperature in fahrenheit is: %f", fahrenheit);
}
}
public class MyClass {

public static void main(String[] args) {

int y = 9;

double x = y;

System.out.println(x); // Output: 9.0

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
if(x == 50 || y == 50 || x + y == 50) {
System.out.print("\nTrue");
} else {
System.out.print("\nFalse");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x, even = 0, odd = 0, positive = 0, negative = 0;
System.out.println("\nPlease enter 18 numbers:");
for(int i = 0; i < 18; i++) {
x = STDIN_SCANNER.nextInt();
if(x > 0) {
positive++;
}
if(x < 0) {
negative++;
}
if(x % 2 == 0) {
even++;
}
if(x % 2 != 0) {
odd++;
}
}
System.out.print("\nNumber of even values: " + even);

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:

Write a program to check whether the person is a senior citizen or not.

import java.util.ArrayList;
Solution:
public class MyClass {

import java.util.Scanner; public static void main(String[] args) {

ArrayList<String> x = new ArrayList<String>()


public class MyClass { x.add("Albert");
public static void main(String[] args) {
x.add("Joe");
int age;
x.add("Alan");
System.out.print("Enter age: ");
age = STDIN_SCANNER.nextInt(); x.add("Mary");

if(age >= 60) { System.out.println(x.get(0));


System.out.print("Senior citizen");
// Output: Albert
} else {
}
System.out.print("Not a senior citizen");
} }

}
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

average of those scores.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float score, totalScore = 0;
int subject = 0;
System.out.println("Enter three subject scores (0-100):");
while(subject != 3) {
score = STDIN_SCANNER.nextFloat();
if(score < 0 || score > 100) {
System.out.println("Please enter a valid score.");
} else {
totalScore += score;
subject++;
}
}
System.out.printf("Average score = %.2f\n", totalScore / 3);
}

623
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 59

Question:

What results would the following programs produce?

public class MyClass {


public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
if (i == 3) {
break;
import java.util.ArrayList;
}
System.out.println(i); public class MyClass {

} public static void main(String[] args) {


}
ArrayList<String> x = new ArrayList<String>();
}
x.add("Albert");

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

public class MyClass {


public static void main(String[] args) {
for(;;) {
System.out.println("This loop will run forever.");
}
}
}

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.

public class MyClass {


public static void main(String[] args) {
System.out.println((35.5 * 3.7 - 3.6 * 7.5) / (60.8 - 8.9));
}
}

Solution:

2.010597302504817

public class MyClass {


public static void main(String[] args) {
System.out.println("linux");
System.exit(0);
System.out.println("php");
}
}

626
Solution:

linux

public class MyClass {


public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
public class MyClass {
continue;
// Create a myfunc() method with an integer parameter called x
}
static void myfunc(int x) {
System.out.print(i + "\n ");
// If x is less than 18, print "Access denied"
}
} if(x < 18) {

} System.out.println("Access denied");

// If x is greater than, or equal to, 18, print "Access granted"

} 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
}

public class MyClass {


public static void main(String[] args) {
int a = 10, b = 20, c;
c = a < b ? a : b;
System.out.print(c);

627
}
}

Solution:

10

public class MyClass {


public final static int A = 15;
public static void main(String[] args) {
int x;
x = A; import java.util.ArrayList;
System.out.print(x);
public class MyClass {
}
public static void main(String[] args) {
}
ArrayList<String> x = new ArrayList<String>();

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));

public class MyClass { }

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

public class MyClass {


public static void main(String[] args) {
double a, b;
a = -2.5;
b = Math.abs(a);
System.out.printf("|%.2f| = %.2f\n", a, b);
}
}

Solution:

629
|-2.50| = 2.50

public class MyClass {


public static void main(String[] args) {
int x = 12, y = 3;
System.out.println(Math.abs(-x - y)); import java.util.ArrayList;

} import java.util.Iterator;
}

public class MyClass {

public static void main(String[] args) {

ArrayList<String> x = new ArrayList<String>();


Solution: x.add("Albert");

x.add("John");
15
x.add("James");

x.add("Mary");

Iterator<String> it = x.iterator();
public class MyClass {
public static void main(String[] args) { System.out.println(it.next());

int x = 12, y = 3; // Output: Albert


System.out.println(-(-x - y));
}
}
}
}

Solution:

630
15

public class MyClass {


public static void main(String[] args) {
int x = 12, y = 3;
System.out.println(x - -y);
}
}

Solution:

15

public class MyClass {


static void myMethod() {
System.out.println("Anyone who has never made a mistake has never tried
anything new.");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

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:

Write a program to find the size of an array.

Solution:

public class MyClass {


public static void main(String[] args) {
int[] num = {11, 22, 33, 44, 55, 66};
int n = (int)num.length;
System.out.println("Size of the array is: " + n);
}
}

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;

public class MyClass {


public static void main(String[] args) {
int x, i;
System.out.println("\nEnter a integer: ");
x = STDIN_SCANNER.nextInt();
if(x > 0) {
System.out.println("Sequence from 1 to " + x + ":");
for(i = 1; i < x; i++) {
System.out.print(i + "+");
}
System.out.println(i);
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int a, b, c;
System.out.println("Enter the three sides of a triangle: ");
a = STDIN_SCANNER.nextInt();
b = STDIN_SCANNER.nextInt();
c = STDIN_SCANNER.nextInt();
if(a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a *
a) {
System.out.println("Triangle's three sides form a right angled
triangle.");
} else {
System.out.println("Triangle's three sides does not form a right angled
triangle.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int a, b, c;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third number: ");
c = STDIN_SCANNER.nextInt();
if(a > b && a > c) {
if (b > c) {
System.out.print("\n" + b + " is second largest number among three
numbers");
} else {
System.out.print("\n" + c + " is second largest number among three
numbers");
}
} else if(b > c && b > a) {
if(c > a) {

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:

public class MyClass {


public static void main(String[] args) {
System.out.print(myfunc(3, 5));

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;

public class MyClass {


public static void main(String[] args) {
int mins, hrs;
System.out.print("Input minutes: ");
mins = STDIN_SCANNER.nextInt();
hrs = mins / 60;
mins = mins % 60;
System.out.println("\n" + hrs + " Hours, " + mins + " Minutes.");
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

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);
}

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
if(x >= 100 && x <= 200 || y >= 100 && y <= 200) {
System.out.print("True");
} else {
System.out.print("False");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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:

public class MyClass {


public static void main(String[] args) {
System.out.print(myfunc(86, 99));
System.out.print("\n" + myfunc(55, 55));
System.out.print("\n" + myfunc(65, 80));
}

public static int myfunc(int a, int b) {


int x = Math.abs(a - 100);
int y = Math.abs(b - 100);
return x == y ? 0 : (x < y ? a : b);
}

public class MyClass {

public static void main(String[] args) {

int a = 15;

int b = 13;

// returns false because 15 is not equal to 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 A 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 {

public static void main(String[] args) {

int x = 15;

// returns true because 15 is greater than 13 AND 15 is less than 30

System.out.println(x > 13 && x < 30);

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
if(Math.abs(x % 10) == Math.abs(y % 10)) {
System.out.print("True");
} else {
System.out.print("False");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

642
Question 71

Question:

Write a program to determine whether a given non-negative number is a multiple of 12 or


it is one more than a multiple of 12.

import java.util.ArrayList;

public class MyClass {

Solution: public static void main(String[] args) {

ArrayList<Integer> x = new ArrayList<Integer>();


public class MyClass {
public static void main(String[] args) { x.add(30);

int x = 43; x.add(45);


if(x % 12 == 0 || x % 12 == 1) {
x.add(50);
System.out.print("True");
} else { x.add(65);

System.out.print("False"); for(int i : x) {
}
System.out.println(i);
} } M

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
if(x == 6 || y == 6 || x + y == 6 || Math.abs(x - y) == 6) {
System.out.print("True");
} else {
System.out.print("False");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x, y, z;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for z: ");
z = STDIN_SCANNER.nextInt();
if(x == y + z || y == x + z || z == x + y) {
System.out.print("T rue");
} else {
System.out.print("False");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 74

Question:

Write a program that converts kilometers per hour to miles per hour.

Solution:

645
import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float kmph;
System.out.print("Enter kilometers per hour: ");
kmph = STDIN_SCANNER.nextFloat();
System.out.printf("\n%f miles per hour", kmph * 0.6213712);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 75

Question:

Write a program to calculate area of an ellipse.

Solution:

import java.util.Scanner;

public class MyClass {


public final static double PI = 3.141592;
public static void main(String[] args) {
float major, minor;
System.out.print("\nEnter length of major axis: ");
major = STDIN_SCANNER.nextFloat();
System.out.print("\nEnter length of minor axis: ");

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:

public class MyClass {


public static void main(String[] args) {
System.out.print("\n" + myfunc(11, 11, 11));
System.out.print("\n" + myfunc(11, 11, 16));
System.out.print("\n" + myfunc(18, 15, 10));
}

public static int myfunc(int a, int b, int c) {


if(a == b && b == c) {
return 0;
}
if(a == b) {
return c;
}

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:

Write a program to convert bytes to kilobytes.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
double bytes;
System.out.print("\nEnter number of bytes: ");
bytes = STDIN_SCANNER.nextDouble();
System.out.printf("\nKilobytes: %.2f", bytes / 1024);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);

648
}

Question 78

Question:

Write a program to convert megabytes to kilobytes.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
double megabytes, kilobytes;
System.out.print("\nInput the amount of megabytes to convert: ");
megabytes = STDIN_SCANNER.nextDouble();
kilobytes = megabytes * 1_024;
System.out.printf("\nThere are %f kilobytes in %f megabytes.", kilobytes,
megabytes);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

649
Question 79

Question:

Write a program to count the number of even elements in an integer array.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int[] array = new int[1000];
int arrSize, even = 0;
System.out.print("Input the size of the array: ");
arrSize = STDIN_SCANNER.nextInt();
System.out.println("Enter the elements in array: ");
for(int i = 0; i < arrSize; i++) {
array[i] = STDIN_SCANNER.nextInt();
}

for(int i = 0; i < arrSize; i++) {


if(array[i] % 2 == 0) {
even++;
}
}
System.out.print("Number of even elements: " + even);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

650
Question 80

Question:

Write a program to count the number of odd elements in an integer array.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int[] array = new int[1000];
int arrSize, odd = 0;
System.out.print("Input the size of the array: ");
arrSize = STDIN_SCANNER.nextInt();
System.out.println("Enter the elements in array: ");
for(int i = 0; i < arrSize; i++) {
array[i] = STDIN_SCANNER.nextInt();
}

for(int i = 0; i < arrSize; i++) {


if(array[i] % 2 != 0) {
odd++;
}
}
System.out.print("Number of odd elements: " + odd);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.println("Input the values for x and y: ");
x = STDIN_SCANNER.nextInt();
y = STDIN_SCANNER.nextInt();
if(x == y) {
System.out.println("x and y are equal");
} else {
System.out.println("x and y are not equal");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int angle1, angle2;
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("\nThird angle of the triangle is: " + (180 - (angle1 +
angle2)));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 83

Question:

Write a program to determine whether a particular year is a leap year or not.

653
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int year;
System.out.print("Enter the year: ");
year = STDIN_SCANNER.nextInt();
if(year % 400 == 0) {
System.out.print("\n" + year + " is a leap year.");
} else if(year % 100 == 0) {
System.out.print("\n" + year + " is a not leap year.");
} else if(year % 4 == 0) {
System.out.print("\n" + year + " is a leap year.");
} else {
System.out.print("\n" + year + " is not a leap year.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int age;
System.out.print("\nEnter the age of the candidate: ");
age = STDIN_SCANNER.nextInt();
if(age < 18) {
System.out.print("\nWe apologize, but the candidate is not able to cast
his vote.");
System.out.print("\nAfter " + (18 - age) + " year, the candidate would be
able to cast his vote.");
} else {
System.out.println("Congratulation! the candidate is qualified to cast
his vote.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 85

Question:

Write a program to Convert Yard to Foot.

655
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float yard;
System.out.print("\nEnter the Length in Yard : ");
yard = STDIN_SCANNER.nextFloat();
System.out.printf("\n%f Yard in Foot is: %f", yard, 3 * yard);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 86

Question:

Write a program to convert gigabytes to megabytes.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
double gigabytes, megabytes;
System.out.print("\nInput the amount of gigabytes to convert: ");
gigabytes = STDIN_SCANNER.nextDouble();

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:

Write a program to Convert Kilogram to Pounds.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float kg, lbs;
System.out.print("\nEnter Weight in Kilogram: ");
kg = STDIN_SCANNER.nextFloat();
lbs = (float)(kg * 2.20462);
System.out.printf("\n%f Kg = %f Pounds", kg, lbs);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

657
Question 88

Question:

Write a program to Convert Kilogram to Ounce.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float kg, ounce;
System.out.print("\nEnter Weight in Kilogram: ");
kg = STDIN_SCANNER.nextFloat();
ounce = (float)(kg * 35.274);
System.out.printf("\n%f Kg = %f Ounce", kg, ounce);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 89

Question:

Write a program to Convert Pounds to Grams.

658
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
float pound, gram;
System.out.print("\nEnter Weight in Pounds: ");
pound = STDIN_SCANNER.nextFloat();
gram = (float)(pound * 453.592);
System.out.printf("\n%f Pound = %f Grams", pound, gram);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 90

Question:

Write a program to verify whether a triangle is valid or not using angles.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {

659
int angle1, angle2, angle3, sum;
System.out.print("\nEnter the first angle of the triangle: ");
anglel = 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;

public class MyClass {


public static void main(String[] args) {

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:

Write a program to verify if a character you entered is a vowel or a consonant.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a alphabet: ");
char ch = scanner.next().charAt(0);

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) {

ArrayList<String> x = new ArrayList<String>();

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;

public class MyClass {


public static void main(String[] args) {
int fact = 1, num;
System.out.print("\nEnter a number: ");
num = STDIN_SCANNER.nextInt();
for(int i = 1; i <= num; i++) {
fact = fact * i;

662
}
System.out.print("\nFactorial of " + num + " is: " + fact);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 94

Question:

Write a program to print number of days in a month.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int[] x = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int m;
System.out.print("\nEnter the month number: ");
m = STDIN_SCANNER.nextInt();
if(m > 12 || m < 1) {
System.out.print("Invalid input");
} else if(m == 2) {
System.out.print("\nNumber of days in month 2 is either 29 or 28");
} else {
System.out.print("\nNumber of days in month " + m + " is " + x[m - 1]);
}

663
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 95

Question:

Write a program to concatenate multiple strings.

Solution:

public class MyClass {


public static void main(String[] args) {
String x = "Stephen";
String y = "-William"; public class MyClass {
String z = "-Hawking";
public static void main(String[] args) {
String c = x.concat(y).concat(z);
System.out.println(c); Integer x = 10065;

}
String y = x.toString();
}
System.out.println(y.length());

// Output: 5

Question 96 }

}
Question:

Write a program to find maximum between two numbers.

664
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int a, b;
System.out.println("Enter two numbers: ");
a = STDIN_SCANNER.nextInt();
b = STDIN_SCANNER.nextInt();
if(a > b) {
System.out.print("\n" + a + " is a maximum number");
} else {
System.out.print("\n" + b + " is a maximum number");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
public class MyClass {
public static void main(String args[]) {
double a = 15.143;
double b = 15.656;
System.out.println(Math.max(a, b));
}
}

665
Question 97

Question:

Write a program to compare two strings.

Solution:

public class MyClass {


public static void main(String[] args) {
String x = "Albert";
String y = "Albert";
if(x == y) {
System.out.println("The 2 strings are equal.");
}
else {
System.out.println("The 2 strings are not equal.");
}
}
}

public class MyClass {


public static void main(String[] args) {
String x = "Albert";
String y = "Albert";
if(x.equals(y)) {
System.out.println("The 2 strings are equal.");

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:

public class MyClass {


public static void main(String args[]) {
String x = new String("ALBERT EINSTEIN");
System.out.println(x.toLowerCase());
}
} public class MyClass {

public static void main(String[] args) {

String a = "20";

int b = 30;

String c = a + b;

System.out.println(c); // Output: 2030

667
Question 99

Question:

Write a program to find the quotient and remainder of a entered dividend and divisor.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int dividend, divisor;
System.out.print("\nEnter dividend: ");
dividend = STDIN_SCANNER.nextInt();
System.out.print("\nEnter divisor: ");
divisor = STDIN_SCANNER.nextInt();
System.out.println("\nQuotient = " + (dividend / divisor));
System.out.print("\nRemainder = " + (dividend % divisor));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 100

Question:

Write a program to determine the Size of int, float, double and char.

668
Solution:

public class MyClass {


public static void main (String[] args) {
System.out.println("Size of int is: " + (Integer.SIZE/8) + " bytes.");
System.out.println("Size of char is: "+ (Character.SIZE/8) + " bytes.");
System.out.println("Size of float is: " + (Float.SIZE/8) + " bytes.");
System.out.println("Size of double is: " + (Double.SIZE/8) + " bytes.");
}
}

Question 101

Question:

Write a program to promt user for 4 times password check.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
String password = "123";
String inputPass;
Scanner input = new Scanner(System.in);
System.out.println("Enter Your Password: ");

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:

Write a program to find absolute value of a number.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int num;
System.out.println("Input a positive or negative number: ");

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;

public class MyClass {


public static void main(String[] args) {

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;

public class MyClass {


public static void main(String[] args) {

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.

Otherwise print "No".

Solution:

public class MyClass {


public static void main(String[] args) throws Exception {
char ch;
System.out.println("Enter a character: ");
ch = (char)System.in.read();
if(ch == 'y' || ch == 'Y') {
System.out.println("Yes\n");
}
else {
System.out.println("No\n");
}
public class MyClass {
}
public static void main(String[] args) {
}
// return a random number between 0 and 1

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;

public class MyClass {


public static void main(String[] args) {
long x, y;
System.out.print("Enter a integer: ");
x = STDIN_SCANNER.nextLong();
y = x;
x = x << 2;
System.out.println(y + " x 4 = " + x);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter a number: ");
x = STDIN_SCANNER.nextInt();
if(x != 0 && (x & x - 1) == 0) {
System.out.print("\n" + x + " is a power of 2");
} else {
System.out.print("\n" + x + " is not a power of 2");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 108

Question:

Write a program to determine whether a triangle is scalene, isosceles, or equilateral.

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:

public class MyClass {


public static void main(String[] args) {
for(int i = 'A'; i <= 'Z'; i++) {
System.out.println("ASCII value of " + ((char)Byte.toUnsignedInt((byte)i)) +
" = " + i);
}
}
}

Question 110

Question:

Write a program to find sum of even numbers between 1 to n.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int num, sum = 0;
System.out.print("Enter a number: ");
num = STDIN_SCANNER.nextInt();
for(int i = 2; i <= num; i = i + 2) {
sum = sum + i;
}

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:

Write a program to find sum of odd numbers between 1 to n.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int num, sum = 0;
System.out.print("Enter a number: ");
num = STDIN_SCANNER.nextInt();
for(int i = 1; i <= num; i = i + 2) {
sum = sum + i;
}
System.out.print("\nSum of all odd number between 1 to " + num + " is: " +
sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int cp, sp;
System.out.print("\nInput Cost Price: ");
cp = STDIN_SCANNER.nextInt();
System.out.print("\nInput Selling Price: ");
sp = STDIN_SCANNER.nextInt();
if(sp > cp) {
System.out.print("Profit = " + (sp - cp));
} else if(cp > sp) {
System.out.print("Loss = " + (cp - sp));
} else {
System.out.print("No Profit No Loss.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 114

Question:

Write a program that display the pattern like a right angle triangle using an asterisk.

681
Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int rows;
System.out.print("Input the number of rows: ");
rows = STDIN_SCANNER.nextInt();
for(int x = 1; x <= rows; x++) {
for(int y = 1; y <= x; y++) {
System.out.print("*");
}
System.out.println();
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 115

Question:

Write a program that display the pattern like a right angle triangle using a number.

Solution:

682
import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int rows;
System.out.print("Input the number of rows: ");
rows = STDIN_SCANNER.nextInt();
for(int x = 1; x <= rows; x++) {
for(int y = 1; y <= x; y++) {
System.out.print(y);
}
System.out.println();
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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:

public class MyClass {


public static void main(String[] args) {

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;

public class MyClass {


public static int myfunc(int x) {
return x & 1;
}

public static void main(String[] args) {

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:

Write a program to find square root of a entered number.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x;
System.out.print("Enter any number: ");
x = STDIN_SCANNER.nextInt();
System.out.printf("Square root of %d is %.2f", x, Math.sqrt(x));

685
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 119

Question:

Write a program to find power of a entered number using library function.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int x, y;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
System.out.print("\n" + x + "A" + y + " = " + ((long)Math.pow(x, y)));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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:

Write a program to determine whether the given character is an alphanumeric character

or not.

Solution:

public class MyClass {


public static void main(String[] args) {
String x="abc123", y="abc.com";
System.out.println(x.matches("[a-zA-Z0-9]+"));
System.out.println(y.matches("[a-zA-Z0-9]+"));
}
}

Question 122

Question:

Write a program to illustrate try-catch statement.

688
Solution:

public class MyClass {


public static void main(String[] args) {
try {
int[] num = {1, 2, 3};
System.out.println(num[3]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Question 123

Question:

Write a program to remove all whitespaces from a given string.

Solution:

public class MyClass {


public static void main(String[] args) {
String x = "T his is b ett er.";
x = x.replaceAll("\\s", "");
System.out.println(x);
}

689
}

Question 124

Question:

Write a program to get current working directory.

Solution:

public class MyClass {


public static void main(String[] args) {
String path = System.getProperty("user.dir");
System.out.println("Current Working Directory: " + path);
}
}

Question 125

Question:

Write a program to split a sentence into words.

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:

Write a program to replace all occurrences of 'a' to 'e' in a string.

Solution:

public class MyClass {


public static void main(String args[]){
String x="Java is a powerful general-purpose programming language.";
String replaceString=x.replace('a','e');
System.out.println(replaceString);
}
}

691
Question 127

Question:

Write a program to check if the given string is empty or not.

Solution:

public class MyClass {


public static void main(String[] args) {
String a="";
String b="Java";
System.out.println(a.isEmpty());
System.out.println(b.isEmpty());
}
}

Question 128

Question:

Write a program to illustrate .joinO method.

Solution:

public class MyClass {


public static void main(String[] args) {

692
String a=String.join("-","Java","Programming");
System.out.println(a);
}
}

Question 129

Question:

Write a program to calculate surface area of cube.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int side;
long area;
System.out.print("\nEnter the side of cube: ");
side = STDIN_SCANNER.nextInt();
area = 6 * side * side;
System.out.print("\nThe surface area of cube is: " + area);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

693
Question 130

Question:

Write a program to subtract 2 numbers without using subtraction operator.

Solution:

public class MyClass {


public static void main(String[] args) {
int x = 6, y = 3;
System.out.print(x + ~y + 1);
}
}

Question 131

Question:

Write a program to add 2 numbers without using addition operator.

Solution:

public class MyClass {


public static void main(String[] args) {
int x = 6, y = 3;
System.out.print(x - ~y - 1);

694
}
}

Question 132

Question:

Write a program to multiply a number by 2 without using multiplication operator.

Solution:

public class MyClass {


public static void main(String[] args) {
int x = 2;
System.out.print(x << 1);
}
}

Question 134

Question:

Write a program to divide a number by 2 without using division operator.

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:
}

Write a program to calculate volume of sphere. }

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int radius;
float PI = 3.141592f;
System.out.print("\nEnter the radius of sphere: ");
radius = STDIN_SCANNER.nextInt();
float volume = (4 / 3) * (PI * radius * radius * radius);
System.out.printf("\nThe volume of sphere is: %f", volume);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

696
Question 136

Question:

Write a program to calculate volume of ellipsoid.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int r1, r2, r3;
float PI = 3.141592f;
System.out.print("\nEnter the radius of the ellipsoid of axis 1: ");
r1 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the radius of the ellipsoid of axis 2: ");
r2 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the radius of the ellipsoid of axis 3: ");
r3 = STDIN_SCANNER.nextInt();
float volume = (4 / 3) * (PI * r1 * r2 * r3);
System.out.printf("\nThe volume of ellipsoid is: %f", volume);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

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;

public class MyClass {


public static void main(String[] args) {
int x, y;
long power = 1;
System.out.print("\nEnter the value for x: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the value for y: ");
y = STDIN_SCANNER.nextInt();
for(int i = 1; i <= y; i++) {
power = power * x;
}
System.out.print(x + " A " + y + " = " + power);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

698
Question 138

Question:

Write a program to read three numbers and find average of numbers.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int a, b, c;
float avg;
System.out.print("\nEnter the first number: ");
a = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
b = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third number: ");
c = STDIN_SCANNER.nextInt();
avg = (float)((a + b + c) / 3.0);
System.out.printf("\nAverage of three numbers is: %f", avg);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

699
Question 139

Question:

Write a program to read integer "n" and print first three powers (n1, n2, n3).

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
int n;
System.out.print("\nEnter a number: ");
n = STDIN_SCANNER.nextInt();
System.out.printf("%f, %f, %f", Math.pow(n, 1), Math.pow(n, 2), Math.pow(n,
3));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Question 140

Question:

Write a program to search the substring in a given string.

700
Solution:

public class MyClass {


public static void main(String[] args) {
String name="Java is a powerful general-purpose programming language";
System.out.println(name.contains("Java"));
System.out.println(name.contains("programming"));
System.out.println(name.contains("language"));
}
}

Question 141

Question:

Write a program to check if the string ends with a given suffix.

Solution:

public class MyClass {


public static void main(String[] args) {
String a="Java Programming";
System.out.println(a.endsWith("g"));
}
}

701
Question 142

Question:

Write a program to check if the string starts with the given prefix.

Solution:

public class MyClass {


public static void main(String[] args) {
String a="Java Programming";
System.out.println(a.startsWith("j"));
System.out.println(a.startsWith("J"));
}
}

Question 143

Question:

Write a program to check whether a character is alphabet, digit or special character.

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:

Write a program to Check whether Java is installed on your computer.

Solution:

public class MyClass {


public static void main(String[] args) {
System.out.println("\nJava Version: "+System.getProperty("java.version"));
System.out.println("Java Runtime Version:
"+System.getProperty("j ava.runtime.version"));

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("j ava.vendor.url"));
System.out.println("Java Class Path:
"+System.getProperty("java.class.path")+"\n");
}
}

Question 145

Question:

Write a program to Check whether Java is installed on your computer.

Solution:

public class MyClass {


public static void main(String[] args) {
System.out.println("\nJava Version: "+System.getProperty("java.version"));
System.out.println("Java Runtime Version:
"+System.getProperty("j ava.runtime.version"));
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("j ava.vendor.url"));
System.out.println("Java Class Path:
"+System.getProperty("java.class.path")+"\n");
}

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:

Write a program to measure how long code takes to execute in nanoseconds.

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:

Write a program to replace the spaces of a string with a specific character.

Solution:

public class MyClass {


public static void main(String[] args) {
String a = "Java Programming";
char ch = '-';

706
a = a.replace(' ', ch);
System.out.println("String after replacing spaces with the character '-': ");
System.out.println(a);
}
}

Question 149

Question:

Write a program to count the total number of punctuations in a given string.

Solution:

public class Main {


public static void main (String args[]) {
int count = 0;
String str = "Logic will get you from A to Z; imagination will get you
everywhere.";
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '!' || str.charAt(i) == ',' || str.charAt(i) == ';'
|| str.charAt(i) == '.' || str.charAt(i) == '?' || str.charAt(i) == '-'
|| str.charAt(i) == '\'' || str.charAt(i) == '\"' || str.charAt(i) == ':') {
count++;
}
}
System.out.println("The total number of punctuations in a given string is: "
+count);
}

707
}

Question 150

Question:

Write a program to convert Decimal to Hexadecimal.

Solution:

public class MyClass {


public static void main(String args[]){
System.out.println(Integer.toHexString(10));
System.out.println(Integer.toHexString(15));
System.out.println(Integer.toHexString(289));
}
}

Question 151

Question:

Write a program to convert Decimal to Octal.

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:

Write a program to convert Decimal to Binary.

Solution:

public class MyClass {


public static void main(String args[]){
System.out.println(Integer.toBinaryString(10));
System.out.println(Integer.toBinaryString(21));
System.out.println(Integer.toBinaryString(31));
}

709
Question 153

Question:

Write a program to convert Binary to Decimal.

Solution:

public class MyClass {


public static void main(String args[]){
String a="1010";
public class MyClass {
int decimal=Integer.parseInt(a, 2);
int x = 15;
System.out.println(decimal);
public static void main(String[] args) {
}
} Main myfunc = new Main();

System.out.println(myfunc.x);

// Output: 15

Question 154 }

Question:

Write a program to convert Hexadecimal to Decimal.

Solution:

710
public class MyClass {
public static void main(String args[]){
String hex="a";
int decimal=lnteger.parselnt(hex, 16);
System.out.println(decimal);
}

Question 155

Question:

Write a program to determine whether one string is a rotation of another.

Solution:

public class MyClass {


public static void main(String[] args) {
String x = "abcde", y = "deabc";
if(x.length() != y.length()){
System.out.println("Second string is not a rotation of first string");
}
else {
x = x.concat(x);

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:

Write a program to illustrate the isNaN method.

Solution:

public class MyClass {


public static void main(String args[]) {

/* The isNaN method returns true if the value is NaN. */

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:

Write a program to illustrate the isNaN method.

Solution:

public class MyClass {


public static void main(String args[]) {

/* The isNaN method returns true if the value is NaN. */

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));
} I----------------
public class MyClass {

public static void main(String[] args) {

String[] x = {"Apple", "Orange", "Kiwi", "Lemon"};

for (String i : x) {

System.out.println(i);
} ?

713
Question 158

Question:

Write a program to Design Simple Calculator.

Solution:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {

char operator;
Double number1, number2, result;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);

System.out.println("Enter first number:");


number1 = input.nextDouble();

System.out.println("Enter second number:");


number2 = input.nextDouble();

switch (operator) {

case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);

714
break;

case '-':
result = numberl - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;

case '*':
result = numberl * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;

case '/':
result = numberl / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}

input.close();
}
}

public class MyClass {

public static void main(String[] args) {

int[][] x = { {11, 12, 13, 14}, {15, 16, 17}};

System.out.println(x[1][2]); // Output: 17

715
Question 159

Question:

Write a program to print Invert Triangle.

Solution:

public class MyClass {


public static void main(String args[]) {
int x = 9;
while(x > 0) {
for(int i=1; i<=x; i++) {
System.out.print(" "+x+" ");
}
System.out.print("\n");
x--;
}
}
}

public class MyClass {

public static void main(String[] args) {

String[] x = {"Albert", "John", "James", "Mary"};

x[0] = "Elsa";

System.out.println(x[0]); // Output: Elsa

716
public class MyClass {

public static void main (String [] args) {

String x = "Einstein";

System.out.println(x.charAt(1));

// Output: i

public class MyClass {

public static void main (String [] args){


# Output:
String x = " Albert ";
Albert
System.out.println(x);
Albert
System.out.println(x.trim());

public class MyClass {

public static void main (String [] args){

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(y)); // Output: -57

System.out.println(Math.round(z)); // Output: 56

717
public class MyClass {

public static void main (String [] args){

String x = "Most Important Programming Concepts";

System.out.println(x.substring(15));

// Output: Programming Concepts

System.out.println(x.substring(26));

// Output: Concepts

System.out.println(x.substring(15, 26));

// Output: Programming

System.out.println(x.substring(0, 5));

// Output: Most

718
public class MyClass {

public static void main(String args[]) {

Integer i = new Integer(10);


Output:

int a = i; 10

System.out.println(a);

} -------------------------------------

public class MyClass {

public static void main(String args[]) {

StringBuffer buffer=new StringBuffer("Java");

buffer.append(" Programming");
Output:
System.out.println(buffer);
Java Programming
}

Overloading provides

• code clarity

• reduce complexity

• increases runtime presentation of a code

719
public class MyClass {

public static void main(String args[]) {

StringBuilder builder=new StringBuilder("Java");

builder.append(" Programming");

System.out.println(builder);

}
Output:

Java Programming

Function overloading Operator overloading

using a single name and giving adding extra functionality

more functionality to it for a certain operator

720
Python Exercises

Python is a well-known general-purpose, interactive, object-oriented, and high-level


programming language. Python is a dynamically typed, garbage-collected programming
language. Between 1985 and 1990, Guido van Rossum developed it. Python is a
wonderful introductory language since its code is clear and simple to read. Python is
capable of doing everything you ask of it. Python is the language for you if you're into
data research, machine learning, or web development. This chapter includes Python
programming language learning problems and solutions. Exercises are an excellent
approach to learn the Python programming language since you learn programming best
by doing. Python is a very well-liked programming language that enables you to create
anything from robotics to web applications.

721
Question 1

Question:

Write a program to add two numbers.

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)

# Output: Elsa (Einstein)

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:

a = int(input("Enter a number: "))

723
Question 4

Question:

Write a program to display the calendar of a given date.

names = ["Albert", "Paul", "John"]


Solution:

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:

Write a program to concatenate two strings.

Solution:

x = input("Enter first string to concatenate: ")


y = input("Enter second string to concatenate: ")
z = x + y
print("String after concatenation = ", z)

Question 7

Question:

Write a program to check if an item exists in the list.

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:

Write a program to join two or more lists.

Solution:

x = ["This" , "is", "a", "blood", "sample"]


y = [20, 6, 55, 3, 9, 7, 18, 20]
z = x + y
print(z)
x = min(15, 100, 215)

y = max(15, 100, 215)

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:

Write a program to calculate square root of a number. import math

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:

i = [6, 10, 75, 60, 55]


print([i[0], i[4]])

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))
k
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

elements of this list in it.

Solution:

x = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

x=input("Please enter a word: ") x = math.pi


z = x.casefold() print(x)
y = reversed(z)
# Output: 3.141592653589793
if list(z) == list(y):
print("It is palindrome")
else:
print("It is not palindrome")

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:

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]
print([i for i in set(x) if i in y])

Question 16

Question:

Write a program to add a string to text file.

Solution: x = ["albert", "john", "david"]

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:

Write a program to read a file and display its contents on console.

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()

str = "Stephen William Hawking"

x = re.split("\s", str)

Question 18 print(x)

# Output: ['Stephen', 'William', 'Hawking']


Question:

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

the elements that are common between the sets.

Solution:

x = {1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89}


y = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
print(set(x) & set(y))

731
Question 19

Question:

Write a program to split the characters of the given string into a list.

Solution:

x= "albert" A program to replace all white-space 1


y = list(x) characters with the symbol "+" B
print(y) import re

str = "Stephen William Hawking"

x = re.sub("\s", "+", str)

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:

x=int(input("Enter an integer: "))


print("The divisors of the number are: ")
for i in range(1,x+1):
if(x%i==0):

732
print(i)

Question 21

Question:

Write a program to Find the largest of three numbers.

Solution:

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
z = int(input("Enter third number: "))
if (x > y) and (x > z):
largest = x A program to return a list containing

elif (y > x) and (y > z): every occurrence of "in"

largest = y
else: import re
largest = z
str = "Albert Einstein"
print("The largest number is", largest)

x = re.findall("in", str)

print(x)

Question 22 # Output: ['in', 'in']

Question:

Write a program to find absolute value of a number.

733
Solution:

x = int(input("Enter a number: ")) A program to check if the string starts


if x >= 0: with "The" and ends with "secretary"
BmpoRRB^^H
r- - -
print(x)
str = "The boy is the sports secretary"
else:
x = re.search("AThe.*secretary$", str)
print(-x)

if x:
print("YES! We've got a match!")
else:
Question 23
^^^B print("No match")

Question: # Output: YES! We've got a match!

Write a program to find the length of a string.

Solution:

print("Enter 'y' for exit.")


i = input("Enter a string: ")
if i == 'y':
exit()
else:
print("Length of the string is: ", len(i))

734
Question 24

Question:

Write a program to print natural numbers from 1 to x.

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:

x = int(input("Please Enter any Number: "))


sum = 0
for i in range(1,x+1): x = [(2,6),(4,7),(5,9),(8,4),(2,1)]
sum = sum + i
x.sort()
print(sum)
average = sum / x print(x)
print(average)
# Output: [(2, 1), (2, 6), (4, 7), (5, 9), (8, 4)]

735
Question 26

Question:

Write a program to print a statement any number of times.

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]))

# Output: <class 'list'>


Question 27
print(type({1,2}))

Question:
# Output: <class 'set'>

Write a program to multiply two numbers using Function.

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)

Write a program to add an item to the end of the list. # Output: 4

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:

x = ["pen", "book", "ball"]


x.remove("ball")

737
print(x)

Question 30

Question:

Write a program to print the number of elements in an array.

Solution:

x = ["pen", "book", "ball"]


import sys
y = len(x)
print(y) sys.stdout.write("Albert ")

sys.stdout.write("Einstein")

# Output: Albert Einstein


Question 31

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

# Output: Albert Einstein


Question:

Write a program to get the difference between the two lists.

Solution:

x = [4, 5, 6, 7]
y = [4, 5]
print(list(set(x) - set(y)))

Question 33

Question:

Write a program to select an item randomly from a list.

Solution:

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:

Write a program to check whether a string starts with specified characters.

Solution:

x = "science.com"
print(x.startswith("phy"))
print("Albert ", end="")

print("Einstein")

# Output: Albert Einstein


Question 37

Question:

Write a program to create the multiplication table (from 1 to 10) of a number.

Solution:

x = int(input("Enter a number: "))


for i in range(1,11):

741
print(x,'x',i,'=',x*i)

Question 38

Question:

Write a program to check a triangle is equilateral, isosceles or scalene.

Solution: def main():

print("Enter lengths of the triangle sides: ") x = input('First number: ' )

x = int(input("x: ")) y = input('Second number: ')


y = int(input("y: "))
print(x + y)
z = int(input("z: "))
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:

x = int(input("Enter a number: "))


y = int(input("Enter a number: ")) def main():
z= x+y a = 2.5
if z in range(15, 20):
b = 2.9
print (20)
else: print(int(a) + int(b))

print(z)

main()

# Output: 4

Question 40

Question:

Write a program to convert degree to radian.

x = ["albert", "john", "david"]


Solution:
for i in x:
pi=22/7
if i == "john":
degree = int(input("lnput degrees: "))
continue
radian = degree*(pi/180)
print(radian) print(i)

# Output:

albert

david

743
Question 41

Question:

Write a program to generate a random number.

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:

Write a program to find the semi-perimeter of triangle.

Solution:

x = int(input('Enter first side: '))


y = int(input('Enter second side: '))
z = int(input('Enter third side: '))
s = (x + y + z) / 2
print(s)

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)

Write a program to multiply all numbers in the list. print(y)

# Output: 2

Solution:

import numpy
x = [1, 2, 3]
y = numpy.prod(x)
print(y)

745
Question 45

Question:

Write a program to print ASCII Value of a character.


x = "56"

print(type(x))

# Output: <class 'str'>


Solution:
y = int(x)
x = 'j'
print("The ASCII value of '" + x + "' is", ord(x)) print(type(y))

# Output: <class 'int'>

A program to convert
Question 46
'string' to 'int'

Question:

Write a program to print "#" without a newline or space.

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

print(type(y)) 'float' to 'int'

# Output: <class 'int'>

746
Question 47

Question:

Write a program that will convert a string to a float or an integer.

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:

Write a program to add and search data in the dictionary.

Solution:

# Define a dictionary
customers = {'1':'Mehzabin Afroze','2':'Md. Ali',
'3':'Mosarof Ahmed','4':'Mila Hasan', '5':'Yaqub Ali'}

# Append a new data


customers['6'] = 'Mehboba Ferdous'

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: ')

y = input('Second number: ')


# Take customer ID as input to search
if int(y) == 0:
name = input("Enter customer ID:")
print("Cannot divide by 0")

# Search the ID in the dictionary else:


for customer in customers:
print("Dividing", x, "by", y)
if customer == name:
print(int(x) / int(y))
print(customers[customer])
break main()

Question 49

Question:

Write a program to obtain the details of the math module.

Solution:

import math
print(dir(math))

748
Question 50

Question:

Write a program to demonstrate throw and catch exception.

Solution: import random

# Try block names = ["Albert", "John", "Mary", "Alan"]


try:
# pick and print one of the names
# Take a number
x = int(input("Enter a number: ")) print(random.choice(names))
if x % 2 == 0:
# Output: Albert
print("Number is even")
else:
print("Number is odd")

# 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:

Write a program to illustrate password authentication.

a = 4

Solution: b = 2

# import getpass module print(a ** b) # is the same as a A b


import getpass
# Output: 16

# Take password from the user print(a % b)


passwd = getpass.getpass('Password:')
# a is divided by b that returns 0 as the remainder

# Check the password # Output: 0

if passwd == "albert":
a += 2 # is the same as a = a + 2
print("You are authenticated")
else: print(a)

print("You are not authenticated")


# Output: 6

b -= 1 # is the same as b = b - 1

print(b)

Question 52 # Output: 1

Question:

Write a program to calculate the average of numbers in a given list.

750
Solution:

x=int(input("Enter the number of elements to be inserted: "))


y=[]
for i in range(0,x):
n=int(input("Enter element: "))
y.append(n)
avg=sum(y)/x
print("Average of elements in the list: ",round(avg,2))

Question 53

Question:

Write a program that sorts three integers without the need of loops or conditional

statements.
import random

x = "123456789"

# pick and print one of the numbers


Solution:
print(random.choice(x))

# 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:

Write a program to determine the sum of digits of a number.

Solution:

num = int(input("Enter a four digit number: "))


x = num //1000
y = (num - x*1000)//100
z = (num - x*1000 - y*100)//10
c = num - x*1000 - y*100 - z*10
print("The number's digits add up to: ", x+y+z+c)

Question 55

Question:

Write a program to take in the marks of 5 subjects and display the grade.

752
Solution:

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80 and avg<90): import random
print("Grade: B")
names = ["Albert", "Alan", "John", "James", "Mary"]
elif(avg>=70 and avg<80):
print("Grade: C") print(random.sample(names, 2))
elif(avg>=60 and avg<70):
# Output: ['Mary', 'James']
print("Grade: D")
else:
print("Grade: F")

Question 56

Question:

Write a program to print all numbers in a range divisible by a given number.

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:

a=int(input("Enter the first number: "))


b=int(input("Enter the second number: ")) for x in range(7):
quotient=a//b
remainder=a%b
print("Quotient is:", quotient)
print("Remainder is:", remainder)

754
Question 58

Question:

Write a program to determine whether a given value is present in a collection of values.

Solution: x = 0

if x:

def myfunc(x, i): print("Albert Einstein")

for value in x: else:


if i == value:
print("Elsa Einstein")
return True
return False
print(myfunc([19, 15, 18, 13], 13)) # Output: Elsa Einstein
print(myfunc([15, 18, 13], -11))

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:

Write a program to find the smallest divisor of an integer.

for i in range(5):
Solution:
print(i)

else:
n=int(input("Enter an integer: "))
print("Albert!")
a=[]
for i in range(2,n+1):
if(n%i==0): # Output:
a.append(i)
0
a.sort()
1
print("Smallest divisor is:",a[0])
2

Albert!

756
Question 61

Question:

Write a program to count the number of digits in a number.


x = "56"

y = 56

print(x == y)
Solution:
# Output: False

n=int(input("Enter a number:")) print(x != y)

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:

n=int(input("Enter a number: "))

757
x=[]
for i in range(1, n+1):
a = 16
print(i, sep=" ", end=" ")
if(i<n): b = 4

print("+", sep=" ", end=" ")


print(a > b)
x.append(i)
print("=",sum(x)) # Output: True

print()

Question 63

Question:

Write a program to read a number n and print the natural numbers summation pattern.

Solution:

n=int(input("Enter a number: ")) a = "16"


for j in range(1, n+1):
b = "4"
x=[]
for i in range(1, j+1): print(a > b)
print(i, sep=" ", end=" ")
# Output: False
if(i<j):
print("+",sep=" ",end=" ")
x.append(i)
print("=", sum(x))

758
print()

Question 64

Question:

Write a program to read a number n and print an identity matrix of the desired size.

Solution:

for j in range(0, n):

Output:

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:

n=int(input("Enter number of rows: ")) x = "Stephen " \


for i in range (n,0,-1):
"William " \
print((n-i) * ' ' + i * '*')
"Hawking"

print(x)

# Output: Stephen William Hawking


Question 66

Question:

Write a program to determine the hypotenuse of a right-angled triangle.

Solution:

from math import sqrt


print("Enter the lengths of shorter triangle sides: ")
x = float(input("x: "))
y = float(input("y: "))

760
z = sqrt(x**2 + y**2)
print("The length of the hypotenuse is: ", z)

Question 67

x = .. Stephen
Question:
William

Write a program to find the largest number in a list.


Hawking..

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:

Write a program to find the second largest number in a list.

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

str = str[:2] + 'Q' + str[3:]

print(str)

Question 70 # Output: wxQz

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:

result += str(i) print(a, b)


return result
# Output:
print(myfunc([2, 4, 13, 4])) Alan Turing

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:

def myfunc(a, b, c):


x = "albert"
if a == b or b == c or a==c:
sum = 0 y = x.upper()

else:
print(y)
sum = a + b + c
return sum # Output: ALBERT

print(myfunc(12, 11, 12))


print(y.lower())
print(myfunc(13, 22, 22))
print(myfunc(22, 22, 22)) # Output: albert
print(myfunc(12, 22, 13))

Question 72

Question:

Write a program to sort a list according to the length of the elements.

764
Solution: x = "Einstein"

if "ein" in x:

print('Found ein')
x=[]
n=int(input("Enter number of elements: ")) else:
for i in range(1,n+1):
print("NOT found ein")
y=input("Enter element: ")
x.append(y)
x.sort(key=len) # Output: Found ein
print(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:

x=int(input("Enter the lower range:"))


y=int(input("Enter the upper range:"))
a=[(i,i**2) for i in range(x,y+1)]
print(a)

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:

l=int(input("Enter lower range: "))


u=int(input("Enter upper range: "))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and
sum(list(map(int,str(x))))<10]
print(a)
for x in range(32, 126):

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:])

# Output: bert Einstein

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]

def sort(tuples): print(np.multiply(x, y))

return sorted(tuples, key=last) # Output: [6 24 96]

print(np.dot(x, y)) # dot product


a=input("Enter a list of tuples:")
# Output: 126
print("Sorted:")
print(sort(a)) print(np.matmul(x, y)) # matrix multiplication

# 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:

Write a program to determine whether the system is a big-endian or little-endian


platform.
x = 'Albert Einstein'

for i in x:

if i == ' ':
Solution:

break

import sys print(i)


print()
if sys.byteorder == "little":
print("Little-endian platform.") # Output:
else:
A
print("Big-endian platform.")
l
print()
b

Question 79 t

Question:

Write a program to examine the available built-in modules.

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)

Question 80 # Output: True

if i:
Question:
print("Albert Einstein")

Write a program to determine an object's size in bytes. else:

print("Elsa Einstein")

# Output: Albert Einstein


Solution:

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'

Write a program to concatenate 'n' strings. for i in x:

if i ==

continue
Solution:
print(i)

t
Question 82
E

Question:
n
Write a program to display the current date and time.
s

e
Solution:

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))

# Output: Albert Einstein's 1915 papers.


Question:

Write a program to calculate the volume of a sphere with a radius of 8.

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'

print(y + " Einstein's " + str(x) + " papers.")


Question 85

# Output: Albert Einstein's 1915 papers.


Question:

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=float(input("Enter the principal amount: "))


y=float(input("Enter the rate: "))
z=int(input("Enter the time (years): "))
simple_interest=(x*y*z)/100
print("The simple interest is: ", simple_interest)

x = 1915

y = 'Albert'

Question 87 print("{} Einstein's {} papers.".format(y, x))

# Output: Albert Einstein's 1915 papers.


Question:

Write a program to check whether a given year is a leap year or not.

Solution:

year=int(input("Enter the year to be checked: "))


if(year%4==0 and year%100!=0 or year%400==0):
print("The", year, "is a leap year!")
else:
print("The", year, "isn't a leap year!")

774
Question 88

Question:

Write a program that determines if a file path points to a file or a directory.

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("lt is a unique file (socket, FIFO, device file)" )
print()

x = 1915

y = 'Albert'

print("{0} Einstein's {1} papers.".format(y, x))


Question 89
# Output: Albert Einstein's 1915 papers.

Question:

Write a program to generate all the divisors of an integer.

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'

print("{1} Einstein's {0} papers.".format(y, x))


Question 90
# Output: 1915 Einstein's Albert papers.

Question:

Write a program to print the table of a given number.

Solution:

n=int(input("Enter the number to print the tables for: "))


for i in range(1,11):
print(n,"x",i, "=",n*i)

Question 91

Question:

Write a program to check if a number is an Armstrong number.

776
Solution:

n=int(input("Enter any number: "))


a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
print("The number", n, "is an armstrong number. ")
else:
print("The number", n, "isn't an arsmtrong number. ")

x = 1915

y = 'Albert'

Question 92 print(f"{y} Einstein's {x} papers.")

# Output: Albert Einstein's 1915 papers.


Question:

Write a program to find Python site-packages.

Solution:

import site
print(site.getsitepackages())

777
Question 93

Question:

Write a program to check if a number is a perfect number.

Solution:

x = int(input("Enter any number: "))


sum = 0
for i in range(1, x):
if(x % i == 0):
sum = sum + i
if (sum == x):
print("The number", x, "is a perfect number!")
else:
print("The number", x, "is not a perfect number!")

x 1915

y = 'Albert'

Question 94 print("{name} Einstein's {year} papers.".format(name = y, year = x))

# Output: Albert Einstein's 1915 papers.


Question:

Write a program to find the LCM of two numbers.

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

print("LCM is:",min)
print(i)
break
min=min+1 print('NSTEIN')

# Output:

A
Question 95
l

b
Question:
e

Write a program to find the GCD of two numbers. r

Solution:

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]

Question 96 ["Alan", 17]

["Mary", 39]
Question:
["James", 44]

Write a program to determine a file's size. ]

print(type(x))

Solution: # Output: <class 'list'>

for i in x:
import os
x = os.path.getsize("1.csv") print("{} {}".format(i[0], i[1]))
print("The size of l.csv is:", x, "Bytes")
print()
# Output:

John 56

Albert 77

Alan 17
Question 97
Mary 39

James 44
Question:

Write a program to check if two numbers are amicable numbers.

Solution:

x=int(input('Enter number 1: '))

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("'{:A12}'".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))

Question: # Output: Albert

Write a program to find the gravitational force acting between two objects.

Solution:

m1=float(input("Enter the first mass: "))


m2=float(input("Enter the second mass: "))
r=float(input("Enter the distance between the centers of the masses: "))
G=6.673*(10**-11)
f=(G*m1*m2)/(r**2)
print("Hence, the gravitational force is: ",round(f,2),"N")

Question 100

Question:

Write a program to determine if a string is numeric.

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

Question 101 print("{:F}".format(a))

# 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:

Write a program to find the sum of first n positive integers.

Solution:

n=int(input("Enter a number: "))


sum = 0
while(n > 0):
sum=sum+n
n=n-1
print("The sum of first n positive integers is: ", sum)

n = int(input("Enter a number: "))


sum = (n * (n + 1)) / 2
print("The sum of first", n /'positive integers is:", sum)

def myfunc(x = "Paul"):

print("Albert " + x)

myfunc("Einstein")

# Output: Albert Einstein

784
Question 103

Question:

Write a program to find the sum of series: 1 + 1/2 + 1/3 +...... + 1/n.

Solution:

n=int(input("Enter the number of terms: "))


sum=0
for i in range(1,n+1):
sum=sum+(1/i)
print("The sum of series is: ", round(sum,2))

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:

x = [55, 144, 72, 155, 120, 135, 540]


result = list(filter(lambda i: (i % 15 == 0), x))
print("Numbers divisible by 12 are: ", result)

785
Question 105

Question:

Write a program to format a given string with a string length limitation.

pi = 3.141592653589793
Solution:
r = 6

print(f"The value of PI is: '{pi:.4}'.")


x = "987653421066"
print('%.5s' % x) # Output: The value of PI is: '3.142'.
print('%.7s' % x)
print(f"The value of PI is: '{pi:.4f}'.")
print('%.9s' % x)
# Output: The value of PI is: '3.1416'.

print(f"Area of a circle is: {pi * r ** 2}")

# Output: Area of a circle is: 113.09733552923255

print(f"Area of a circle is: {pi * r ** 2:.4f}")


Question 106

# Output: Area of a circle is: 113.0973

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)

# Output: <68 >

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:

x = [22, -10, 11, -28, 52, -75]


y = list(filter(lambda i: i <0, x))
print("Negative numbers in the above list: ", y)

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:

Write a program to find whether a number is a power of two.

Solution:

def myfunc(n): x="Albert"


.. Return True if n is a power of two...
if n <= 0: print(r"b\nc {x}")

return False # Output: b\nc {x}


else:
return n & (n - 1) == 0 print(rf"b\nc {x}")

# Output: b\nc Albert

n = int(input('Enter a number: ')) print(fr"b\nc {x}")

# Output: b\nc Albert


if myfunc(n):
print('{} is a power of two.'.format(n))
else:
print('{} is not a power of two.'.format(n))

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:

Write a program to solve (a - b) * (a - b).

Solution:

a, b = 2, 4
result = a * a - 2 * a * b + b * b
print("({} - {}) A 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:

Write a program that count all occurrences of the number 5 in a list.

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

print(myfunc([11, 5, 16, 18, 15]))


print(myfunc([17, 14, 5, 12, 9, 5]))

790
Question 112

Question:

Write a program to determine if a file is present.

Question:

Write a program to replace all occurrences of 'a' with '$' in a string.

Solution:

x=input("Enter string: ")


x=x.replace('a','$')
x=x.replace('A','$')
print("Modified string: ")

791
print(x)

x = ['11', '12', '13', '14']

x[1:3] = ['alan', 'john']

Question 114 print(x)

# Output: ['11', 'alan', 'john', '14']


Question:

Write a program to calculate the product of a list of numbers (without using for loop).

Solution:

from functools import reduce


num = [2, 4, 10,11]
result = reduce( (lambda x, y: x * y), num)
print("Product of the above numbers is: ", result)

num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Question 115
print(num[1:20:3])

Question: # Output: ['2', '5', '8']

Write a program to detect if two strings are anagrams.

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 = ['11', '12', '13', '14']

x[1:3] = ['john']

Question 116 print(x)

# Output: ['11', 'john', '14']

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))

x = ['100', '120', '130', '140']

x[1:2] = ['bat', 'ball']

print(x)

# Output: ['100', 'bat', 'ball', '130', '140']

793
Question 117

Question:

Write a program to count the number of vowels in a string.

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]

x[1::2] = [10, 10, 10, 10, 10, 10]


Question 118
print(x)

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'

1print(a)
X z

# Output: ['computer', 'john', 'mary', 'david']

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:

s=input("Enter string: ")


x=0
for i in s:
x=x+1
print("Length of the string is: ")
print(x)

import array

x = array.array('i', [11,13,15,17,19,22])

print("Length of the array is: ", len(x))

# Output: Length of the array is: 6

795
Question 120

Question:

Write a program to determine whether lowercase letters are present in a string.

from copy import deepcopy


Solution:
a = ['green', 'red', 'blue', 'orange']

b = deepcopy(a)
x = 'Albert Einstein'
print(any(i.islower() for i in x)) a[0] = 'albert'

print(a)

# Output: ['albert', 'red', 'blue', 'orange']

print(b)

Question 121 # Output: ['green', 'red', 'blue', 'orange']

Question:

Write a program to calculate the number of words and characters present in a string.

Solution: x = ["albert", "1915", "john"]

y = ["albert", 1915, "john"]

x=input("Enter a string: ") print(":".join(x))


char=0
# Output: albert:1915:john
word=1
for i in x:
char=char+1

796
if(i==' '):
word=word+1
print("Number of words in the string: ")
print(word)
print("Number of characters in the string: ")
print(char)

x = ["albert", "1915", "john"]

y = ["albert", 1915, "john"]

print(":".join( map(str, y)))


Question 122
# Output: albert:1915:john

Question:

Write a program that rounds a floating-point integer to a specified number of decimal

places.

x = ["albert", "1915", "john"]


Solution:
y = ["albert", 1915, "john"]

x = 549.968 print(":".join(str(i) for i in y))

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:

Write a program to count number of lowercase characters in a string.

Solution:

x=input("Enter string: ") print("xy:wz:pq".split(':'))

count=0
# Output: ['xy', 'wz', 'pq']
for i in x:
if(i.islower()):
count=count+1

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(countl)
print("The number of uppercase characters is: ")
print(count2)

Question 125

Question:

Write a program to calculate the number of digits and letters in a string.

Solution: x = ['apple', 'orange', 'mango', 'kiwi']

print(x.index('orange' ))

x=input("Enter a string: ") # Output: 1

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(countl)
print("The number of characters is: ")
print(count2)

x = ['apple', 'orange', 'mango', 'kiwi']

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

from a given string.

Solution:

x=input("Enter a string: ")


count=0
for i in x:
count=count+1
new=x[0:2]+x[count-2:count]
print("Newly formed string is: ")
print(new) ----------
x = ['apple', 'orange', 'mango', 'kiwi']

x.insert(len(x), 'papaya')

print(x)

# Output: ['apple', 'orange', 'mango', 'kiwi', 'papaya']

800
Question 127

Question:

Write a program to create a bytearray from a list.

Solution:

x = [10, 20, 56, 35, 17, 99]


# Create bytearray from list of integers.
y = bytearray(x)
for i in y: print(i)
print()

Question:

Write a program to determine whether an integer fits in 64 bits.

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)

# Output: [17, 22, -44, 38, 6]

x.sort(reverse=True)

Question 129 print(x)

# Output: [38, 22, 17, 6, -44]


Question:

Write a program that returns true if the two given integer values are equal, or if their sum
or difference is 10.

Solution:

def myfunc(a, b):


if a == b or abs(a-b) == 10 or (a+b) == 10:
return True
else:
return False x = [17, 22, -44, 38, 6]
print(myfunc(17, 2))
print(x)
print(myfunc(30, 20))
print(myfunc(5, 5)) # Output: [17, 22, -44, 38, 6]
print(myfunc(17, 13))
x.sort(key=abs, reverse=True)
print(myfunc(53, 73))
print(x)

# Output: [-44, 38, 22, 17, 6]

802
Question 130

Question:

Write a program to add two objects if they are both of the integer type.

Solution:

def myfunc(x, y):


if not (isinstance(x, int) and isinstance(y, int)):
return "Inputs have to be integers only!"
return x + y
print(myfunc(50, 70))
print(myfunc(20, 50.74))
A program to sort the list
print(myfunc('6', 8))
according to length
print(myfunc('8', '8'))

x = ['alan', 'albert', 'james', 'bob']

x.sort(key=len)

Question 131
print(x)

# Output: ['bob', 'alan', 'james', 'albert']


Question:

Write a program to add leading zeros to a string.

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)

# Output: ['albert', 'james', 'alan', 'bob']

Question 132

Question:

Write a program that displays strings with double quotes.

Solution:

import json
print(json.dumps({'Albert': 1, 'Alan': 2, 'Alex': 3}))

Question 133

Question:

Write a program to check if a given key exists in a dictionary or not.

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:

Write a program to find the sum all the items in a dictionary.

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:

Write a program to multiply all the items in a dictionary.

Solution: x = ['albert', 'elsa']

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)

# Output: ['albert', 'elsa', 'david']


Question 136

Question:

Write a program to remove the given key from a dictionary.

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]

print([i for i in x if i%2!=0]) # Output:

[5, 57, 35]

807
Question 138 x = [0] * 5

for i in range(0, 5):


Question:
print("{} {}".format(i, x[i]))

Write a program to input two integers in a single line.


# Output:

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:

Write a program to convert true to 1 and false to 0.

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:

Write a program to determine whether a variable is an integer or a string.

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:

s=input("Enter a string: ")


count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("The number of vowels present in a string is: ")
print(count)
x= ['Alan Turing', 'Mary John']

y = ['David Hilbert', 'Joseph Sam']

x.extend(y)

Question 142 print(x)

# Output: ['Alan Turing', 'Mary John', 'David Hilbert', 'Joseph Sam']


Question:

Write a program to check common letters in the two input strings.

Solution:

x=input("Enter the first string: ")


y=input("Enter the second string: ")
z=list(set(x)&set(y))
print("The common letters are: ")
for i in z:
print(i)

810
Question 143

Question:

Write a program to display which letters are in the first string but not in the second string.

Solution:

x=input("Enter the first string: ")


y=input("Enter the second string: ")
z=list(set(x)-set(y))
print("The letters in the first string but not in the second string are: ")
for i in z:
print(i)

Question 144

Question:

Write a program to determine whether a variable is a list, tuple, or set.

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:

Write a program to determine whether a given number is even or odd recursively.

# 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)

return True # Output: {'name': 'albert', 'email': 'albert_john@gmail.com'}


else:
return False;
print(myfunc([11,15,17,19]))
print(myfunc([12,14,15,15,17,19]))

x = "Albert "

y = "Einstein" # Output: Albert Einstein

print(x + y)

813
Question 147

Question:

Write a program to add two positive numbers without using the ' + ' operator.

Solution: x = {

'name': 'Albert',

def myfunc(x, y): 'age': 26,


while y != 0: 'email': None
z = x & y x = lambda a, b: a * b
}
x = x A y
print(x(2, 2))
y = z << 1
return x # Output: 4 print(x.get('name'))
print(myfunc(12, 50))
# Output: Albert

print(x.get('age'))

# Output: 26

print(x.get('email'))

# Output: None
Question 148
print(x.get('address'))

Question: # Output: None

Write a program to find the factorial of a number using recursion.

Solution:

814
def myfunc(n): x = {
if(n <= 1):
'name': 'Albert',
return 1
else: 'age': 26,
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

Question 149 print('Albert' in x.values())

# 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:

print("Enter three side lengths of a triangle: ")


a,b,c = sorted(list(map(int,input().split())))
if a**2+b**2==c**2:
print('Yes')
else:
print('No')

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)

print(myfunc(11, 11, 11))


print(myfunc(11, 12, 12)) # Output: {'name': 'Albert', 'age': 26, 'email': None}

Question 151

Question:

Write a program to extract numbers from a given string.

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:

Write a program to get the smallest number from a list.

x = {}

x['A'] = 11
Solution:
x['B'] = 12

def myfunc(list): x['C'] = 13

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',

x = ["ball", "bat", "bag", "book"] 'email': 'albert_john@gmail.com'


y = ["book", "book", "book", "book"]
}

print(all(i == 'bag' for i in x))


print(all(i == 'book' for i in y))
for i in x:

print("{} -> {}".format(i, x[i]))

# Output:

U
name -> Albert

email -> albert john@gmail.com


Question:

Write a program to count the number of words in a text file.

Solution:

x = input("Enter the file name: ")


num_words = 0

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:

Write a program to count the number of lines in a text file.

Solution:

x = input("Enter the file name: ")


num_lines = 0
with open(x, 'r') as f:
for line in f:
num_lines += 1
print("Number of lines: ", num_lines)
x = 11

y = 12.5

z = "Albert"

print(type(x)) # Output: <class 'int'>

print(type(y)) # Output: <class 'float'>

print(type(z)) # Output: <class 'str'>

819
Question 156

Question:
x = set()

Write a program to create a list of empty dictionaries.


print(x)

# Output: set()

x.add('Mary')
Solution:
print(x)

print([{} for _ in range(10)]) # Output: {'Mary'}

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:

def myfunc(x, y):


result = sum(x + y) / len(x + y)
return result

x = [11, 11, 13, 14, 14, 15, 16, 17]


y = [0, 11, 12, 13, 14, 14, 15, 17, 18]

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(w) # Output: 5.6

print(z) # Output: 6

821
Question 159

Question:

Write a program to delete empty lists from a given list of lists.

Solution:

x = [[], [], [], ['Ball', 'Bag'], [11,12], ['Bat','Book'], []]


print([i for i in x if i])

Question 160

Question:

Write a program to determine whether or not every dictionary in a list is empty.

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

the lists is shared by both.

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"

print(x[2:5]) # Output: ber

823
Question 162

Question:

Write a program to determine whether a list is empty or not.

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:

x = input("Enter the file name: ")

824
set(['John', 'Mary'])

with open(x, 'r') as f: x = set(['Mary', 'James', 'Alan'])


for line in f:
y = set(['Bob', 'Joe', 'Albert', 'Mary'])
print(line.title())
x.update(y)

print(x)

# Output: {'Joe', 'Alan', 'Mary', 'James', 'Bob', 'Albert'}

print(y)
Question 164
# Output: {'Joe', 'Bob', 'Mary', 'Albert'}

Question:

Write a program to read the contents of a file in reverse order.

Solution: def myfunc(a, b):

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 165 # Output: 121

Question:

Write a program to decapitalize the first letter of a given string.

825
Solution:

def myfunc(i, x = False):


return ''.join([i[:1].lower(), (i[1:].upper() if x else i[1:])])
print(myfunc('Albert'))
print(myfunc('John'))

x :int = 6

print(x)

# Output: 6

Question 166

Question:

Write a program to remove spaces from a given string.

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:

def myfunc(a, b, c):


def myfunc(x :int, y :int) -> int:

sum = a + b + c return x+y

if a == b == c:
sum = sum * 3 print(myfunc(12, 13))
return sum
# Output: 25

print(myfunc(11, 12, 13))


print(myfunc(13, 13, 13))

Question 169

Question:

Write a program to check whether an OS is running a Python shell in 32 or 64 bit mode.

Solution:

import platform
print(platform.architecture()[0])

828
Question 170

Question:

Write a program to implement birthday dictionary.

import os

x = os.path.join('home', 'etc', 'files')


Solution: print(x)

if __name__ == '__ main__ ': # Output: home\etc\files

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'}

print('Welcome to the birthday dictionary. We know the birthdays of:')


for name in birthdays:
print(name)

print('Who\'s birthday do you want to look up?')


name = input()
if name in birthdays:
print('{}\'s birthday is {}.'.format(name, birthdays[name]))
else:
print('Sadly, we don\'t have {}\'s birthday.'.format(name))

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())

Question 172 # Output: Windows

print(platform.release())
Question:
# Output: 10
Write a program to implement password generator.

Solution:

import random
x =
"abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%A&*O?"

830
passlen = 8
print("".join(random.sample(x, passlen)))

x = ["apple", "orange", "kiwi", "ball", "bat", "blackboard"]

Question 173 print(list(filter(lambda i: len(i) == 4, x)))

# Output: ['kiwi', 'ball']


Question:

Write a program to display calendar of the given month and year.

from functools import reduce


Solution:
x = [11, 12, 13, 14]

print(reduce(lambda a, b: a+b, x))


# importing calendar module
# Output: 50
import calendar
print(reduce(lambda a, b: a*b, x))
yy = 2014 # year # Output: 24024
mm = 11 # month

# To take month and year input from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))

831
Question 174
from functools import reduce

Question:
print(reduce(lambda a, b: a+b, [], 1))

Write a program to eliminate a newline. # Output: 1

print(reduce(lambda a, b: a+b, [5, 5], 0))

# 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

print(reduce(lambda a, b: a*b, [], 0))


Question 175
# Output: 0

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:

Write a program to count the number of CPUs being used.

x = ['Mon', 'Tue', 'Wed', 'Thru', 'Fri']


Solution:
y = [1, 2, 3, 4, 5]

import multiprocessing print(zip(x, y))

print(multiprocessing.cpu_count())

Question 177

Question:

Write a program to reverse a string if its length is a multiple of 6.

833
Solution:

def myfunc(x):
if len(x) % 6 == 0:
return ''.join(reversed(x))
return x

print(myfunc('alan'))
print(myfunc('albert'))

x = ['Mon', 'Tue', 'Wed', 'Thru', 'Fri']

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

three, leave it unaltered.

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'))

x = ['Mon', 'Tue', 'Wed', 'Thru', 'Fri']

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:

Write a program to shuffle the elements of a given list.

Solution: import numpy as np

x = np.array([6, 8, 10], dtype='int8')

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))

import socket # Output: False


x = socket.gethostname()

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:
return False print(10 > 15)

# Output: False
print(myfunc([11,12,13,14]))
print(myfunc([11,12,15,13,14]))

x = ["alan", "john", "albert"]

x.clear()

print(x) # Output: []

837
Question 183

Question:

Write a program to illustrate Dice Roll Simulator.

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)))

roll_again = "yes" # Output: False

while roll_again == "yes" or roll_again == "y":


print ("Rolling the dices...")
print ("The values are....")
print (random.randint(min, max))
print (random.randint(min, max))

roll_again = input("Roll the dices again?")

Question 184

Question:

Write a program to convert the temperature in degree centigrade to Fahrenheit.

838
Solution:

c = input(" Enter temperature in Centigrade: ")


f = (9*(int(c))/5)+32
print(" Temperature in Fahrenheit is: ", f)

Question 185

Question:

Write a program to check whether the given integer is a multiple of 5.

import numpy as np

x = np.array([13, 14, 17])


Solution:
print(x)
x = int(input("Enter an integer: "))
# Output: [13 14 17]
if(x%5==0):
print(x, "is a multiple of 5") print(x * 3)
else:
# Output: [39 42 51]
print(x, "is not a multiple of 5")
print(x + 4)

# Output: [17 18 21]

Question 186 print(x.dtype)

# Output: int32
Question:

Write a program to check whether the given integer is a multiple of both 3 and 5.

839
Solution:

x = int(input("Enter an integer: "))


if((x%3==0)and(x%5==0)):
print(x, "is a multiple of both 3 and 5")
else:
print(x, "is not a multiple of both 3 and 5")

Question 187

Question:

Write a program to display all the multiples of 5 within the range 10 to 70.

Solution: x = [11, 12, 13, 450]

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.

Solution: from functools import reduce

x = [12, 11, 14, 31]

def myfunc(n): print(reduce(lambda a,b: a if a < b else b, x))


if (n==0):
# Output: 11 (minimum)
return
print(n) print(reduce(lambda a,b: a if a > b else b, x))
n=n-1
# Output: 31 (maximum)
myfunc(n)

841
myfunc(9)
from functools import reduce

x = 5

print(reduce(lambda a,b: a*b, range(1, x+1), 1))


Question 190
# Output: 120 (factorial of 5)

Question:

Write a program to find the odd numbers in an array.

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:

Write a program to reverse a given upper case string in lower case.

Solution:

842
import numpy as np
def myfunc(x):
x = np.array([
return x[::-1].lower()
x = "JAVASCRIPT" [ 11, 12, 13, 14, 15],

print(myfunc(x)) [ 12, 13, 14, 15, 16]

])

print(x)

print(x * 6)
Question 192 print(x + 5)

Question:

Write a program to find the maximum of two numbers.

import itertools

for i in itertools.count(start=10, step=1):


Solution:
print(i) # Output:
def maximum(a, b):
if i > 15: 10

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

print(max(a, b)) from collections.abc import Iterator, Iterable

from types import GeneratorType

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:

Write a program to find the minimum of two numbers.

x = [11, 11, 12, 13, 15, 18, 19, 35, 64]

y = x[2:5]
Solution: print(y)

def minimum(a, b): # Output: [12, 13, 15]

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)

# Output: [12, 13, 15]

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:
B
Question:
break
C
Write a program to calculate Profit or Loss. print('')
A

Solution: x = [11, 12, 13, 14]

cp=float(input("Enter the Cost Price : ")); for i in x:


sp=float(input("Enter the Selling Price : "));
print(i)
if cp==sp:
print("No Profit or No Loss") if i == 12:
else:
x.remove(12)
if sp>cp:
print("Profit of ",sp-cp) print(x)
else:
# Output:
print("Loss of ",cp-sp)
11

12

Question 195 14

[11, 13, 14]


Question:

Write a program to find Student Grade.

845
Solution:

physics = float(input(" Please enter Physics Marks: "))


math = float(input(" Please enter Math score: "))
chemistry = float(input(" Please enter Chemistry Marks: "))

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)

if(percentage >= 90): x = myfunc()


print("A Grade") print(type(x))
elif(percentage >= 80):
# Output: <class 'generator'>
print("B Grade")
elif(percentage >= 70): print(next(x))

print("C Grade") # Output: 24


elif(percentage >= 60):
print(next(x))
print("D Grade")
# Output: 48
elif(percentage >= 40):
print("E Grade") print(next(x))
else:
# Output: 64
print("Fail")

x = 5

y = 100

print("X") if x > y else print("Y")

# Output: Y

846
Question 196 def myfunc():

yield 24
Question:
yield 48

Write a program to print Even numbers from 1 to N.


yield 64

x = myfunc()
Solution:
print(type(x))
x = int(input(" Enter the Value of N : "))
for i in x:

for num in range(1, x+1): print(i)


if(num % 2 == 0):
print("{0}".format(num))
# Output:

<class 'generator'>

24
Question 197
48

64
Question:

Write a program to print Odd numbers from 1 to N.

Solution:

x = int(input(" Enter the Value of N : "))

for num in range(1, x+1):


if(num % 2 != 0):
print("{0}".format(num))

847
Question 198

Question:

Write a program to compute sum of Even numbers from 1 to N.

def myfunc(name):

def x():
Solution: print(f"Albert {name}")

x = int(input(" Enter the Value of N : ")) return x

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

print("The Sum of Even Numbers from 1 to {0} is: {1}".format(num, total))

Question 199

Question:

Write a program to compute sum of Odd numbers from 1 to N.

Solution:

848
x = int(input(" Enter the Value of N : "))
total = 0

for num in range(1, x+1):


if(num % 2 != 0):
print("{0}".format(num))
total = total + num

print("The Sum of Odd Numbers from 1 to {0} is: {1}".format(num, total))

Question 200

Question:

Write a program to check whether a character is Alphabet or not.

Solution:

ch = input("Enter a Character : ")

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

if x > y and z > x:

print("Both conditions are satisfied")

# Output: Both conditions are satisfied

849
Question 201

Question:

Write a program to check whether a character is Alphabet or Digit or Special Character.

Solution:

ch = input("Enter a Character : ")

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")

# Output: Albert Einstein


Question 202

Question:

Write a program to check whether a character is Lowercase or not.

Solution:

ch = input("Enter a Character : ")

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:

Write a program to check whether a character is Uppercase or not.


x += 2

yield x

Solution:
x += 2

ch = input("Enter a Character : ") yield x

if(ch.isupper()):
for i in myfunc():
print(ch, "is a Uppercase character")
else: print(i)

print(ch, "is Not a Uppercase character")

# Output:

Question 204 2

Question: 6

Write a program to check whether a character is Vowel or Consonant.

851
Solution:

ch = input("Enter a Character : ")

if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or ch == 'A'


or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U'):
print(ch, "is a Vowel")
else:
def myfunc():
print(ch, "is a Consonant")
x = 1

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:

str = input("Enter a String : ") # Output:

1
string = str.upper()
2

print("String in Lowercase = ", str) 3


print("String in Uppercase = ", string) 4

852
Question 206
def myfunc():

Question: i = 0

Write a program to convert string to Lowercase. i += 2

return i

Solution:
print(myfunc())

str = input("Enter a String : ")


print(myfunc())

string = str.lower() print(myfunc())

print("String in Uppercase = ", str)


# Output:
print("String in Lowercase = ", string)
2

2
Question 207

Question:

Write a program to convert Decimal to Binary, octal, and Hexadecimal.

Solution:

decimal = int(input("Enter a Decimal Number: "))

binary = bin(decimal)

853
octal = oct(decimal)
hexadecimal = hex(decimal)

print(decimal, " Decimal Value = ", binary, "Binary Value")


print(decimal, " Decimal Value = ", octal, "Octal Value")
print(decimal, " Decimal Value = ", hexadecimal, "Hexadecimal Value")

Question 208

Question:

Write a program to check a Triangle is Valid or Not.

Solution:

a = int(input('Please Enter the First Angle of a Triangle: '))


b = int(input('Please Enter the Second Angle of a Triangle '))
c = int(input('Please Enter the Third Angle of a Triangle: '))

i = 0

total = a + b + c while True:

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:

age = int(input("What is your age? "))


print("In twenty years, you will be", age + 20, "years old!")

x = [11, 12, 13, 14]


Question 210
for i in x[:]:

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 212 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:

print("At least one of the conditions is satisfied")

# Output: At least one of the conditions is satisfied

x = 1

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)

# Output: [11 11 12 13 15 18 23 31 65]

product = mult print(x[4])

say(product(6, 6)) # Output: 15

print(x[2:5])
# Output: 36
# Output: [12 13 15]

import numpy as np

x = np.array([[2, 4 6], [8, 10, 12]])

y = np.array([[3, 6 12], [15, 18, 21]])

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]

[120 180 252]]

858
print(np.multiply(x, y))

# Output:

[[ 6 24 72]

[120 180 252]]

import numpy as np

x = np.array([True, True, False])

print(x.dtype)

# Output: bool

print(x)

# Output: [ True True False]

import numpy as np

x = np.array(['Albert', 'James', 'Mary', 'Einstein', 'Bob'])

print(x)

# Output: ['Albert' 'James' 'Mary' 'Einstein' 'Bob']

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

return 28
# Output: ['pqrs' ]

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

x = np.array(['Albert', 'James', 'Mary', 'Einstein', 'Bob'])

print( [(len(i), i) for i in x])

# Output: [(6, 'Albert'), (5, 'James'), (4, 'Mary'), (8, 'Einstein'), (3, 'Bob')]

import multiprocessing as mp

print(mp.cpu_count()) # Multiprocess CPU count

# Output: 4

860
x = complex(5, 6)

print(x) def f(x, y = []):

# Output: (5+6j) y.append(x)

return y
print(x.real)

# Output: 5.0
print(f(11))
print(x.imag)
print(f(12))
# Output: 6.0 print(f(13))

print((-1) ** 0.5)

# Output: (6.123233995736766e-17+1j)

print(complex(0, 1))

# Output: 1j

print(complex(0, 1) ** 2)

# Output: (-1+0j)

def f (x, y = None):

if y == None:
# Output:
y = []

y.append(x) [11]

return y
[12]

[13]
print(f(11))

print(f(12))

print(f(13))
I____________

861
x = 59

def f():

print(x)

f()

# Output: 59

import pandas

x = pandas.Series([11, 11, 12, 13, 15, 18]) # Output:

0 11
print(x)
1 11
----------------------------------------►
2 12
print(x.values)
3 13

# Output: [11 11 12 13 15 18] 4 15

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)

1
# Output: [11 12 13 14 15 16]

q = np.hstack([w, z])

print(q)

# Output: [11 12 13 14 15 16 17 18 19]

863
for i in [1, 2, 3]:
1
print(i)
Albert
print('Albert' * i)
2

AlbertAlbert

3
# Output:
AlbertAlbertAlbert

print(6, type(6))

# Output: 6 <class 'int'> a = 0

print(6.8, type(6.8)) b = 1

# Output: 6.8 <class 'float'> for i in [2, 4,8]:

print(-6.8, type(-6.8)) a = a + b*i

# Output: -6.8 <class 'float'> b =b + 1

print([], type([])) print(a)

# Output: [] <class 'list'> # Output: 34

print(False, type(False))

# Output: False <class 'bool'>

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

print(format(.1 + .2, '.20f'))

# Output: 0.30000000000000004441

print(format(.3, '.20f'))

# Output: 0.29999999999999998890

print('str: {}, int: {}, formatted float: {:.3f}.'.format('Bob', 53, 6.1687))


str: Bob, int: 53, formatted float: 6.169.

865
Best Linux Books that Every Superuser Should Read:

• How Linux Works: What Every Superuser Should Know

Book by Brian Ward

• The Linux Programming Interface

Book by Michael Kerrisk

• Linux pocket guide

Book by Daniel J. Barrett

• Linux for Beginners

Book by Jason Cannon

• How Linux Works: What Every Superuser Should Know

Book by Brian Ward

• Linux Kernel Development

Book by Robert Love

• Linux: The Complete Reference

Book by Richard Petersen

• Linux in a Nutshell

Book by Ellen Siever and Robert Love

• Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security

in Kali

Book by OccupyTheWeb
• Linux Command Line and Shell Scripting Bible

Book by Christine Bresnahan and Richard BLUM

• Linux Administration: The Linux Operating System and Command Line Guide for

Linux Administrators

Book by Jason Cannon

• The Art of Unix Programming

Book by Eric S. Raymond

• The Linux Command Line, 2nd Edition: A Complete Introduction

Book by William Shotts

• Linux Bible

Book by Christopher Negus

• Linux System Programming: Talking Directly to the Kernel and C Library

Book by Robert Love

• A Practical Guide to Linux Commands, Editors, and Shell Programming

Book by Mark G. Sobell

• Linux for Beginners and Command Line Kung Fu

Book by Jason Cannon

• Linux Device Drivers

Book by Alessandro Rubini, Greg Kroah-Hartman, and Jonathan Corbet

• Advanced Linux programming

Book by Alex Samuel, Jeffrey Oldham, and Mark Mitchell

• Understanding the Linux Kernel


Book by Daniel Pierre Bovet and Marco Cesati

• Learn Linux Quickly: A Beginner-friendly Guide to Getting Up and Running with

the World's Most Powerful Operating System

Book by Ahmed Alkabary

• Linux administration

Book by Wale Soyinka

• Linux For Dummies

Book by Richard Blum

• Linux Essentials

Book by Christine Bresnahan and Richard BLUM

• The Linux Command Line Beginner's Guide

Book by Jonathan Moeller

• Linux All-in-One for Dummies

Book by Emmett Dulaney

• Learning the bash Shell

Book by Cameron Newham

• Linux for Developers: Jumpstart Your Linux Programming Skills

Book by William "Bo" Rothwell

• Lfm: Linux Field Manual

Book by Tim Bryant

• CompTIA Linux+ Study Guide: Exam XK0-005

Book by Christine Bresnahan and Richard BLUM


• sed & awk

Book by Arnold Robbins and Dale Dougherty

• Linux From Scratch

Book by Gerard Beekmans

Linux is a complex example of the wisdom of crowds. It's a good

example in the sense that it shows you can set people to work in

a decentralized way - that is, without anyone really directing

their efforts in a particular direction - and still trust that they're

going to come up with good answers.

- James Surowiecki
Best Programming Books that Every Programmer Should Read:

C:

• The C Programming Language

Book by Brian Kernighan and Dennis Ritchie

• C Programming Absolute Beginner's Guide

Book by Dean Miller and Greg Perry

• Head First C

Book by David Griffiths and Dawn Griffiths

• Expert C Programming

Book by Peter van der Linden

• C Programming: A Modern Approach

Book by K. N King

• C: The complete reference

Book by Herbert Schildt

• Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep
Avoiding (Like C)

Book by Zed Shaw

• C in a Nutshell: The Definitive Reference

Book by Peter Prinz and Tony Crawford

• C Programming In Easy Steps

Book by Mike McGrath


• Computer Fundamentals and Programming in C

Book by Reema Thareja

• Hands-On Network Programming with C: Learn Socket Programming in C and Write


Secure and Optimized Network Code

Book by Lewis Van Winkle

• Let Us C

Book by Yashavant Kanetkar

• Low-Level Programming: C, Assembly, and Program Execution on Intel® 64 Architecture

Book by Igor Zhirkov

• Effective C: An Introduction to Professional C Programming

Book by Robert C. Seacord

• Data Structures Using C

Book by Reema Thareja

• A Book on C: Programming in C

Book by Al Kelley and Ira Pohl

• C Traps and Pitfalls

Book by Andrew Koenig

• C Interfaces and Implementations: Techniques for Creating Reusable Software

Book by David Hanson and David R. Hanson

• Mastering algorithms with C

Book by Kyle Loudon

• 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

Book by Yashavant Kanetkar

• Bare Metal C: Embedded Programming for the Real World

Book by Stephen Oualline

• Introduction to C Programming

Book by Reema Thareja

• C - In Depth

Book by Deepali Srivastava

• C How to Program

Book by Harvey Deitel and Paul Deitel

• The C answer book

Book by Clovis L. Tondo

• C Programming For Dummies

Book by Dan Gookin

• Understanding Pointers In C & C++: Fully Working Examples and Applications of Pointers

Book by Yashavant Kanetkar

C++:

• The C++ Programming Language

Book by Bjarne Stroustrup

• Effective Modern C++


Book by Scott Meyers

• C++ Primer

Book by Barbara E. Moo, Josee Lajoie, and Stanley B. Lippman

• A Tour of C++

Book by Bjarne Stroustrup

• Programming: Principles and Practice Using C++

Book by Bjarne Stroustrup

• C++ Concurrency in Action

Book by Anthony Williams

• Modern C++ Design

Book by Andrei Alexandrescu

• More Effective C++: 35 New Ways To Improve Your Programs And Designs

Book by Scott Meyers

• Accelerated C++: Practical Programming by Example

Book by Andrew Koenig and Barbara E. Moo

• C++ Templates: The Complete Guide

Book by David Vandevoorde, Douglas Gregor, and Nicolai M. Josuttis

• More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and


Solutions

Book by Herb Sutter

• C++ coding standards

Book by Andrei Alexandrescu and Herb Sutter


• C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and
Beyond

Book by Aleksey Gurtovoy and David Abrahams

• Beginning C++ Game Programming

Book by Michael Dawson

• Beginning C++ Programming

Book by Richard Grimes

• C++ Programming

Book by D. S. Malik

• Sams Teach Yourself C++ in One Hour a Day

Book by Rao Siddhartha

• Professional C++

Book by Nicholas A. Solter and Scott J. Kleper

• Starting Out with C++

Book by Tony Gaddis

• C++: The Complete Reference

Book by Herbert Schildt

• Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions

Book by Herb Sutter

• C++ High Performance: Master the Art of Optimizing the Functioning of Your C++ Code

Book by Bjorn Andrist and Viktor Sehr

• The C++ Standard Library: A Tutorial and Reference

Book by Nicolai M. Josuttis


• Effective C++ Digital Collection: 140 Ways to Improve Your Programming

Book by Scott Meyers

• C++17 - The Complete Guide

Book by Nicolai M. Josuttis

• C++ Primer Plus

Book by Stephen Prata

• Data Parallel C++: Mastering DPC++ for Programming of Heterogeneous Systems using

C++ and SYCL

Book by James Brodman, Michael Kinsner, Xinmin Tian, Ben Ashbaugh, John Pennycook,

James Reinders

• Data Structures Using C++

Book by Varsha H. Patil

• The Design and Evolution of C++

Book by Bjarne Stroustrup

• Modern CMake for C++: Discover a Better Approach to Building, Testing, and Packaging

Your Software

Book by Rafal Swidzinski

• Expert C++: Become a Proficient Programmer by Learning Coding Best Practices with

C++17 and C++20's Latest Features

Book by Shunguang Wu and Vardan Grigoryan

• Learn C++ Quickly: A Complete Beginner's Guide to Learning C++, Even If You're New to

Programming

Book by Code Quickly

• Memory Management Algorithms and Implementation in C/C++

Book by Bill Blunden


• Thinking in C++

Book by Bruce Eckel

• Modern C++ Programming Cookbook

Book by Marius Bancila

• Hands-On Design Patterns with C++: Solve Common C++ Problems with Modern Design

Patterns and Build Robust Applications

Book by Fedor G. Pikus

• A complete guide to programming in C++

Book by Ulla Kirch-Prinz

• C++ Crash Course: A Fast-Paced Introduction

Book by Josh Lospinoso

• C++ For Dummies

Book by Stephen Randy Davis

JAVA:

• Head First Java

Book by Bert Bates and Kathy Sierra

• Effective Java

Book by Joshua Bloch

• Thinking in Java
Book by Bruce Eckel

• Java Concurrency in Practice

Book by Brian Goetz

• Core Java

Book by Cay S. Horstmann and Gary Cornell

• Java: A Beginner's Guide

Book by Herbert Schildt

• Java: The Complete Reference

Book by Herbert Schildt

• Java 8 in Action: Lambdas, streams, and functional-style programming

Book by Alan Mycroft and Mario Fusco

• Beginning Programming With Java for Dummies

Book by Barry A. Burd

• Learn Java in One Day and Learn It Well

Book by Jamie Chan

• Modern Java in Action: Lambdas, Streams, Functional and Reactive Programming

Book by Alan Mycroft, Mario Fusco, and Raoul-Gabriel Urma

• Test Driven: Practical TDD and Acceptance TDD for Java Developers

Book by Lasse Koskela


• Java Puzzlers: Traps, Pitfalls, and Corner Cases

Book by Joshua Bloch and Neal Gafter

• Spring in Action

Book by Craig Walls and Ryan Breidenbach

• Java generics and collections

Book by Maurice Naftalin

• Core Java Volume I-Fundamentals

Book by Cay S. Horstmann

• Think Java: How to think like a computer scientist

Book by Allen B. Downey

• Java SE 8 for the Really Impatient

Book by Cay S. Horstmann

• Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D

Book by Brett McLaughlin

• Learning Java: An Introduction to Real-World Programming with Java

Book by Daniel Leuck, Marc Loy, and Patrick Niemeyer

• Core Java for the Impatient

Book by Cay S. Horstmann

• Java By Comparison: Become a Java Craftsman in 70 Examples

Book by Jorg Lenhard, Linus Dietz, and Simon Harrer


• High-Performance Java Persistence

Book by Vlad Mihalcea

• Java in a Nutshell: A Desktop Quick Reference

Book by Benjamin Evans and David Flanagan

• Spring Microservices in Action

Book by Edward John Carnell

• Optimizing Java: Practical Techniques for Improving JVM Application Performance

Book by Benjamin Evans, Chris Newland, and James Gough

• Java Performance: The Definitive Guide: Getting the Most Out of Your Code

Book by Scott Oaks

• Microservices Patterns: With Examples in Java

Book by Chris Richardson

• Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Book by Venkat Subramaniam

• Mastering Java Machine Learning

Book by Krishna Choppella and Uday Kamath

• OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808

Book by Jeanne Boyarsky and Scott Selikoff

• Let Us Java: Strong Foundation For Java Programming

Book by Yashavant Kanetkar


• Learn Java: A Crash Course Guide to Learn Java in 1 Week

Book by Timothy C. Needham

• Java Performance

Book by Binu John and Charlie Hunt

• The Java Language Specification

Book by Oracle Corporation

• Elements of Programming Interviews in Java: The Insider's Guide

Book by Adnan Aziz, Amit Prakash, and Tsung-Hsien Lee

PYTHON:

• Fluent Python

Book by Luciano Ramalho

• Learn Python the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful

World of Computers and Code

Book by Zed Shaw

• Python Cookbook: Recipes for Mastering Python 3

Book by Brian K. Jones and David M. Beazley

• Automate the Boring Stuff with Python: Practical Programming for Total Beginners

Book by Al Sweigart

• Python Crash Course: A Hands-On, Project-Based Introduction to Programming

Book by Eric Matthes

• Head First Python

Book by Paul Barry


• Programming Python

Book by Mark Lutz

• Think Python: An Introduction to Software Design

Book by Allen B. Downey

• Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython

Book by Wes McKinney

• Python Tricks: A Buffet of Awesome Python Features

Book by Dan Bader

• Learning Python

Book by Mark Lutz

• Introduction to Machine Learning with Python: A Guide for Data Scientists

Book by Andreas C. Muller and Sarah Guido

• Learning Python: Powerful Object-Oriented Programming

Book by Mark Lutz

• Python for Everybody: Exploring Data Using Python 3

Book by Charles Severance

• Python for Kids: A Playful Introduction To Programming

Book by Jason R. Briggs

• Python Programming: An Introduction to Computer Science

Book by John M. Zelle


• Learn Python in One Day and Learn It Well: Python for Beginners with Hands-on Project

Book by Jamie Chan

• Invent Your Own Computer Games with Python

Book by Al Sweigart

• Python Data Science Handbook: Essential Tools for Working with Data

Book by Jake VanderPlas

• Effective Python: 90 Specific Ways to Write Better Python

Book by Brett Slatkin

• Python Pocket Reference: Python In Your Pocket

Book by Mark Lutz

• Python 3 Object Oriented Programming

Book by Dusty Phillips

• How to think like a computer scientist: Learning with Python

Book by Allen B. Downey

• Python in a nutshell

Book by Alex Martelli

• Natural Language Processing with Python

Book by Edward Loper, Ewan Klein, and Steven Bird

• The Big Book of Small Python Projects: 81 Easy Practice Programs

Book by Al Sweigart
• Python Programming for the Absolute Beginner

Book by Michael Dawson

• Python Essential Reference

Book by David M. Beazley

• Deep Learning with Python

Book by Francois Chollet

• Dive into Python

Book by Mark Pilgrim

• Impractical Python: Projects Playful Programming Activities to Make You Smarter

Book by Lee Vaughan

• Object-Oriented Python: Master OOP by Building Games and GUIs

Book by Irv Kalb

• The Python Bible 7 in 1: Volumes One To Seven (Beginner, Intermediate, Data Science,

Machine Learning, Finance, Neural Networks, Computer Vision)

Book by Florian Dedov

• Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities

Book by Adrienne Tacke

• Learn More Python 3 the Hard Way: The Next Step for New Python Programmers

Book by Zed Shaw

• Artificial Intelligence with Python

Book by Prateek Joshi


• Python Programming: Using Problem Solving Approach

Book by Reema Thareja

• Django for Beginners: Build websites with Python and Django

Book by William S. Vincent

• Python for Dummies

Book by Aahz Maruch and Stef Maruch

• Beginning Programming with Python For Dummies

Book by John Paul Mueller

HTML:

• Learning Web Design

Book by Jennifer Niederst Robbins

• Head First HTML with CSS and XHTML

Book by Elisabeth Robson and Eric Freeman

• HTML5: The Missing Manual

Book by Matthew MacDonald

• Learn HTML for Beginners: The Illustrated Guide to Coding

Book by Jo Foster

• HTML5 for Web Designers

Book by Jeremy Keith

• HTML 4 for the World Wide Web

Book by Elizabeth Castro


• Introducing HTML5

Book by Bruce Lawson and Remy Sharp

• Core HTML5 Canvas: Graphics, Animation, and Game Development

Book by David M. Geary

• The Definitive Guide to HTML5

Book by Adam Freeman

• Html: Basic Fundamental Guide for Beginners

Textbook by M. G. Martin

• HTML5 in Easy Steps

Book by Mike McGrath

CSS:

• CSS Pocket Reference: Visual Presentation for the Web

Book by Eric A. Meyer

• CSS Secrets: Better Solutions to Everyday Web Design Problems

Book by Lea Verou

• CSS: The Missing Manual

Book by David McFarland

• CSS in Depth

Book by Keith Grant

• CSS mastery

Book by Andy Budd

• CSS: The Definitive Guide: Visual Presentation for the Web

Book by Eric A. Meyer and Estelle Weyl

• CSS Visual Dictionary


Book by Greg Sidelnikov

• Cascading Style Sheets: The Definitive Guide

Book by Eric A. Meyer

• The Book of CSS3: A Developer's Guide to the Future of Web Design

Book by Peter Gasston

• CSS3: The Missing Manual

Book by David Sawyer McFarland

• Learn CSS in One Day and Learn It Well: CSS for Beginners With Hands-On Project

Book by Jamie Chan

• CSS Master

Book by Tiffany A. Brown

• Basics of Web Design: HTML5 and CSS

Textbook by Terry A. Felke-Morris

• CSS for Babies

Book by John Vanden-Heuvel

• CSS in Easy Steps

Book by Mike McGrath

JAVASCRIPT:

• JavaScript: The Good Parts

Book by Douglas Crockford


• Eloquent JavaScript: A Modern Introduction to Programming

Book by Marijn Haverbeke

• JavaScript and JQuery: Interactive Front-End Web Development

Book by Jon Duckett

• You Don't Know JS: Scope and Closures

Book by Kyle Simpson

• A Smarter Way to Learn JavaScript

Book by Mark Myers

• Effective JavaScript : 68 specific ways to harness the power of JavaScript

Book by David Herman

• Head First JavaScript Programming: A Brain-Friendly Guide

Book by Elisabeth Robson and Eric Freeman

• JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language

Book by David Flanagan

• Learn JavaScript Visually: With Interactive Exercises

Book by Ivelin Demirov

• The Principles of Object-Oriented JavaScript

Book by Nicholas C. Zakas

• Professional JavaScript for Web Developers

Book by Nicholas C. Zakas


• Speaking JavaScript: An In-Depth Guide for Programmers

Book by Axel Rauschmayer

• Programming JavaScript Applications: Robust Web Architecture with Node, HTML5, and

Modern JS Libraries

Book by Eric Elliott

• JavaScript Enlightenment

Book by Cody Lindley

• Learning JavaScript Design Patterns

Book by Addy Osmani

• Secrets of the JavaScript Ninja

Book by Bear Bibeault, John Resig and Josip Maras

• Beginning JavaScript

Book by Jeremy McPeak and Paul Wilton

• JavaScript Patterns

Book by Stoyan Stefanov

• Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers

Book by Nicholas C. Zakas

• JavaScript for Kids: A Playful Introduction to Programming

Book by Nick Morgan

• High Performance JavaScript

Book by Nicholas C. Zakas

• Object-Oriented JavaScript

Book by Kumar Chetan Sharma and Stoyan Stefanov

• Maintainable JavaScript
Book by Nicholas C. Zakas

• Secrets of the JavaScript Ninja

Book by Bear Bibeault and John Resig

• Coding with JavaScript For Dummies

Book by Chris Minnick and Eva Holland

• DOM Enlightenment

Book by Cody Lindley

• JavaScript from Beginner to Professional: Learn JavaScript Quickly by Building Fun,

Interactive, and Dynamic Web Apps, Games, and Pages

Book by Laurence Lars Svekis and Rob Percival

• Testable JavaScript

Book by Mark Ethan Trostler

• You Don't Know JS: Up and Going

Book by Kyle Simpson

• JavaScript Allonge: A strong cup of functions, objects, combinators, and decorators

Book by Reginald Braithwaite

• You Don't Know JS Yet: Get Started

Book by Kyle Simpson

• JavaScript and JQuery: The Missing Manual

Book by David Sawyer McFarland


• The Recursive Book of Recursion: Ace the Coding Interview with Python and JavaScript

Book by Al Sweigart

• The Road to Learn React: Your Journey to Master Plain Yet Pragmatic React. Js

Book by Robin Wieruch

• Javascript In Easy Steps

Book by Mike McGrath

• Building JavaScript Games: For Phones, Tablets, and Desktop

Book by Arjan Egges

• High Performance Browser Networking

Book by Ilya Grigorik

• Learning TypeScript

Book by Josh Goldberg

• Pro JavaScript Techniques

Book by John Resig

• The Little Book on CoffeeScript

Book by Alex MacCaw

• Learning React: Functional Web Development with React and Redux

Book by Alex Banks and Eve Porcello

• Learn JavaScript Quickly: A Complete Beginner's Guide to Learning JavaScript, Even If

You're New to Programming


Book by Code Quickly

• Test-Driven JavaScript Development

Book by Christian Johansen

• Structure and Interpretation of Computer Programs, JavaScript Edition

Textbook by Gerald Jay Sussman and Hal Abelson

• Functional Programming in JavaScript: How to Improve Your JavaScript Programs Using

Functional Techniques

Book by Luis Atencio

• Pro JavaScript Design Patterns

Book by Dustin Diaz and Ross Harmes

• Java Script: The Complete Reference 2/E

Book by Thomas Powell

PHP:

• The Joy of PHP: A Beginner's Guide to Programming Interactive Web Applications with

PHP and MySQL

Book by Alan Forbes

• Learning PHP, MySQL, JavaScript, CSS and HTML5: A Step-by-Step Guide to Creating

Dynamic Websites

Book by Robin Nixon

• Programming PHP
Book by Rasmus Lerdorf

• PHP and MySQL Web Development

Book by Laura Thomson and Luke Welling

• Murach's PHP and MySQL

Book by Joel Murach and Ray Harris

• Head First PHP and MySQL

Book by Lynn Beighley and Michael Morrison

• PHP and MySQL: Novice to Ninja: Get Up to Speed With PHP the Easy Way

Book by Tom Butler and Kevin Yank

• PHP and MySQL: Server-side Web Development

Book by Jon Duckett

• Learning PHP, MySQL & JavaScript: With JQuery, CSS & HTML5

Book by Robin Nixon

• PHP and MySQL in easy steps, 2nd Edition: Updated to cover MySQL 8.0

Book by Mike McGrath

• PHP: A Beginner's Guide

Book by Vikram Vaswani

• Modern PHP: New Features and Good Practices

Book by Josh Lockhart

• Laravel: Up & Running: A Framework for Building Modern PHP Apps


Book by Matt Stauffer

• Mastering PHP 7

Book by Branko Ajzele

• PHP and MySQL

Book by Jon Duckett

• PHP and MySQL: The Missing Manual

Book by Brett McLaughlin

• PHP 8 Programming Tips, Tricks and Best Practices: A Practical Guide to PHP 8 Features,

Usage Changes, and Advanced Programming Techniques

Book by Cal Evans and Doug Bierer

• PHP for the Web: Visual QuickStart Guide

Book by Larry Ullman

• PHP and MySQL for Dynamic Web Sites

Book by Larry Ullman

• PHP: Learn PHP in One Day and Learn It Well. PHP for Beginners with Hands-on Project

Book by Jamie Chan

• PHP 7: Real World Application Development

Book by Altaf Hussain, Branko Ajzele and Doug Bierer

• PHP Cookbook

Book by Adam Trachtenberg and David Sklar


• Full Stack Web Development For Beginners: Learn Ecommerce Web Development Using

HTML5, CSS3, Bootstrap, JavaScript, MySQL, and PHP

Book by Riaz Ahmed

• Drupal 9 Module Development: Get Up and Running with Building Powerful Drupal

Modules and Applications

Book by Daniel Sipos

• Building Web Apps with WordPress: WordPress as an Application Framework

Book by Brian Messenlehner and Jason Coleman

• PHP and MySQL in easy steps

Book by Mike McGrath

• WordPress Complete

Book by Karol Krol

• PHP, MySQL, and JavaScript All-in-One For Dummies

Book by Richard BLUM

• PHP in Action: Objects, Design, Agility

Book by Chris Shiflett, Dagfinn Reiersol, and Marcus Baker

• PHP Advanced and Object-Oriented Programming: Visual QuickPro Guide

Book by Larry Ullman

• Learning PHP 7

Book by Antonio Lopez


• PHP 7 Programming Cookbook

Book by Doug Bierer

• PHP: The Complete Reference

Book by Steven Holzner

• PHP and MySQL for Dummies

Book by Janet Valade

• PHP Beginner's Practical Guide

Book by Pratiyush Guleria

• Building RESTful Web Services with PHP 7

Book by Haafiz Waheed-ud-din Ahmad

• Mastering PHP Design Patterns

Book by Junade Ali

• PHP and MongoDB Web Development Beginner's Guide

Book by Rubayeet Islam

• PHP 7 Data Structures and Algorithms

Book by Mizanur Rahman

• Mastering The Faster Web with PHP, MySQL, and JavaScript: Develop State-of-the-art

Web Applications Using the Latest Web Technologies

Textbook by Andrew Caya

• Learning PHP: A Gentle Introduction to the Web's Most Popular Language


Book by David Sklar

• Learn PHP 8: Using MySQL, JavaScript, CSS3, and HTML5

Book by Steve Prettyman

• PHP Microservices

Book by Carlos Perez Sanchez and Pablo Solar Vilarino

• Professional CodeIgniter

Book by Thomas Myer

• Symfony 5: The Fast Track

Book by Fabien Potencier

• Practical PHP and MySQL Website Databases: A Simplified Approach

Book by Adrian W. West

• PHP Programming for Beginners: Key Programming Concepts. How to use PHP with

MySQL and Oracle databases (MySqli, PDO)

Book by Sergey Skudaev

ALGORITHMS:

• Introduction to Algorithms

Book by T Cormen, C Leiserson, R Rivest, C Stein

• The Algorithm Design Manual

Book by Steven Skiena

• Grokking Algorithms: An Illustrated Guide for Programmers and Other Curious People
Book by Aditya Bhargava

• Algorithms

Book by Robert Sedgewick

• Algorithm Design

Book by Jon Kleinberg and Eva Tardos

• Algorithms Illuminated: Algorithms for NP-hard problems

Book by Tim Roughgarden

• Algorithms in a nutshell

Book by George T. Heineman

• Data structures and algorithms made easy in Java: data structure and algorithmic puzzles

Book by Narasimha karumanchi

• A Common-Sense Guide to Data Structures and Algorithms: Level Up Your Core

Programming Skills

Book by Jay Wengrow

• Cracking the Coding Interview

Book by Gayle Laakmann McDowell

• Guide to Competitive Programming: Learning and Improving Algorithms Through

Contests

Book by Antti Laaksonen

• Algorithms Unlocked

Book by Thomas H. Cormen

• Problem Solving with Algorithms and Data Structures using Python

Book by Bradley N Miller and David L. Ranum

• Computer Science Distilled: Learn the Art of Solving Computational Problems

Book by Wladston Ferreira Filho


• Python Algorithms: Mastering Basic Algorithms in the Python Language

Book by Magnus Lie Hetland

• Advanced Algorithms and Data Structures

Book by Marcello La Rocca

• The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake

Our World

Book by Pedro Domingos

• Dive Into Algorithms: A Pythonic Adventure for the Intrepid Beginner

Book by Bradford Tuckfield

• Advanced Data Structures

Book by Peter Brass

• Algorithmic Thinking: A Problem-Based Introduction

Book by Daniel Zingaro

• Algorithms + Data Structures = Programs

Book by Niklaus Wirth

• Algorithms Illuminated (Part 2): Graph Algorithms and Data Structures

Book by Tim Roughgarden

• Introduction to the Design and Analysis of Algorithms

Book by Anany Levitin

• Automate This: How Algorithms Came to Rule Our World

Book by Christopher Steiner

• Think Like a Programmer: An Introduction to Creative Problem Solving

Book by V. Anton Spraul

• Spies, Lies, and Algorithms: The History and Future of American Intelligence

Book by Amy Zegart


• Algorithms Illuminated (Part 3): Greedy Algorithms and Dynamic Programming

Book by Tim Roughgarden

• Algorithms for Decision Making

Book by Kyle H. Wray, Mykel J. Kochenderfer and Tim A. Wheeler

• Fundamentals of Computer Algorithms

Book by Ellis Horowitz and Sartaj Sahni

• Information Theory, Inference and Learning Algorithms

Book by David J. C. MacKay

• 9 Algorithms That Changed the Future

Book by John MacCormick

• The Art of Computer Programming

Book by Donald Knuth

• Data Structure and Algorithmic Thinking with Python

Book by Narasimha Karumanchi

• A Common-Sense Guide to Data Structures and Algorithms

Book by Jay Wengrow

• Hello World: How to be Human in the Age of the Machine

Book by Hannah Fry

• The Design and Analysis of Computer Algorithms

Book by Alfred Aho, Jeffrey Ullman, and John Hopcroft

• Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services

Book by Brendan Burns

• A Programmer's Guide to Computer Science: A virtual degree for the self-taught developer

Book by William M Springer

• Concrete Mathematics
Textbook by Donald Knuth, Oren Patashnik and Ronald Graham

• Understanding Cryptography: A Textbook for Students and Practitioners

Textbook by Christof Paar and Jan Pelzl

• Algorithms For Dummies

Book by John Mueller and Luca Massaron

DATA STRUCTURES:

• Data Structures and Algorithm Analysis in C++

Book by Clifford A Shaffer

• Purely functional data structures

Book by Chris Okasaki

• Open Data Structures: An Introduction

Book by Pat Morin

• Think Data Structures: Algorithms and Information Retrieval in Java

Book by Allen B. Downey

• Data Structures Using C

Book by Reema Thareja

• Data Structures Through C in Depth

Book by Deepali Srivastava and Suresh Kumar Srivastava

• C++ Plus Data Structures

Book by Nell B. Dale

• JavaScript Data Structures and Algorithms: An Introduction to Understanding and


Implementing Core Data Structure and Algorithm Fundamentals
Book by Sammie Bae

• Data structures using C and C++

Book by Yedidyah Langsam

• Algorithms and Data Structures: The Basic Toolbox

Book by Kurt Mehlhorn and Peter Sanders

• Data Structures and Algorithm Analysis in Java

Book by Clifford A Shaffer

• Handbook of Data Structures and Applications

Book by Dinesh P. Mehta and Sartaj Sahni

• Data structures with Java

Book by J. R Hubbard

• Java Structures

Book by Duane A. Bailey

LINUX:

• The Linux Command Line: A Complete Introduction

Book by William E. Shotts Jr. and William E. Shotts, Jr.

• The Linux Programming Interface

Book by Michael Kerrisk

• Linux bible

Book by Christopher Negus

• Linux pocket guide


Book by Daniel J. Barrett

• Linux for Beginners

Book by Jason Cannon

• How Linux Works: What Every Superuser Should Know

Book by Brian Ward

• Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali

Book by OccupyTheWeb

• Linux Kernel Development

Book by Robert Love

• Linux Administration: The Linux Operating System and Command Line Guide for Linux
Administrators

Book by Jason Cannon

• Linux: The Complete Reference

Book by Richard Petersen

• Linux Command Line and Shell Scripting Bible

Book by Christine Bresnahan and Richard BLUM

• Linux in a Nutshell

Book by Ellen Siever and Robert Love

• The Art of Unix Programming

Book by Eric S. Raymond

• Linux System Programming: Talking Directly to the Kernel and C Library

Book by Robert Love


• A Practical Guide to Linux Commands, Editors, and Shell Programming

Book by Mark G. Sobell

• Learn Linux Quickly: A Beginner-friendly Guide to Getting Up and Running with the
World's Most Powerful Operating System

Book by Ahmed Alkabary

• Linux for Beginners and Command Line Kung Fu

Book by Jason Cannon

• The Ultimate Kali Linux Book: Perform Advanced Penetration Testing Using Nmap,
Metasploit, Aircrack-Ng, and Empire

Book by Glen D. Singh

• Understanding the Linux Kernel

Book by Daniel Pierre Bovet and Marco Cesati

• Linux for Developers: Jumpstart Your Linux Programming Skills

Book by William "Bo" Rothwell

• Learning the bash Shell

Book by Cameron Newham

• Linux Device Drivers

Book by Alessandro Rubini, Greg Kroah-Hartman, and Jonathan Corbet

• Mastering Linux Shell Scripting: A Practical Guide to Linux Command-line, Bash


Scripting, and Shell Programming

Book by Andrew Mallett and Mokhtar Ebrahim

• Efficient Linux at the Command Line

Book by Daniel J. Barrett


• Shell Scripting: How to Automate Command Line Tasks Using Bash Scripting and Shell

Programming

Book by Jaosn Cannon

• Advanced Programming in the Unix Environment

Book by W. Richard Stevens

• Lfm: Linux Field Manual

Book by Tim Bryant

• CompTIA Linux+ Certification All-in-One Exam Guide

Book by Ted Jordan and Sandor Strohmayer

• Advanced Linux programming

Book by Alex Samuel, Jeffrey Oldham and Mark Mitchell

• Linux Kernel in a Nutshell

Book by Greg Kroah-Hartman

• Linux Kernel Debugging: Leverage Proven Tools and Advanced Techniques to Effectively

Debug Linux Kernels and Kernel Modules

Book by Kaiwan N Billimoria

• Bash cookbook

Book by Carl Albing

• Linux for Beginners: A Practical and Comprehensive Guide to Learn Linux Operating

System and Master Linux Command Line.

Book by Ethem Mining

• Beginning Linux Programming

Book by Mathew Neil and Richard Stones

• The Linux Command Line Beginner's Guide

Book by Jonathan Moeller


• Linux System Programming

Book by Robert Love

• A Practical Guide to Fedora and Red Hat Enterprise Linux

Book by Mark G. Sobell

• Kali Linux Hacking: A Complete Step by Step Guide to Learn the Fundamentals of Cyber

Security, Hacking, and Penetration Testing

Book by Ethem Mining

• Kali Linux Revealed: Mastering the Penetration Testing Distribution

Book by Jim O'Gorman, Mati Aharoni and Raphael Hertzog

• Linux in Easy Steps

Book by Mike McGrath

• Bash Pocket Reference: Help for Power Users and Sys Admins

Book by Arnold Robbins

• Learn PowerShell in a Month of Lunches: Covers Windows, Linux, and macOS

Book by Travis Plunk, James Petty and Leon Leonhardt

• Linux From Scratch

Book by Gerard Beekmans

• Linux For Dummies

Book by Richard Blum

DATABASE:

• Database Systems: The Complete Book

Book by Hector Garda-Molina, Jeffrey Ullman and Jennifer Widom

• Fundamentals of Database Systems


Book by Ramez Elmasri

• Database Design for Mere Mortals

Book by Michael J. Hernandez

• An Introduction to Database Systems

Book by Christopher J. Date

• SQL Antipatterns: Avoiding the Pitfalls of Database Programming

Book by Bill Karwin

• Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and

Maintainable Systems

Book by Martin Kleppmann

• Database System Concepts

Book by Avi Silberschatz, Henry F. Korth and S. Sudarshan

• Database Internals: A Deep Dive Into How Distributed Data Systems Work

Book by Alex Petrov

• Beginning Database Design Solutions

Book by Rod Stephens

• SQL Performance Explained

Book by Markus Winand

• Database Management Systems

Book by Johannes Gehrke and Raghu Ramakrishnan

• Oracle PL/SQL programming

Book by Scott Urman

• Database in Depth: Relational Theory for Practitioners

Book by Christopher J. Date

• Database Design and Relational Theory: Normal Forms and All That Jazz
Book by Christopher J. Date

• Database Systems: A Practical Approach to Design, Implementation, and Management

Book by Carolyn Begg and Thomas M. Connolly

• Introductory Relational Database Design for Business, with Microsoft Access

Book by Bonnie R. Schultz and Jonathan Eckstein

• Head First SQL: Your Brain on SQL - A Learner's Guide

Book by Lynn Beighley

• Readings in Database Systems

Book by Joseph M Hellerstein

• The art of SQL

Book by Stephane Faroult

• The theory of relational databases

Book by David Maier

• The Data Warehouse Toolkit

Book by Ralph Kimball

• MongoDB: The Definitive Guide

Book by Kristina Chodorow and Michael Dirolf

• Learning SQL

Book by Alan Beaulieu

• Joe Celko's SQL puzzles and answers

Book by Joe Celko

• Foundations of databases

Book by Serge Abiteboul

• Pro SQL Server Relational Database Design and Implementation: Best Practices for

Scalability and Performance


Book by Louis Davidson

• Six-Step Relational Database Design: A Step by Step Approach to Relational Database

Design and Development

Book by Fidel A. Captain

• Databases, Types and the Relational Model: The Third Manifesto

Book by Christopher J. Date

• Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement

Book by Eric Redmond and Jim R. Wilson

• Practical SQL: A Beginner's Guide to Storytelling with Data

Book by Anthony DeBarros

• Refactoring databases

Book by Scott Ambler

• SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and

Manipulating Data With SQL

Book by Walter Shields

• PHP and MySQL: Server-side Web Development

Book by Jon Duckett

• SQL Cookbook

Book by Anthony Molinaro

• Learn MongoDB 4.x: A Guide to Understanding MongoDB Development and

Administration for NoSQL Developers

Book by Doug Bierer

• Professional Azure SQL Managed Database Administration: Efficiently Manage and

Modernize Data in the Cloud Using Azure SQL

Book by Ahmad Osama and Shashikant Shakya


• PostgreSQL: Up and Running

Book by Leo S. Hsu and Regina O. Obe

• SQL All-in-One for Dummies

Book by Allen G. Taylor

• An Introduction to Relational Database Theory

Book by Hugh Darwen

• Transaction Processing: Concepts and Techniques

Book by Jim Gray

• Making Sense of NoSQL: A Guide for Managers and the Rest of Us

Book by Ann Kelly, Ann Marie Kelly and Dan McCreary

• A Practical Guide to Database Design

Book by Rex Hogan

• Database Development for Dummies

Book by Allen G. Taylor

• SQL Queries for Mere Mortals: A Hands-on Guide to Data Manipulation in SQL

Book by John Viescas and Michael J. Hernandez

• Pro SQL Server 2012 Relational Database Design and Implementation

Book by Jessica Moss and Louis Davidson

• SQL Performance Explained: Everything Developers Need to Know about SQL

Performance

Book by Markus Winand

• Refactoring Databases: Evolutionary Database Design

Book by Scott W Ambler and Pramod J Sadalage

• Designing Data-Intensive Applications

Book by Martin Kleppmann


Programming today is a race between software engineers striving to

build bigger and better idiot-proof programs, and the Universe trying to

produce bigger and better idiots. So far, the Universe is winning.

— Rick Cook, The Wizardry Compiled


"In some ways, programming is like painting. You start with a blank

canvas and certain basic raw materials. You use a combination of

science, art, and craft to determine what to do with them."

- 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.

Coding is both a science and creative art to me. It is both incredibly


fun and fascinating. I want to spread my passion to as many
individuals as I can. I also hope that this is not the end of your
learning.

Thank you!
AN APPROACHABLE MANUAL FOR NEW AND EXPERIENCED
PROGRAMMERS THAT INTRODUCES THE PROGRAMMING LANGUAGES C,
C++, JAVA, AND PYTHON. THIS BOOK IS FOR ALL PROGRAMMERS,
WHETHER YOU ARE A NOVICE OR AN EXPERIENCED PRO. IT IS DESIGNED
FOR AN INTRODUCTORY COURSE THAT PROVIDES BEGINNING
ENGINEERING AND COMPUTER SCIENCE STUDENTS WITH A SOLID
FOUNDATION IN THE FUNDAMENTAL CONCEPTS OF COMPUTER
PROGRAMMING. IT ALSO OFFERS VALUABLE PERSPECTIVES ON
IMPORTANT COMPUTING CONCEPTS THROUGH THE DEVELOPMENT OF
PROGRAMMING AND PROBLEM-SOLVING SKILLS USING THE LANGUAGES
C, C ++, JAVA, AND PYTHON. THE BEGINNER WILL FIND ITS CAREFULLY
PACED EXERCISES ESPECIALLY HELPFUL. OF COURSE, THOSE WHO ARE
ALREADY FAMILIAR WITH PROGRAMMING ARE LIKELY TO DERIVE MORE
BENEFITS FROM THIS BOOK. AFTER READING THIS BOOK YOU WILL FIND
YOURSELF AT A MODERATE LEVEL OF EXPERTISE IN C, C + + , JAVA AND
PYTHON, FROM WHICH YOU CAN TAKE YOURSELF TO THE NEXT LEVELS.
THE COMMAND-LINE INTERFACE IS ONE OF THE NEARLY ALL WELL
BUILT TRADEMARKS OF LINUX. THERE EXISTS AN OCEAN OF LINUX
COMMANDS, PERMITTING YOU TO DO NEARLY EVERYTHING YOU CAN
BE UNDER THE IMPRESSION OF DOING ON YOUR LINUX OPERATING
SYSTEM. HOWEVER, THIS, AT THE END OF TIME, CREATES A PROBLEM:
BECAUSE OF ALL OF SO COPIOUS COMMANDS ACCESSIBLE TO MANAGE,
YOU DON'T COMPREHEND WHERE AND AT WHICH POINT TO FLY AND
LEARN THEM, ESPECIALLY WHEN YOU ARE A LEARNER. IF YOU ARE
FACING THIS PROBLEM, AND ARE PEERING FOR A PAINLESS METHOD TO
BEGIN YOUR COMMAND LINE JOURNEY IN LINUX, YOU'VE COME TO THE
RIGHT PLACE-AS IN THIS BOOK, WE WILL LAUNCH YOU TO A HOLD OF
WELL LIKED AND HELPFUL LINUX COMMANDS. THIS BOOK GIVES A
THOROUGH INTRODUCTION TO THE C, C ++, JAVA, AND PYTHON
PROGRAMMING LANGUAGES, COVERING EVERYTHING FROM LINUX COMMANDS, C, C++,
FUNDAMENTALS TO ADVANCED CONCEPTS. IT ALSO INCLUDES VARIOUS JAVA AND PYTHON EXERCISES

EXERCISES THAT LET YOU PUT WHAT YOU LEARN TO USE IN THE REAL FOR BEGINNERS

WORLD.

MANJUNATH.R

You might also like