Manjunath R. Linux Commands, C, C++, Java and Python Exercises For Beginners 2022
Manjunath R. Linux Commands, C, C++, Java and Python Exercises For Beginners 2022
- Socrates
Manjunath.R
*Email: manjunath5496@gmail.com
Disclaimer
Despite my best efforts to assure the accuracy of the material in this book, I do not accept
and hereby disclaim any liability to any party for any loss, damage, or disruption caused by
mistakes or omissions, whether caused by negligence, accident, or any other cause.
As long as you comply by the conditions of the license, the licensor cannot revoke these rights.
You have to
I dedicate this book to every individual, programmer, teacher, educational institutions and
enterprise corporations in every country of the world for their immense contributions towards the
process of creating, designing, deploying and supporting software...
Acknowledgements
Without the amazing work of some renowned programmers, their creativity, and their inventiveness in the
field of software programming, this book would not have been accomplished. I would like to use this
opportunity to thank my dearest friend and well-wisher "Lawrence" for his unwavering support during
the COVID crisis and for giving me access to all the resources I needed to finish this book. I want to
express my gratitude to my family for their support and encouragement as I wrote this book, especially to
my mother, who has been a tremendous source of inspiration in my life. I owe a lot of gratitude to my
mother for teaching me how to be perseverant and strong in life. Finally, I want to emphasize how crucial
patience is when writing a book or taking on any other project in life.
Foreword
I'm neither the proprietor of a well-known publishing house or a top IT firm with hundreds of in
house programmers who could easily produce anything I needed. I am a self-employed software
engineer who is passionate about what I do, and believe me when I say that a lot of work and
effort went into compiling this comprehensive edition. I'll be overjoyed if it helps even a few
others reach their ideal positions in their professions.
Thank You
- Manjunath.R
An Enjoyable Introduction to Coding
Introduction
Today's devices are mostly powered by software: almost everyone uses Facebook,
WhatsApp and Twitter to communicate, many phones have internet-connected desktops, and the
majority of office work requires using a computer to do tasks. As a response, there is a huge
increase in demand for programmers. Numerous books, interactive websites, and programmer
training courses make the bold claim that they can turn ambitious novices into software
engineers earning six figures. This book is for all programmers, whether you are a novice or an
experienced pro. Its numerous examples and well paced discussions will be especially beneficial
for beginners. Those who are already experienced with programming will probably gain more
from this book, of course. You will be at a modest level of programming proficiency when you
have finished this book, from where you can take yourself to next levels so that you can
automate simple tasks such as:
This book will make an amazing complement to any tutorial and serve as a source of information
to your specific inquiries if you are just learning what kind of animals C, C+ +, Java, PHP,
Python, and JavaScript are. Even if your career has nothing to do with computers, the skills you
learn from programming can be valuable at school and at work. Programming is a pleasant,
occasionally difficult and perhaps frustrating activity. Creativity, logic, and problem-solving are
all enhanced through programming.
As you progress through this book, keep in mind that programming can be enjoyable. Do not
consider of this as work. Consider programming as a means to develop entertaining games or
software applications that you can show off to others or your friends. Programming is a
tremendous brain workout and is essential today because so much of our everyday world is
automated. But above all, you have access to the quick-paced, creative world that depends on
machine connections.
"The only way to learn a new programming language is by writing programs in it."
- Dennis Ritchie
Note:
1. Always be aware of the purpose of your software program before beginning to write it.
2. Programming is not the solution; it is merely a means to achieve a solution.
3. Consider the problem rather than just the solution.
4. Always try to make things simpler; anyone can come up with a complicated answer to a
problem. To make a solution simple while remaining consistent, it requires extra work
and consideration.
5. Reduce Deeply Nested Ifs or Loops: When your software program is deeply nested, your
program becomes complicated and disorganized.
6. Delete Unnecessary Code. Make sure your software program is safe, secure, reliable,
testable and clear to read.
7. Give code reviews some attention so you can spot bugs early, before they cause serious
problems in your software application.
8. Reduce complexity. Software programs must have clear explanations.
9. Generalize your software program. Make sure your software program is documented.
Understanding the function of a certain component of the software application is greatly
aided by the documentation and comments.
10. Fancy algorithms and data structures are more difficult to implement. Use simple,
efficient, appropriate algorithms and data structures.
11. Refractor your software program frequently to improve its internal software attributes in
terms of upkeep, testing and comprehension.
12. Each time you make a change to your software program: check it, build it and test it.
13. Before being released, all software codes must pass each and every unit test.
14. Always use caution when using someone else's code. Maintain a standardized, orderly
and generally consistent coding style.
15. Avoid implementing a code style that is too hard to understand.
16. Because it makes the code more difficult to maintain, duplication is seen adversely in
software programming.
17. Look for bugs and flaws and fix them. Divide your software program into Brief, Concise
Units.
18. Avoid overdesigning. Focus your software design on the requirements of the clients.
19. Program defensively. Functions should be simple and do a distinct, defined task.
20. Create reusable functions and Keep the functions as simple, immutable and manageable
as possible.
21. When naming your variables and functions, choose names that are meaningful and
descriptive.
22. Put your software program's structure on view by using indentation.
23. Delete any unused variables and functions; do not comment them.
24. If you feel that a part of the software program is excessively unorganized, regroup and
modify it, or even split it up into different portions.
25. Avoid using GOTO statements because they cause the software program to be
unstructured, which makes it harder to understand and makes debugging more complex.
26. Avoid using the same identifier more than once.
27. The length of functions shouldn't be excessively long.
28. Think Twice, Code Once: Encourage yourself to consider the problem more before
coming up with a solution.
29. The very first step in making a software program readable by humans is to add
comments. Comments should be detailed explanations of a software program.
30. White space should be utilized regularly to increase code readability even though it has
little significance to compilers.
31. Coding standards must be followed while formatting code.
32. Avoid security pitfalls and Keep your software code portable.
33. All software design is redesign. Take advice from others' experience.
34. The writing of software program should make it simple for a future software developer
to correct errors or modify its functionality.
35. Never compromise clarity for a false sense of efficiency.
"More computing sins are committed in the name of efficiency (without necessarily
achieving it) than for any other single reason - including blind stupidity."
- W.A. Wulf
36. Enhance the appearance of software program by avoiding excessively long names or
ambiguous acronyms
37. Look for a method that employs a loop rather than duplicating lines. Compared to 100
individual blocks of code, one loop that can handle 100 repetitions is simpler to debug.
You're not coding to amaze strangers. You're in this
profession to find ways to resolve problems.
"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
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
— Alan J. Perlis
LINUX COMMANDS
Linux is an open-source Unix-like operating system built on the Linux kernel, which Linus
Torvalds initially made available on September 17, 1991. People switching from Windows or
macOS may find Linux difficult to use and comprehend, and many people give up using it
because they are not aware of the commands and shortcuts that Linux offers. When using Linux,
you can accomplish tasks much more quickly than when using other operating systems by
becoming familiar with the useful commands and how to use them correctly. We'll examine a
few widely used Linux commands in this chapter.
When working with unstructured files in Linux, whether you are a sys admin or a database
administrator, there are a number of commands that will be very helpful to you in your everyday
job. Working as developers requires us to use the Linux command line occasionally. Linux is
typically considered to be dominant for public Internet servers, powering well over twice as
many servers as Windows Server. Linux has a monopoly on the supercomputer market,
powering all 500 of the TOP computers. It's quite easy to customize Linux. Your OS can be
modified. In this chapter, we'll look at some fundamental Linux commands that every
programmer should be familiar with.
1
17 Principles of the philosophy of UNIX
2
• Principle of Least Surprise: Developers should be encouraged to create user-friendly,
intuitive products
• Principle of Silence: Allow programmers and other programs to get the data they require
from a program's output without having to interpret unnecessary extensive and detailed
• Principle of Repair: Programmers should create software that fails in a way that is simple
to identify and diagnose
• Principle of Economy: Project development costs should be minimized
• Principle of Generation: Programmers should develop abstract, high-level programs that
produce code rather than writing code by hand to decrease human error and save time
• Principle of Optimization: Before you can optimize it, get it working. Software should
be developed and tested before being masterfully crafted by developers
• Principle of Diversity: Make programs flexible, enabling their use in ways other than
those that their creators intended
• Principle of Extensibility: Increase the usefulness and lifespan of the developer's written
code
3
Better skills come with increased learning.
Your main focus as a novice should be on becoming familiar with the ins and outs of
operating system architecture as well as discovering shortcuts and time-saving techniques.
4
CentOs is a wonderful option if you use Windows and want to learn Linux because it is one
of the best Linux distributions for beginners. Your first few days using CentOs won't be that
odd. But you must learn how to utilize Linux's command line interface if you want to
experience its full capabilities. You will initially experience some difficulty learning several
instructions. Although employing the instructions won't make you a genius, it will assist you in
carrying out certain fundamental tasks. Here are the most basic CentOs commands for new
users to ensure a smooth start. Let's get right into it!
5
"... being a Linux user is sort of like living in a
house inhabited by a large family of carpenters
and architects. Every morning when you wake
up, the house is a little different. Maybe there
is a new turret, or some walls have moved. Or
perhaps someone has temporarily removed the
floor under your bed."
Linux Commands
Description:
Command:
date
Description:
Display calendar.
Command:
cal
6
Description:
Command:
Description:
Command:
cal 8 2016
Description:
Command:
clear
Description:
Command:
exit
7
Description:
Command:
free
Description:
Command:
free -b
Description:
Command:
free -k
Description:
Command:
8
free -m
Description:
Command:
passwd
Description:
Command:
shutdown
Description:
Command:
shutdown -h now
Description:
9
Command:
shutdown -h +10
Description:
Command:
echo $PWD
Description:
Command:
echo $OLDPWD
Description:
Command:
!11
10
Description:
Command:
history
Description:
Command:
sudo reboot
Description:
Command:
ip address
Description:
Command:
Is -s
11
Description:
Command:
mount
Description:
Command:
du
Description:
Command:
uptime
Description:
Command:
12
date --set 1998-11-02
Description:
Command:
Description:
Command:
fdisk -l /dev/sda
Description:
Command:
Is
Description:
13
Command:
ps
Description:
Command:
df
Description:
Command:
df -H
Description:
Command:
rm -r *
14
Description:
Command:
top
Description:
Command:
reboot
Description:
Command:
kill
Description:
Command:
cd
15
Description:
Command:
login
Description:
Command:
Isof
Description:
Command:
Isusb
Description:
Command:
16
service network status
Description:
Command:
Description:
Command:
Description:
Command:
Description:
Report information about the users currently on the machine and their processes.
17
Command:
Description:
Command:
pwd
Description:
Displays CPU architecture information (such as number of CPUs, threads, cores, sockets, and
more).
Command:
Iscpu
Description:
Command:
nproc
18
Description:
Command:
init 6
Description:
Command:
init 0
Description:
Command:
Is -Irt
Description:
Report information about storage devices such as hard disks, flash drives etc.
Command:
lsblk
19
Description:
Command:
echo $?
Description:
Command:
info
Description:
Command:
cal -y
Description:
Command:
20
service --status-all
Description:
Command:
date +%T
Description:
Tells when the user last logged on and off and from where.
Command:
last -1 username
Description:
Command:
Is -X
Description:
21
Command:
man pwd
Description:
Command:
pstree
Description:
Command:
reset
Description:
Command:
date -d fri
22
Description:
Command:
du -a
Description:
Command:
acpi
Description:
Command:
cd ../..
Description:
Command:
cd -
23
Description:
Command:
help
Description:
Command:
last yourusername
Description:
Command:
mkdir myfiles
Description:
Command:
24
rmdir myfiles
Description:
Command:
passwd -d rootl
Description:
Command:
sudo su rootl
Description:
Command:
logout
Description:
25
Command:
useradd "rootl"
Description:
Command:
passwd "rootl"
Description:
Command:
Description:
Command:
whoami
26
Description:
Command:
logname
Description:
Command:
uname
Description:
Command:
uname -v
Description:
Command:
uname -o
27
Description:
Command:
uname -m
Description:
Command:
uname --version
Description:
Command:
uname -r
Description:
Command:
28
uname -n
Description:
Command:
netstat -a
Description:
Command:
netstat -at
Description:
Command:
netstat -au
Description:
29
Command:
netstat -I
Description:
Command:
netstat -It
Description:
Command:
netstat -lu
Description:
Reveal all the information about the current user (user id, username, group id, group name etc.).
Command:
id
30
Description:
Reveal all the information about the user "root1" (user id, username, group id, group name etc.).
Command:
id rootl
Description:
Command:
arch
Description:
Command:
fc-list
Description:
Command:
31
Description:
Command:
Description:
Command:
Description:
Command:
Description:
Command:
32
apt update httpd
Description:
Command:
Description:
Command:
Description:
Command:
date --help
Description:
33
Command:
ss -tup
Description:
Command:
ss -tupl
Description:
Command:
netstat -lx
Description:
Command:
ifconfig
34
Description:
Command:
ifconfig -a
Description:
Command:
Description:
Tells you how many lines, words, and characters there are in a file (1.txt).
Command:
wc 1.txt
Description:
Command:
gzip 1.txt
35
Description:
Command:
gunzip 1.txt
Description:
Command:
cat 1.txt
Description:
Display calendar.
Command:
ncal
Description:
Command:
36
rm 1.txt
Description:
Command:
mv 1.txt 0.txt
Description:
Command:
cp 1.txt 0.txt
Description:
Command:
touch test.txt
Description:
37
Command:
tail 1.txt
Description:
Command:
tail -n N 1.txt
Description:
Command:
wc -w 1.txt
Description:
Command:
wc -m 1.txt
38
Description:
Command:
wc -L 1.txt
Description:
Print information about usb ports, graphics cards, network adapters etc.
Command:
Ispci
Description:
Command:
less 1.txt
Description:
Command:
cal -3
39
Description:
Compare the contents of three files (1.txt, 2.txt, 3.txt) line by line.
Command:
Description:
Command:
Description:
Command:
Description:
Prints the CRC checksum and byte count for the file "myfiles.txt".
Command:
40
cksum myfiles.txt
Description:
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt).
41
Command:
Shortcuts:
Description:
Writes contents of a file (0.txt) to output, and prepends each line with line number.
Command:
nl 0.txt
Description:
Command:
mkdir test
cd test
pwd
touch test1.txt
42
Description:
Gather information about hardware components such as CPU, disks, memory, USB controllers
etc.
Command:
sudo Ishw
Description:
Command:
sudo fdisk -l
Description:
Displays the line (good morning) in which the string (good) is found in the file (1.txt).
Command:
Description:
Append contents of files (1.txt, 2.txt, 3.txt) into one file (0.txt) using for loop.
43
Command:
Description:
Search for files (test.txt, test1.txt, test2.txt, test.php, test.html) in a directory as well as its sub
directories.
Command:
find test*
Description:
Command:
stat 1.txt
###
| Command 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:
Command:
hostid
Description:
Command:
file myfiles.txt
Description:
Command:
45
Description:
Command:
Description:
Command:
hostname -i
Description:
Command:
Description:
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:
Command:
whereis cal
48
cd /etc && Is
/bin/bash
49
/home/manju/.bash history Holds the name and location
of your Bash history file
50
echo $HISTFILESIZE
1000
filel.txt
filel.txt
filel.txt
file1.txt
file23.txt file34.txt
51
[manju@localhost ~]$ Is test[5A].txt
testA.txt
testA.txt
file23.txt file34.txt
*
List all .txt files starting with a
[manju@localhost ~]$ ls [a-z]*[0-9].txt letter and ending in a number
52
Is ?????
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"
Einstein36
Hilbert3 6
Lucy6 Lucy8
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
root:x:0:0:root:/root:/bin/bash
# List of all filenames in /etc that contain the string "conf" in their filename
54
90% of the public cloud workload is run on Linux distros.
import os
os.system('ls')
current directory
subprocess.call ('ls')
55
Command:
last reboot
Description:
Command:
dmesg
Description:
Displays the messages from the kernel ring buffer (a data structure that records
messages related to the operation of the kernel)
Command:
cat /proc/cpuinfo
Description:
56
Command:
cat /proc/meminfo
Description:
Command:
Ispci -tv
Description:
Command:
Isusb -tv
Description:
57
Command:
free -h
Description:
Display free and used memory (-h for human readable, -m for MB, -g for GB)
Command:
mpstat 1
Description:
Command:
vmstat 1
Description:
58
Display virtual memory statistics
Command:
iostat 1
Description:
Command:
watch df -h
Description:
Command:
ps -ef
Description:
59
Display all the currently running processes on the system
Command:
ip a
Description:
Command:
dig wikipedia.org
Description:
Command:
host wikipedia.org
Description:
60
Display the IP address details of the specified domain (wikipedia.org)
Command:
netstat -nutlp
Description:
Display listening Transmission Control Protocol (TCP) and the User Datagram
Protocol (UDP) ports and corresponding programs
Command:
rpm -qa
Description:
Command:
Description:
Command:
61
yum info httpd
Description:
Command:
du -ah
Description:
Display disk usage for all files and directories in human readable format
Command:
du -sh
Description:
Command:
62
cd /etc
Description:
Command:
ps -A
Description:
List the status of all the processes along with process id and PID
Command:
#include <stdio.h>
int main()
{
printf("Hello world\n"); Hello.c
return 0;
gcc Hello.c
63
Description:
Command:
Description:
Command:
tty
Description:
64
Command:
}
}
javac MyClass.java
Description:
Compile the Java program saved in MyClass.java file using javac compiler
Command:
od -b myfiles.txt
Description:
Command:
od -c myfiles.txt
65
Description:
Command:
od -An -c myfiles.txt
Description:
Displays the contents of myfiles.txt file in character format but with no offset
information
Command:
Description:
If the file myfiles.txt has 123 lines, the csplit command would create four files: the xx00 file
would contain lines 1-12, the xx01 file would contain lines 13-61, the xx02 file would contain
Command:
66
md5sum myfiles.txt
Description:
Prints a 32-character (128-bit) checksum of myfiles.txt file using the MD5 algorithm
Command:
more myfiles.txt
Description:
Command:
shalsum myfiles.txt
Description:
Command:
67
shred myfiles.txt
Description:
Overwrites the myfiles.txt file repeatedly - in order to make it harder for even very
expensive hardware probing to recover the data
Command:
cat myfile.txt
01. Einstein
02. Newton
03. Maxwell
04. Tesla
05. Edison
tac myfile.txt
05. Edison
04. Tesla
03. Maxwell
02. Newton
01. Einstein
Description:
68
Command:
uniq myfiles.txt
Description:
Command:
chkconfig --list
Description:
Displays a list of system services and whether they are started (on) or stopped
(off) in run levels 0-6
Command:
halt -p
Command:
Description:
xdg-open myfiles.txt
69
Command:
lastlog
Description:
Prints the details of the last login (login-name, port and last login time)
Command:
lastlog -t 1
Description:
Command:
lastlog -u manju
Description:
70
Command:
cat /etc/passwd
more /etc/passwd
less /etc/passwd
getent passwd
Description:
Command:
tail -5 /etc/passwd
head -5 /etc/passwd
71
Description:
Command:
Description:
Command:
chage -l manju
Description:
List the password and its related details for a user (manju)
72
Command:
chage -M 10 manju
Description:
Command:
Description:
Command:
chage -I 10 manju
Description:
73
cat /etc/hostname
^ localhost.localdomain
hostname
^ localhost.localdomain
nmtui
yum check-update
# Check whether any updates are available for your installed packages
ls /etc
ls /bin /sbin
ls -al ~
ls -lh /boot
74
mkdir ~/mydir
rm -i file.txt
If we type "yes"
file.txt is removed
If we type "no"
ls
ls
75
Command:
ftp 192.168.42.77
Description:
Command:
arp -a
Description:
Lists all the peers connected at various interfaces along with their MAC
Command:
dnsdomainname
Description:
76
Display the system's DNS domain name
Command:
domainname
Description:
Command:
Output: SGVsbG8gV29ybGQhCg==
Description:
Command:
Description:
77
Decode (SGVsbG8gV29ybGQhCg==) to text (Hello World!)
Command:
fc-cache -f -v
Description:
Command:
cat 1.txt
Einstein
Newton
Albert
fmt 1.txt
Description:
78
df -h | sort -rnk 5 | head -3 | \
awk '{ print "Partition " $6 "\t: " $5 " full!" }'
Is *.xml
1.xml 2.xml
1. xml
2 . xml
[manju@localhost ~]$
12.txt 2.xml.md Documents file34.txt Music Pictures tree.cpio
79
[manju@localhost ~]$ df -h /
Check the actual
Filesystem Size Used Avail Use% Mounted on
used space on the
/dev/sda3 18G 5.2G 13G 29% / current root device
less /proc/modules
totals in megabytes
Mon Jul 18 23:17:47 PDT 2022 Print the date 3 months and 1 day ago from the current date
Fri Apr 22 23:20:01 PDT 2022 Print the date 3 days in the future from now
Hello World
Aello World
80
[manju@localhost ~]$ fgrep 'He' myfiles.txt
Hello World
Look for the string "He" in the file "myfiles.txt"
Command:
lsattr
Description:
Command:
cp {*.txt,*.md} ~
Description:
Copy the files ending with .txt or .md to the user's home directory
Hello World
Hello World
Is file*
Is *file
81
cat phy.txt
fmt -w 1 phy.txt
Albert
Einstein
was
a
German-born
theoretical
physicist,
widely
acknowledged
to
be
one
of
the
greatest
physicists
of
all
time.
Einstein
is
known
for
developing
82
the
theory
of
relativity,
but
he
also
made
important
contributions
to
the
development
of
the
theory
of
quantum
mechanics.
cat phy.txt
fold -w 20 phy.txt
83
a German-born theor
etical physicist, wi
dely acknowledged to
be one of the great
est physicists of al
l time. Einstein is
known for developing
the theory of relat
ivity, but he also m
ade important contri
butions to the devel
opment of the theory
of quantum mechanic
s.
Command:
traceroute google.com
Description:
Prints the route that a packet takes to reach the Google (172.217.26.206) host
from the local machine
Command:
cat 1.txt
84
Einstein
Newton
Albert
gzip 1.txt
zcat l.txt.gz
Einstein
Newton
Albert
Description:
Command:
Description:
85
Command:
ss | less
Description:
Command:
ss -aA tcp
Description:
Command:
ss -aA udp
Description:
86
Command:
ss -Int
Description:
Command:
ss -Itp
Description:
Command:
ss -s
Description:
87
Command:
ss -tl6
Description:
Command:
ss -tl -f inet
Description:
Command:
Description:
88
Command:
pmap 3244
Description:
Command:
Description:
Command:
apropos editor
Description:
Display information about the editing programs that are available on a system
89
Command:
apropos pstree
Description:
Provide information about the pstree command (which displays the names of the
processes currently on the system in the form of a tree diagram)
The apropos command is useful when you know what you want to do, but you have no idea what command
you should be using to do it. If you were wondering how to locate files, for example, the commands
apropos find
and
apropos locate
basename /etc/passwd
Output: passwd
basename /usr/local/apache2/conf/httpd.conf
90
Output: httpd.conf
echo a b c d e f| xargs
Output: a b c d e f
echo a b c d e f| xargs -n 3
a b c
d e f
Command:
env
Description:
Command:
91
printenv HOME
Description:
cat score.txt
Albert-30
John-50
William-80
Stephen-20
Justin-40
30
50
80
20
40
Albert
John
William
Stephen
Justin
92
cat 1.txt
Hello World
cat 2.txt
Computer Program
cat 1.txt
Hello World
cat 2.txt
Computer Program
93
Command:
rev 1.txt
Description:
cat 3.txt
22
33
11
77
55
sort 3.txt
11
22 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
Command:
ls -l *.txt
Description:
The thing with Linux is that the developers themselves are actually customers too: that has
always been an important part of Linux.
Linus Torvalds
96
Is /proc/bus/
[ 2.269581] ata1: PATA max UDMA/33 cmd 0x1f0 ctl 0x3f6 bmdma 0x1060 irq 14
[ 2.269585] ata2: PATA max UDMA/33 cmd 0x170 ctl 0x376 bmdma 0x1068 irq 15
cat /proc/ioports
cat 1.txt
[manju@localhost home]$Becho $
Albert
himBH
cat 2.txt
Einstein
7 8 90abcdefgh
/home/manj u
/home
97
[manju@localhost home]$ w | cut -d -f 1 | grep -v USER | sort -u
Einstein
25
[manju@localhost ~]$ Is
98
Is -Idh * | grep -v total | \
awk '{ print "Size is " $5 " bytes for " $9 }
99
Linux Unix
Source code is accessible to the general public Source code is not accessible to anyone
Uses Graphical User Interface with an optional Uses Command Line Interface
Command Line Interface
Command:
echo $SHELL
Description:
Command:
echo $0
Description:
Display the name of the currently running process ($0 is the name of the running process).
If you 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:
Command:
ps -p $$
Output:
Description:
Print the process ID of the current shell ($$ is the process ID of the current shell)
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:
102
bzip2 -k phy.txt
Description:
phy.txt ^ phy.txt.bz2
Command:
bzip2 -d phy.txt.bz2
Description:
phy.txt.bz2 ^ phy.txt
Command:
bzcat phy.txt.bz2
103
Description:
Command:
bunzip2 phy.txt.bz2
Description:
Command:
crontab -l
Description:
104
cp /dev/null phy.txt
Description:
Command:
Description:
Command:
105
nohup ping google.com > log.txt &
Description:
pgrep -a ping
Output:
kill 3858
pgrep -a ping
Output:
Command:
ls -la /home
106
Description:
Command:
sudo shutdown 2
Description:
Command:
shutdown -c
Description:
Command:
pr 36.txt
107
Description:
Display the contents of the file (36.txt) one page after the other
Command:
stty -a
Description:
Command:
Is -1
Description:
Command:
108
yes John
Description:
Command:
vdir
Description:
List files and directories in the current directory (one per line) with details
Command:
who -b
Description:
109
Command:
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:
Command:
uname -p
Description:
Command:
cat /proc/interrupts
Description:
w --ip-addr
110
# Displays information regarding the users currently on the machine, login time, IDLE time,
TTY and CPU time
Output:
w -short
# Omits CPU time and login information
Output:
Command:
findmnt
Description:
Command:
111
ip addr show
Description:
Command:
netstat -pnltu
Description:
Command:
journalctl
Description:
Command:
112
sudo systemctl status network
Description:
Command:
Description:
Command:
Description:
Command:
113
sestatus -b
Description:
Command:
getenforce
Description:
Security-Enhanced Linux (SELinux) is a security architecture for Linux systems that allows
administrators to have more control over who can access the system
setenforce 0
114
getenforce
Output:
Permissive
setenforce 1
getenforce
Output:
Enforcing
115
[manju@localhost ~]$ let a="36 + 5" ; echo $a
41
25
15
100
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
PASS _MIN_DAYS 0
PASS _MIN_LEN 5
PASS _WARN_AGE 7
116
Command:
Description:
Command:
Description:
Command:
Description:
117
Command:
sestatus
Description:
Display the current status of the SELinux that is running on your system
Command:
ps -aef
Description:
Command:
sar
Description:
118
Display System Activity Report
Command:
ulimit
Description:
Output:
Unlimited The current user can consume all the resources the current system supports
• Hard resource limit: The physical limit that the user can reach.
• Soft resource limit: The limit that is manageable by the user (its value can go up to the
hard limit)
Command:
119
ulimit -a
Description:
Command:
ulimit -s
Description:
Command:
ulimit -e
Description:
120
Command:
ulimit -u
Description:
Command:
ulimit -v
Description:
Command:
ulimit -n
Description:
121
Command:
man limits.conf
Description:
Command:
sar -V
Description:
Command:
sar -u 2 5
Description:
122
Command:
Description:
Report about network interface, network speed, IPV4, TCPV4, ICMPV4 network traffic and errors
Command:
sar -v 1 3
Description:
Report details about the process, kernel thread, i-node, and the file tables
Command:
sar -S 1 3
Description:
123
Command
sar -b 1 3
Description
Report details about I/O operations like transaction per second, read per second, write per second
Command
Description
Command:
Description:
124
firewalld is a firewall management tool for Linux operating systems
Command:
firewall-config
Description:
firewall-cmd
Command:
firewall-cmd --list-all-zones
Description:
Command:
125
firewall-cmd --get-default-zone
Description:
Command:
firewall-cmd --list-services
Description:
Command:
firewall-cmd --list-ports
Description:
Command:
126
firewall-cmd --zone=work --list-services
Description:
Command:
Description:
Provides information about the route that Internet traffic takes between the local
system and a remote host (google.com)
Command:
Description:
127
Samba is client/server technology that implements network resource sharing across
operating systems. With Samba, files and printers can be shared across Windows,
Mac and Linux/UNIX clients.
Command:
Description:
Command:
Description:
Command:
128
unzip q.zip
Description:
zipcloak q.zip
# zipcloak prompts you for a password, and then ask you to confirm it:
Enter password:
Verify password:
unzip q.zip
# When you try to unzip the q.zip file, it prompts you for the password before
allowing you to extract the file (q.txt) it contains
129
Command:
zgrep -l "Einstein" *
Description:
Display the names of the files with the word (Einstein) present in it
Command:
Description:
Split q.zip file to create a sequence of zipfiles (q1 .zip, q2.zip.... ) - each no larger
than 1048576 bytes (one megabyte)
You could concatenate (q1.zip, q2.zip.. ) into a new file, w.zip, with the
command:
130
Command:
mtr google.com
Description:
Test the route and connection quality of traffic to the destination host google.com
Command:
route
Description:
Command:
131
Description:
Command:
Description:
Command:
ss -ta
Description:
Command:
132
ss -to
Description:
Command:
type -a alias
Description:
# Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year.
# Difference between %B and %b is, %B will print full month name while %b will print abbreviated month
name.
133
echo "We are in the month = $(date +%B)"
# Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday
name.
134
echo "tomorrow = $(date -d "tomorrow")"
# Find what is the date and time before 10 days from now.
echo "Before 10 days = $(date -d "tomorrow -10 days")"
Command:
ls -lai /
Description:
Command:
sudo du --inode /
Description:
135
Get the total number of inodes in the root directory
Command:
Description:
Get the list of all clients connected to HTTP (Port 80) or HTTPS (Port 443)
Command:
Description:
Command:
Description:
136
Install PuTTy on CentOS
Command:
Description:
Command:
Description:
Command:
137
Description:
Command:
Description:
Command:
ss -ua
Description:
Command:
138
ss -lu
Description:
Command:
ss -p
Description:
Command:
ss -4
Description:
139
Command:
ss -6
Description:
Command:
Description:
- Dennis Ritchie
140
[manju@localhost ~]$ echo {a..z}
a b c d e f g h ij k l mn o p q r s t u v w x y z
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 {05..12} 005 006 007 008 009 010
05 06 07 08 09 10 11 12
mkdir 20{09..11}-{01..12}
12 11 10 9 8 7 6 5
12 11 10 09 08 07 06 05
x1 x2 x3 y1 y2 y3 z1 z2 z3
0 2 4 6 8 10
afkpuz
141
[manju@localhost ~]$ Is *.txt; echo $_
Albert,Bob
Bob
Bob,John
W X Y Z
W X Y Z
142
[manju@localhost ~]$ let x=20+7; echo "The value of \"x\" is $x."
x = 101
25 # 5 * 5
readelf -h /bin/bash
143
[manju@localhost ~]$ echo -e "\033[4mAlbert Einstein.\033[0m"
Albert Einstein.
Albert Einstein.
Albert Einstein
Albert Einstein
Albert Einstein
13
13
5 5
144
Command:
Description:
Command:
history -c
Description:
Command
ping -c 5 www.google.com
Description:
145
# count number of lines in each .txt file
Is *.txt | xargs wc -l
Is *.txt | xargs wc -w
Is *.txt | xargs wc -c
Is *.txt | xargs wc
Command:
Islogins -u
Description:
146
Command:
Description:
List all loaded services on your system (whether active; running, exited or failed)
Command:
systemctl --type=service
Description:
List all loaded services on your system (whether active; running, exited or failed)
Command:
147
Description:
Command:
Description:
Command:
Description:
List all running services (i.e., all loaded and actively running services)
Command:
148
systemctl --type=service --state=running
Description:
List all running services (i.e., all loaded and actively running services)
nc -v -w 2 z 192.168.56.1 22
nc -v -w 2 z 192.168.56.1 22 80
nc -v -w 2 z 192.168.56.1 20-25
Command:
cat /etc/resolv.conf
Description:
149
Command:
less /etc/resolv.conf
Description:
Command:
Description:
Monitor mount, unmount, remount and move actions on a directory (i.e., on /mnt/test)
Command:
uptime -p
Description:
150
Command:
uptime —s
Description:
Command:
uptime -h
Description:
Command:
Description:
151
Command:
crontab -r
Description:
ADD=$(( 1 + 2 ))
echo $ADD
3
MUL=$(( $ADD * 5 ))
echo $MUL
15
SUB=$(( $MUL - 5 ))
echo $SUB
10
DIV=$(( $SUB / 2 ))
echo $DIV
5
MOD=$(( $DIV % 2 ))
echo $MOD
152
Command:
Description:
echo '3+5' | bc
8
(a + b) = 8
Command:
factor 10
Description:
153
Command:
ps -e
Description:
Command:
ps -x
Description:
Command:
ps -fU manju
Description:
154
Display a user's processes by user name (manju)
Command:
ps -fu 1000
Description:
Command:
ps -U root -u root
Description:
Display every process running with root user privileges (real and effective ID)
155
date +%d\-%m\-%Y
date +%m\/%d\/%Y
ls -a ~/
2350
10
23500 x — = 2350
shuf -i 1-5 -n 5
156
[manju@localhost ~]$ shuf -i 1-5 -n 5 | awk '{ sum+=$1;print $1} END {print "Sum";print sum}'
Sum
15
./1.zip
Find File with .zip extension
./—encrypt.zip
./my.zip
157
find -type f -newermt 2021-03-01
Shell Scripting
if [ 15 -gt 25 ]
then
else False
echo "False"
fi
for i in 1 2 3 4 5 # Output:
do Albert
done Albert
Albert
158
if test 5 -eq 6
then
False
else
echo "False"
fi
help cd
159
help -s cd
Create the myfiles directory, and set its file mode (-m) so that
all users (a) may read (r), write (w), and execute (x) it.
whatis -w make*
who -d -H
finger -s manju
last -F
# Search for all .mp3 and .txt files on your system and ignore case
160
systemctl -l -t service | less
locate "*.txt" -n 20
locate -c [.txt]*
ls -l . | egrep -c 'A-'
# Check the top 10 files that are eating out your space
161
mpstat
mpstat -P ALL
mpstat 1 5 ---------- 1
Albert Einstein
fdisk -s /dev/sda
162
Command:
Description:
Command:
locale
Description:
Command:
locale -a
Description:
163
Display a list of all available locales
cat score.txt
Justin-40
JUSTIN-40
JUSTIN-40
cat domainnames.txt
164
cat domainnames.txt
www.google.....com
www.fb.com
www.mactech.Com
My UID is 0
My
UID
is
0
myw3schools.com:=>Linux-Books,Src,Tutorials
Command:
165
!sud
Description:
Command:
!sudo
Description:
Command:
Description:
166
Generate a compact list of all Linux user accounts on the system
Command:
Description:
Command:
Description:
Command:
167
find . -type f -perm 0777 -print
Description:
Command:
Description:
Command:
Description:
Command:
168
find / -perm /u=r
Description:
Command:
Description:
albert
Convert text from upper case to lower case
Command:
169
find . -type f -name "phy.txt" -exec rm -f {} \;
Description:
Description:
Command:
Description:
170
To find and remove multiple .mp3 files
Command
Description:
Command:
Description:
Phone number:
Remove all digits from string
Command:
171
find / -mtime 50
Description:
Command:
find / -atime 50
Description:
Command:
Description:
172
Find Changed Files in Last 1 Hour
Command:
Description:
Command:
Description:
Command:
type cat
Description:
Command: Identifies whether the "cat" command is a shell built-in command, subroutine, alias, or keyword.
173
find / -size 50M
Description:
Command:
Description:
Command:
Description:
Find all .mp3 files with more than 10MB and delete them
174
Is -l --color
info df
ls /usr/include
ls /usr/local
ls /usr/bin/d*
# List all files whose names begin with the letter "d" in the /usr/bin directory
hello.cpp hello.f99
175
Is /usr
Is ~ /usr
176
Command:
cat /proc/sys/fs/file-max
Description:
Command:
ulimit -Hn
Description:
Command:
ulimit -Sn
Description:
177
Command:
timedatectl status
Description:
Command:
timedatectl list-timezones
Description:
Command:
178
Description:
Command:
Description:
Command:
swapon --summary
Description:
Command:
179
cat /proc/swaps
Description:
exit
Command:
dir -shl
Description:
180
List files and their allocated sizes in blocks
Command:
less /proc/sys/dev/cdrom/info
Description:
cat date.txt
"Don't write better error messages, write code that doesn't need them."
- Jason C. McDonald
181
[manju@localhost ~]$ echo hello > 1.txt
hello
world
program
hello
world
program
hello
world
program
strings /usr/bin/passwd
Is -IrS /etc
182
cat /etc/passwd >> myfiles.txt
# Create a file named myfiles.txt that contains the contents of myfiles.txt followed by the contents of /etc/passwd
/etc/ipsec.conf /etc/pnm2ppa.conf
ls /dev/sd*
183
echo \$USER
# $USER
2 +2 =4
echo Hello && echo World
12 + 12 =24
Hello
World
echo Hello ; echo World
Hello
World
Hello
World
It worked!
It failed!
pwd ; pwd
/home/manj u
184
a=$(pwd)
echo "Current working directory is : $a"
/home/manju
Command:
echo *.jpeg
Description:
Command:
Description:
185
l
n
u
x
Command:
Description:
Output the files with respect of the user (root) owned files in the current directory
Command:
strace pwd
Description:
186
Command:
top -u manju
Description:
187
[manju@localhost ~]$ cat myfiles.txt
Hello World
Hello
World
# Find files that end in .txt in the current directory and all subdirectories
Tuesday 19-04-2022
# Print the number of .txt files in /etc and all its subdirectories
Hello World
Hello World
Hello World
188
[manju@localhost ~]$ echo Albert Einstein | sed 's/Albert/&&/'
AlbertAlbert Einstein
Albert EinsteinEinstein
Albertert
Albert Albert
Albert is Scientist
Albert is Scientist
Hello World
HeAo World
189
[manju@localhost ~]$ cat myfiles.txt
Hello World
HeAo World
0
True: 50 is greater than 15
1
False: 5 is not greater than 15
0
True: 5 is lesser than 15
true
false
190
[manju@localhost ~]$ [ 50 -gt 15 ] && echo true || echo false
true
false
[manju@localhost ~]$ [ 100 -gt 10 -a 100 -It 150 ] && echo true || echo false
true
[manju@localhost ~]$ [ 100 -gt 10 -a 100 -lt 15 ] && echo true || echo false
false
191
Command:
uname -or
Description:
Command:
uname -a
Description:
Command:
cat /proc/version
Description:
Display some of your system information including the Linux kernel version
192
Command:
cat /etc/centos-release
Description:
Command:
fuser .
Description:
Displays the PIDs of processes currently accessing your current working directory
Command:
193
fuser -v -m .bashrc
Description:
Command:
Description:
Displays all the possible signals that can be used with the fuser tool
Command:
Description:
Sends the HUP signal to all processes that have your /boot directory open
194
Command:
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:
■
echo "updatedb" | at -m 23.55
195
Command:
Description:
Execute command "ls -al" and print the result to the standard output
Command:
Description:
Command:
Description:
196
Command:
Description:
Command:
Description:
Find all files in the current directory with .sh and .txt file extensions
Command:
Description:
Find all files in the current directory with .sh, .c and .txt file extensions
197
Description:
Command:
Description:
Command:
Description:
Find files that have more than 100 characters (bytes) in them.
Command:
198
Description:
Command:
Description:
Command:
Description:
Command:
199
Is -a
Description:
Command:
Is -F
Description:
Command:
Is -r
Description:
200
Command:
Is -IS
Description
Command:
Is -i
Description:
Command:
Is --version
Description:
201
Command:
Is -l /tmp
Description:
Command:
Is -n
Description
Command:
202
Description:
Command:
Description:
Command:
Description:
Command:
203
Description:
Command:
Description:
Command:
Description:
List all files modified between 6 and 15 days ago in the home directory.
Command:
204
find /home -type f -mtime +6 -mtime -15
Description:
Command:
Description:
Command:
Description:
205
Command:
Description:
Find and list files and directories together with their permissions.
Command:
Description:
Command:
Is -d */
Description:
206
Command:
Is --format=comma
Description:
Command:
ps -u manju
Description:
Command:
207
Description:
Command:
dmidecode -t 0
Description:
Command:
dmidecode -t 4
Description:
Command:
gnome-system-log
208
Description:
Command:
ssh -V
Description:
Command:
ac -d
Description:
Command:
209
ac -p
Description:
Command:
ac -d manju
Description:
Command:
httpd -l
Description:
210
Command:
ps U $USER
Description:
Command:
df -Tha
Description:
Command:
netstat -tap
Description:
211
Command:
212
[manju@localhost ~]$ PS1="Please enter a command: "
April 2022
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
213
[manju@localhost ~]$ Is /etc/gdm List the contents of GDM configuration directory
Is /etc/gconf
ls /usr/share/gnome
ls /etc/rc.d
214
Important features of Linux Operating System
Linux Kernel
Manage access and use of the various peripherals that are connected to the computer.
215
[manju@localhost ~]$ cd /etc
/ etc
[manju@localhost etc] $ cat /etc/hosts /etc/hosts contains hostnames with their ip address
216
ps -L 3315
[manju@localhost ~]$ awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }'
24 _______________________ _____________________________ 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
Cron Anacron
A service that enables us to run scheduled jobs A service that only enables us to run scheduled jobs
in Linux/Unix systems every minute. in Linux/Unix systems on daily basis.
Command:
cat /etc/crontab
Description:
Command:
netstat --listen
218
Description:
y ▼
A mirror copy of the original file A symbolic link to the original file
219
Is /bin
Is /boot
Is /dev
# List the device files - typically controlled by the operating system and the system administrators
ls /etc
ls /lib
ls /lib64
ls /proc
ls /sbin
ls /var/log
220
[manju@localhost ~]$ Is -l myfiles.txt
# Display files that are more than 1 day old - but less than 3 days old in the current directory
# Find files that start with the letter "s"and perform the command "ls" on them
ffff
[manju@localhost ~]$Btouch file1; touch file2
eee
file1 file2
cc
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:
Description:
Remove read write and execute permissions on the file "myfiles.txt" for the group and others
Command:
Description:
Command:
-3
Description:
linux-gnu
The current operating system you are using
222
Command:
df -i /dev/sdal
Description:
Command:
Is -il myfiles.txt
Description:
Command:
getfacl myfiles.txt
Description:
SSH (Secure Shell or Secure Socket Shell) is a network protocol that gives users and
system administrators a secure way to access a computer over an unsecured network.
223
3 standard streams in Linux:
Text terminal
Standard input
(stdin)
Keyboard Program
Standard output
(stdout)
Display
Standard error
(stderr)
Command:
du -sh /var/log/*
Description:
Command
Idd /bin/cp
224
Description:
Command:
Idd -v /bin/cp
Description:
Command:
Idd -u /bin/cp
Description:
225
[manju@localhost ~]$ date; cal
April 2022
Su Mo Tu We Th Fr Sa
date command is executed
1 2 followed by a cal command
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
April 2022
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
226
[manju@localhost ~]$ a='ls *.c'; echo $a
true
true
true
true
true
[manju@localhost ~]$ test 320 -eq 30 && echo true | | echo false
false
false
[manju@localhost ~]$ test 320 -ne 30 && echo true | | echo false
true
227
Command:
cat /proc/net/dev
Description:
Command:
cat /proc/mounts
Description:
Command:
telinit 0
Description:
cd /home
cd ..
228
iconv -l
Is -iSr | more
Command:
ls -lh
Description:
Display permissions
Command:
yum list
Description:
Command:
Description:
229
Command:
Description:
Command:
Description:
Command:
Description:
Clean Metadata
ip link show
ps -eafw
lsof -p $$
230
Command:
Description:
Find files in the /var directory that have not been accessed in the last 90 days
Command:
Description:
Search for core files in the entire directory tree and delete them as found without
prompting for confirmation
Command:
who -r
Description:
231
Bash script:
Description:
Delete all the files in the current directory that contains the word "linux"
Command:
Description:
sleep 5s
sleep 5h
sleep 5d
232
Command:
In myfiles.txt hardFl
Description:
Command:
cat hardFl
Description:
Command:
In myfiles.txt softFl
Description:
Command:
cat softFl
Description:
233
Foreground processes Background processes
Require a user to start them or to interact Run independently of a user.
with them.
Command:
ps -p 13
Description:
Command:
ulimit -f 100
Description:
Command:
Ismod
Description:
234
Find out what kernel modules are currently loaded
The path of a file or directory from the The path of a file or directory from the
root directory. present working directory.
Command:
Description:
Command:
Description:
Run a PHP statement from the command line without creating a file
Command:
php -a
Description:
235
Command:
du -h -d 1 /
Description:
Command:
Description:
Command:
man -f Is
Description:
man -a Is
man -k ls
# Allows users to search the short command descriptions and manual page names for ls command
man -w ls
236
cat /etc/redhat-release
Is ~
ls ../
Command:
ps -U root -u root
Description:
Command:
cal -1
Description:
Command:
cal -j
Description:
237
Command:
su
Description:
Command:
Description:
Command:
Description:
ps r
ps T
ps -f
# List processes along with the parent process ID associated with the current Terminal
238
ps -x
Command:
Description:
Command:
Description:
239
Command:
Description:
Command:
Description:
Command:
Description:
Command:
file /etc/passwd
Description:
240
Command:
wc /etc/passwd
Output:
46 91 2373 /etc/passwd
The /etc/passwd file has 46 lines, 91 words and 2373 letters present in it
Command:
Description:
Command:
Description:
Display all lines from /etc/passwd containing the string "root" with line numbers
Command:
Description:
241
Command:
Description:
Display all lines from /etc/passwd starting with the string "root" followed by colon
Command:
last | head
Description:
Displays information about the users who logged in and out of the system
lastb
du /etc/passwd
killall proc
wget https://repo.mysql.com/mysql80-community-release-el8-1.noarch.rpm
242
sudo yum localinstall https://repo.mysql.com/mysql80-community-release-el7-1.noarch.rpm
curl --version
curl -O http://website.com/myfiles.tar.gz
# Saved as myfiles.tar.gz
# Saved as files.tar.gz
exit 110
sudo -l
# know which commands are permitted and not permitted on the current host
243
Command:
echo -e "\thello\nworld"
hello
world
• Difficulty to use
Disadvantages of Open Source Operating System:
• Compatibility Issues
Command:
Description:
Command:
Description:
Find files in the /home directory which were modified more than 120 days ago
244
Samba enables Linux / UNIX machines to communicate with
date "+%s'
245
Command
cd ../../
Command:
Description:
List all the processes on the system containing the string 'xlogo'
abcdef
246
Command:
Description:
List the files in /var larger than 1 megabyte but less than 1 gigabyte
Command:
Is -IhS
Description:
# Searches for all files in the /tmp directory named *.txt and deletes them
use of Linux
247
watch -n 5 tail -n 3 /etc/passwd
watch -t -n 1 date
# Search for files containing the string "hello computer" in the current directory
248
Command:
free -t -m
Command:
gnome-system-monitor
Description:
Displays what programs are running and how much processor time, memory and disk space are being used
lsblk -m
lsblk -S
249
Command:
Is -l ~
Description:
Command:
Is ./Documents
Description:
Is -R
compgen -c
# Displays the list of all commands which we can use in the command-line interface
hostnamectl
# Display system information including operating system, kernel and release version
250
Command:
find . -type f
Find files
Command:
find . -type d
Description:
Find directories
251
{ echo "Albert Einstein"; pwd; uptime; date; }
1 Albert Einstein
/ home / manj u
shutdown -r
shutdown +0
shutdown -r +5
252
Command:
kill 12838
ss -t -r state established
Force the file system check during
Description: reboot
ss -t -r state listening
253
ls -al --time-style =+%D | grep 'date +%D'
mpstat -P 0
# Print processor statistics and helps to monitor CPU utilization on the system
# Assign full permission to the owner and read and write permission to group and others
chmod -x myfiles.txt
history 30
find ~ -empty
gzip -l *.gz
254
Command:
ps -efH | more
Command:
df -t
Description:
mkdir ~/temp
Is *py
chsh -l
ipcs -a
255
ipcs -q
Lists only message queues for which the current process has read access
ipcs -s
ipcs -m
quotastats
# Display the report of quota system statistics gathered from the kernel
rpcinfo
# Display all of the RPC (Remote Procedure Call) services of the local host
slabtop
tload
# Display a graph of the current system load average to the specified tty
256
cat /proc/devices
# Display the device drivers configured for the currently running kernel
cat /proc/dma
cat /proc/filesystems
cat /proc/kmsg
cat /proc/loadavg
ls /proc/net
ls /etc/udev
cat /proc/stat
cat /proc/uptime
257
Command:
poweroff -i -f
[2 = 2 ] ; echo $?
# 0 (logically TRUE)
[ 2 = 6 ] ; echo $?
# 1 (logically FALSE)
type echo
systemctl list-sockets
258
systemctl reboot
systemctl hibernate
loginctl user-status
# Display terse runtime status information of the user of the caller's session
loginctl session-status
ip route show
ip neigh
# Display the current content of the ARP (Address Resolution Protocol) cache tables
netstat -l --inet
259
Command:
atq
echo $$
echo $!
date --date="yesterday"
Is / | wc -w
260
sudo blkid
bin
etc
home
lib ls -l /etc/shadow
lib64 # Display the user password stored in an encrypted form and the password expiry data
media
root
run
sudo journalctl --since "2019-12-10 13:00:00"
sbin
# Display all the logs since 2019-12-10 13:00:00
srv
sys
tmp
journalctl -disk-usage
usr
261
Command:
ls -m
ls -Q
# List Unix Sockets # Lists all of the .desktop files in the current directory
ss --raw
tracepath www.google.com
# Traces a path to a network host (www.google.com) discovering MTU along the path
echo D*
# Lists all of the files and directories in the current directory whose name starts with letter D
262
echo $'I\'m a Linux Learner.'
echo $USER
echo -e "\033[0;32mGREEN"
GREEN
echo -e "\033[0;31mRED"
1r
Hello,
World!
echo "This is the list of directories and files on this system: $(ls)"
Documents
Downloads
Music \
Pictures
Public
Templates
Videos
263
echo *s
echo [[:upper:]]*
# Print all files and folders that start by upper case character
^ 5
^ 12
echo Capital-{A,B,C}-Letter
echo {1..5}
^ 1 2 3 4 5
echo {A..Z}
^ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
echo x{P{1,2},Q{3,4}}y
264
echo The total price is $500.00
Su Mo Tu We Th Fr Sa — C:\WIK2N\LINUX_OS.EXE
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
March 2022 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
echo $(cal)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
265
sudo Isof -i -P -n | grep LISTEN
Check ports in use
sudo netstat -tulpn | grep LISTEN
sudo ss -tulw
266
[root@localhost manju]# ipcs -u
allocated queues = 0
segments allocated 4
pages swapped 0
used arrays = 0
allocated semaphores = 0
dmidecode -t 16
dmidecode -t baseboard
dmidecode -t bios
267
Command:
dmidecode -t system
Description:
Display the information about the manufacturer, model and serial number of the system
The Linux philosophy is 'Laugh in the face of danger'. Oops. Wrong One. 'Do it
yourself'. Yes, that's it.
Linus Torvalds
268
nmcli con show -a
netstat -r
nmap google.com
# Scan a hostname
nmap 193.169.1.1
# Scan a ip address
nmap --iflist
echo [![:digit:]]*
# Print all files and folders that are not beginning with a numeral
echo *[[:lower:]123]
# Print all files and folders ending with a lowercase letter or the numeral
echo g*
269
echo b*.txt
# Print all files and folders beginning with "b" followed by any characters and ending with ".txt"
echo [abc]*
# Print all files and folders beginning with either "a", "b" or "c"
netstat -t
netstat -x
# Display Information about all connections, listeners and shared endpoints for Network Direct
netstat -n
echo $LANG
^ AAA
270
echo "albert einstein" | tr a-z A-Z
^ ALBERT EINSTEIN
^ EEEEEE EEEEEEEE
Albert Eins
tein was a G
erman-born t
heoretical p
hysicist.
Albert
Einstein
was a
German-born
theoretical
physicist.
271
Is /usr/bin | pr -3 -w 65 | head
D Einstein
Hawking
Darwin
for i in {A..D}; do echo $i; done
file1.txt
file.txt
echo ${!BASH*}
# List all the variables in the environment with names that begin with BASH
bc <<< "6+6"
12
272
df -k
ls -alh
# Search for the files which were modified more than 90 days back
find / -size 0c
# Search all files and folders which are more than 1GB
df -a
df -i
273
du -ch *.png
ac
# Display the total amount of time users are connected to the system
ac --individual-totals
cancel
finger manju
chfn
finger -s manju
274
groups
id -nG
groupadd mygroup
groupdel mygroup
less /etc/group
getent group
userdel manju
# Change the owning group of the file test.txt to the group named "mygroup"
275
sudo depmod -a
# Generates a list of all kernel module dependences and associated map files
dirname /usr/bin
^ /usr
dirname /Desktop/root
^ /Desktop
# Count the number of lines in myfiles.txt which begin with the word 'Hello' or end with the word 'World'
ex myfiles.txt
expand myfiles.txt
# Expand the file myfiles.txt - changing tabs to spaces - and display on standard output
# Convert the tabs in the file myfiles.txt to 10 spaces each, and write the output to myfiles0.txt
276
expr 2 = 5
Returns 0 (false)
# 0
fc -l
!l
# Executes the most recently executed command that begins with the letter "l"
fc -e - l
# Executes the most recently executed command that begins with the letter "l"
fmt myfiles.txt
finger -p manju
# Wrap thelines ofmyfiles.txt to a width of 5characters and writes the outputto myfiles0.txt
277
grep manju /etc/passwd
head myfiles.txt
# Display the first 10 lines of both myfiles.txt and myfiles0.txt - with a header before each that indicates the file name
head -n 5K myfiles.txt
head -n 4 *.txt
# Display the first 4 lines of every file in the working directory whose file name ends with the .txt extension
iostat
# Display listing of last logged in users and system last reboot time and date
278
last -x | less
last shutdown
ldd /bin/bash
less -N myfiles.txt
# View the file myfiles.txt - displaying a line number at the beginning of each line
ls *.{html,php,txt}
# List all files with .html, .php and .txt file extension
lsof -i 6
ls [aeiou]*
lsof -i -U
# List all open Internet, x.25 (HP-UX) and UNIX domain files
lsof -i 4 -a -p 555
# List all open IPv4 network files in use by the process whose Process ID is 555
279
xz myfiles.txt
xz -dk myfiles.txt.xz
# Create the directory "dir" and set its file mode so that all users may read, write and execute it
modinfo snd
# Display all available information about the "snd" Linux kernel module
more +3 myfiles.txt
# Display the contents of file "myfiles.txt" beginning at the first line containing the string "Hello"
netstat -g
# Display multicast group membership information for both IPv4 and IPv6
netstat -c
netstat -natp
280
netstat -rn
# Display the routing table for all IP addresses bound to the server
netstat -an
od -b myfiles.txt
od -Ax -c myfiles.txt
# Display the contents of "myfiles.txt" in ASCII character format - with byte offsets displayed as hexadecimal
trap -l
trap
yum grouplist
yum repolist
281
yum repolist all
cat dc.txt
1 .
2 ..
3 1.txt
4 2.txt
5 .bash_history
6 .bash_logout
7 .bash_profile
8 .bashrc
9 bio.txt
10 .cache
11 .config
12 Data.txt
13 Desktop
14 dir
15 Documents
282
printf "Hi, I'm %s.\n" $LOGNAME
^ abcdef
ps -eLf
ps axms
283
ip route list
route -n
Hello, World!
cat hello.txt
Hello, World!
sfdisk -s
ls -d ~/.ssh
sha224sum myfiles.txt
# Display the SHA224 checksum of the "myfiles.txt" file in the current directory
284
sha256sum myfiles.txt
# Display the SHA256 checksum of the "myfiles.txt" file in the current directory
sha384sum myfiles.txt
# Display the SHA384 checksum of the "myfiles.txt" file in the current directory
sha512sum myfiles.txt
# Display the SHA512 checksum of the "myfiles.txt" file in the current directory
shutdown 8:00
shutdown 20:00
# Schedule the system to shut down in 15 minutes with the normal message alerting users that the system is shutting down
shutdown -P now
sleep 10
startx -- -depth 16
285
time cal
Hello World # Lists all fonts available to the default X server and display
xset q
Hello
World
yes | rm -i *.txt
w manju
286
What is Linux and why is it so popular?
Whether you know it or not you are already using Linux (the best-known and most-used open
source operating system) every day. From supercomputers to smartphones, the Linux operating
system is everywhere. As an operating system, Linux is a family of open source Unix-like
software based on the Linux kernel - that sits underneath all of the other software on a computer,
receiving requests from those programs and relaying these requests to the computer's hardware.
With regard to careers, it is becoming increasingly valuable to have Linux skills rather than just
knowing how to use Windows. In general, Linux is harder to manage than Windows, but offers
more flexibility and configuration options.
Every desktop computer uses an operating system. The most popular operating systems in use
today are: Windows, Mac OS, and LINUX. Linux is the best-known notoriously reliable and
highly secure open source portable operating system -- very much like UNIX -- that has become
very popular over the last several years -- created as a task done for pleasure by Linus Torvalds -
- computer science student at the University of Helsinki in Finland -- in the early 1990s and later
developed by more than a thousand people around the world.
Linux is fast, free and easy to use, that sits underneath all the other software on a computer -
runs your computer -- handling all interactions between you and the hardware i.e., whether
you're typing a letter, calculating a money budget, or managing your food recipes on your
computer, the Linux operating system (similar to other Operating Systems, such as Windows XP,
Windows 7, Windows 8, and Mac OS X) provides the essential air that your computer breathes.
Linux is the most important technology advancement of the twenty-first century and Licensed
under the General Public License (GPL) that Linux uses ensures that the software will always be
open to anyone and whose source code is open and available for any user to check, which makes
it easier to find and repair vulnerabilities and it power the laptops, development machines and
287
servers at Google, Facebook, Twitter, NASA, and New York Stock Exchange, just to name a
few. Linux has many more features to amaze its users such as: Live CD/USB, Graphical user
interface (X Window System) etc.
Why LINUX?
Although Microsoft Windows (which is the most likely the victim of viruses and malware) has
made great improvements in reliability in recent years, it considered less reliable than Linux.
Linux is notoriously reliable and secure and it is free from constant battling viruses and malware
(which may affect your desktops, laptops, and servers by corrupting files, causing slow downs,
crashes, costly repairs and taking over basic functions of your operating system) - and it keep
yourself free from licensing fees i.e., zero cost of entry ... as in free. You can install Linux on as
many reliable computer ecosystems on the planet as you like without paying a cent for software
or server licensing. While Microsoft Windows usually costs between $99.00 and $199.00 USD
for each licensed copy and fear of losing data.
288
• Kernel
Kernel is the core part of Linux Operating System and interacts directly with hardware. It is
responsible for all major activities of the Linux operating system.
• System Library
System libraries are special programs using which application programs accesses Kernel's
features.
• System Utility
• Portable
• Open Source
• Multi-User
• Multiprogramming
• Hierarchical File System
• Security
Now Linux (successfully being used by several millions of users worldwide) has grown passed
the stage where it was almost exclusively an academic system, useful only to a handful of people
with a technical background. It provides more than the operating system: there is an entire
infrastructure supporting the chain of effort of creating an operating system, of making and
testing programs for it, of bringing everything to the users, of supplying maintenance, updates
and support and customizations, runs on different platforms including the Intel and Alpha
platform. Today, Linux is ready to accept the challenge of a fast-changing world to do various
289
types of operations, call application programs etc. Since the hiring focus is shifting more
and more toward DevOps type skills, a Linux skill set will be the types of things that will
make you very deployable.
[manju@localhost ~]$ Is
cat /etc/profile
cat /etc/bashrc
cat .bash_profile
290
[manju@localhost ~]$ date
[manju@localhost ~]$ x
290 Display the number of the current command in the history list
1000
Display the Effective user ID
291
[manju@localhost ~]$ PS1="\d" __________________
Hello
World
Hello \ World
292
Directory Function
/ The top-level directory of a Linux system that holds all files, device
/usr Contains the commands and files that the system uses
/var/spool Contains spooled files, such as those produced for network transfers and
printing operations
/sbin Contains commands for system administration used to boot the system
/dev Holds file interfaces for devices like printers and terminals
293
find / -user manju -print
ls /usr/share/X11
ls /etc/X11
ls /etc/gdm
ls /usr/share/gdm
# Display the contents of GDM configuration directory for default settings and themes
ls /etc/gconf
ls /usr/share/gnome
ls /usr/share/doc/gnome*
# Display the contents of Documentation for various GNOME packages, including libraries
294
Is /usr/share/icons
Is /etc/cron.d
# List the directory with numerous crontab files that is only accessible to the root user
ls /etc/cron.hourly
ls /etc/cron.daily
ls /etc/cron.weekly
ls /etc/cron.monthly
ls /etc/mtab
ls /etc/services
# List the services run on the system and the ports they use
295
Is /etc/cups
Is /proc/net
free -s 3
# Display the current usage status of Memory continuously after regular interval
whereis -b ls
whereis -m ls
whereis -s ls
296
watch -t -n 1 date
Albert
du -sh * --time
# Check each file's size and the date and time it was last edited
dmidecode -s system-serial-number
ls -aril
du -sch *
# Display the sum of size of all files and folders in present directory
297
cat /proc/cpuinfo | grep processor | wc -l
dirs
blkid -i /dev/sda
# Display information about available block devices
crontab -e <
298
[manju@localhost ~]$ hostname -I
192.168.6.131 192.168.122.1
badblocks -s /dev/sda
lsof -u manju
sudo shutdown -r 2
albert
ALBERT
299
nmcli d
# Search for a line which will start with alphanumeric characters in "myfiles.txt"
# Search for a line which will start with alpha characters in "myfiles.txt"
# Search for a line which will start with blank characters in "myfiles.txt"
# Search for a line which will start with digit characters in "myfiles.txt"
# Search for a line which will start with lowercase letters in "myfiles.txt"
# Search for a line which will start with punctuation characters in "myfiles.txt"
# Search for a line which will start with graphical characters in "myfiles.txt"
# Search for a line which will start with printable characters in "myfiles.txt"
300
grep "A[[:space:]]" myfiles.txt
# Search for a line which will start with space charactersin "myfiles.txt"
# Search for a line which will start with uppercase letters in "myfiles.txt"
# Search for a line which will start with hexadecimal digits in "myfiles.txt"
vmstat -a
vmstat -s
vmstat -f
vmstat -D
vmstat -d
301
[manju@localhost ~]$ free -h --total
• hostname -s
Display the short version of the hostname
• hostname --short
hostname --all-ip-addresses
date -r /etc/hosts
Albert Einstein
Elsa Einstein
Albert Einstein
302
[manju@localhost ~]$ cat 12.txt
Albert Einstein
Elsa Einstein
1 Albert Einstein
2 Elsa Einstein
Albert Einstein
Albert Einstein$
# Search for the words "but" and "is" in the phy.txt file
# Search for the words "but", "is" and "of" in the phy.txt file
▲
303
echo "The system will be shutdown in 10 minutes." | wall
I_____________________
▼
The message (The system will be shutdown in 10 minutes.) will
be broadcasted to all users that are currently logged in
Albert Einstein
ss --all
ss --listen
ss -t state listening
192.168.6.131
System's IP address
304
yum erase httpd
# Uninstall apache
• 4 = 4 + 0 + 0 (read)
305
cat /var/log/boot.log
cat /var/log/maillog
cat /var/log/yum.log
ps -AlFH
306
ps -auxf | sort -nr -k 3 | head -10
grep -r "is" *
307
chkconfig --list | grep network
shutdown -r 18:30
netstat -ain
ls -ld /home
308
chmod go=+r 1.txt
du -sh .[!.]* *
# Display the disk usages of the files (including hidden files) in the current directory
du -sch .[!.]* *
309
iostat -kx
netstat -nulp
sudo yum install parted
# Display open UDP sockets
# Install parted
netstat -nxlp
parted -v
# Display open Unix sockets
# Check Parted version
dmidecode -q | less
parted -l
# Display BIOS information
# Lists partition layout on all block devices
systemctl --failed
parted -m
# List failed services
# Displays machine parseable output
losetup
# Exit the parted shell
# Display information about all loop devices
310
sudo tcpdump -D
myfiles.txt.xz
61.852
61.852
311
[manju@localhost ~]$ free -t | awk 'NR == 3 {print $3/$2*100}'
2.54155
2.54155
Display Swap Utilization
61.86%
61.86%
Display Memory Utilization with Percent Symbol and two decimal places
2.65%
2.65%
Display Swap Utilization with Percent Symbol and two decimal places
312
[manju@localhost ~]$ top -b -n1 | grep 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
alias -p
313
sudo netstat -anp | grep tcp | grep LISTEN
printf "%s\n" *
# Prints the files and directories that are in the current directory
printf "%s\n" */
[manju@localhost ~]$ x
314
[manju@localhost ~]$ x="alan"; printf '%s\n' "${xA}"
Alan
ALAN
ALAN
Find directories and files with names starting with "xyz" and
ending with an alpha character after a one-digit
find . -mtime -3
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
Mathison
Alan
# prints 4 * 2
316
x='4 * 2'; echo "$(($x))"
# prints 8
aLAN
alan
aLAN
alan
317
[manju@localhost ~]$ x='You are a genius'; echo "${x#*a}"
re a genius
enius
foo
25
You are
You
Bob
Bob-Dev
Fox
Dev-Fox
318
find . -type f -path '*/Documents/*'
# Find all files except the ones contained in a folder called Documents
# Find all files except the ones contained in a folder called Documents or log files
0000
319
[manju@localhost ~]$ echo "$(printf "%05d" "${x}")"
00000
15
15
n Tu
1 (True)
0 (False)
320
[manju@localhost ~]$ expr PQRSTUVWXYZ : PQRS
Is -ral
• ls -tl
• ls -trl
# List the files such that the one that was most recently edited is at the top of the list
./bc.pdf
find . -type f -print
./1.PDF
# List only regular files
./data.sh
./1.sh
[manju@localhost ~]$ echo "alan+alan+alan+alan" | xargs -d +
./2.SH
alan alan alan alan
./1.pdf
[manju@localhost ~]$ echo "alan+alan+alan+alan" | xargs -d + -n 2
./2.sh
alan alan
alan alan
321
[manju@localhost ~]$ echo -e "2\nalbert\n" > 1.txt
albert
Albert
Tesla
John
1 Albert
2 Tesla
3 John
322
[manju@localhost ~]$ echo -e "Albert\nTesla\nJohn" | nl -s ": " -w 1
1: Albert
2: Tesla
3: John
du -h -d1
find / - manju
locate "*.png"
323
find . -type f -printf "\"%p\" " | xargs chmod 664
# Find all files in the current directory, including subfolders and assign rights 664
# Find all files in the current directory, including subfolders and assign rights 775
ll
ls -l
# List the files in current directory
date +%j
date +%Y%m%d
date +%d\/%m\/%Y
324
C Exercises
Dennis Ritchie, known as the "Father of C Low-Level Programming Language," created the
general-purpose, procedural, imperative computer programming language "C" in 1972 at the
Bell Telephone Laboratories to be used with the UNIX operating system. It now ranks among the
most popular programming languages after spreading to numerous different operating systems.
Many other well-known languages, including C++, which was initially created as an
improvement to C, have also been strongly inspired by C. Though it is also widely used for
creating applications, it is the most frequently used programming language for creating system
software. It is one of the programming languages that is most frequently used today. Since 1989,
C has been standardized by both the International Organization for Standardization and the
American National Standards Institute. Don't worry if you are a beginner; we have exercises for
you. We'll concentrate on beginner-level programming problems in this chapter to help you learn
C and develop your programming abilities.
325
Question 1
Question:
#include<stdio.h>
Solution:
int main() {
#include<stdio.h> int a = 6;
int main() {
{
printf("Hello, World!");
int a = 2;
return 0;
printf("%d\n", a);
} Output:
}
2
printf("%d\n", a);
6
}
Question 2
Question:
Solution:
#include<stdio.h>
int main() {
int height = 8;
int width = 5;
326
int perimeter = 2*(height + width);
printf("Perimeter of the rectangle is: %d cm\n", perimeter);
int area = height * width;
printf("Area of the rectangle is: %d square cm\n", area);
return 0;
}
Question 3
Question:
Solution:
#include<stdio.h>
int main() {
int radius = 4;
float perimeter = 2*3.14*radius;
printf("Perimeter of the circle is: %f cm\n", perimeter);
float area = 3.14*radius*radius;
printf("Area of the circle is: %f square cm\n", area);
return 0;
}
327
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
#include<stdio.h> "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);
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>
scanf("%f", &y);
printf("\nEnter the third number: "); Error
scanf("%f", &z);
Question 8
Question:
Write a program that reads an integer between 1 and 7 and print the day of the week in
English.
Solution:
331
#include<stdio.h>
int main() {
int day;
printf("\nEnter a number between 1 to 7 to get the day name: ");
scanf("%d", &day);
switch(day) {
case 1 : printf("Monday\n"); break;
case 2 : printf("Tuesday\n"); break;
case 3 : printf("Wednesday\n"); break;
case 4 : printf("Thursday\n"); break;
case 5 : printf("Friday\n"); break;
case 6 : printf("Saturday\n"); break;
case 7 : printf("Sunday\n"); break;
default : printf("Enter a number between 1 to 7.");
}
return 0;
}
Question 9
Question:
332
a=1;
b=2;
sum = a + b;
printf("The sum of a and b = %d", sum);
return 0;
}
Question 10
Question:
Solution:
#include<stdio.h>
#include<stdio.h>
#include<math.h> extern int a;
return 0; int a = 1;
}
Output:
a = 1
333
Question 11
Question:
Solution: #include<stdio.h>
Question 12
Question:
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:
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;
printf("%d", b);
Output:
Question:
printf("\n");
1
Write a program: }
12
If you enter a character M return 0;
1234
12345
Solution:
337
#include<stdio.h> #include<stdio.h>
return 0; z = 28;
return 0; Output:
Question 17 } 15 28
Question:
Write a program to print the multiplication table of a number entered by the user.
#include<stdio.h>
Solution:
int main () {
#include<stdio.h> float a;
int main() {
a = (float) 51/4;
int n, i;
printf("%f", a);
printf("Enter any number: ");
scanf("%d", &n); return 0;
338
Question 18
Question:
Question 19
Question:
Solution:
#include<stdio.h>
339
int main() {
int a; #include<stdio.h>
a = -35;
int main() {
if(a>0) {
char name[] = "Einstein";
printf("Number is positive");
} printf("%c", name[0]);
else { return 0;
printf("Number is negative");
}
}
return 0;
Output:
}
E
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the first number: ");
scanf ("%d", &x);
printf("\nEnter the second number: ");
scanf ("%d", &y);
if(x-y==0) {
printf("\nThe two numbers are equivalent");
340
}
else {
printf("\nThe two numbers are not equivalent");
}
return 0;
}
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
341
Question 22
Question:
Solution:
#include<stdio.h>
#include<stdio.h> int main() {
int main() {
char name[] = "Einstein";
char i;
name[0] = 'H';
for(i='A'; i<='Z'; i++) {
printf("%c\n", i); printf("%s", name);
} return 0;
return 0;
}
}
Output:
Hinstein
Question 23
Question:
Solution:
#include<stdio.h>
#include<string.h>
342
int main() {
char str[1000];
printf("Enter a string to calculate its length: ");
scanf("%s", str);
printf("The length of the entered string is: %ld", strlen(str));
return 0;
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
343
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
Question 26
Question:
Write a program to convert the lower case letter to upper case letter.
344
Solution:
In a C program, any number of functions can be written.
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches. #include<stdio.h>
int main() {
int i = 6;
Solution: while(i == 3) {
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() {
printf("%d", i);
Write a program to print the output:
return 0;
Einstein [0] = E
}
Einstein [1] = I
Einstein [2] = N
Output:
Einstein [3] = S
54
Einstein [4] = T
Einstein [5] = E
Einstein [6] = I
Einstein [7] = N
Solution:
#include<stdio.h>
int main() {
char name [8] = {'E' , 'I', 'N', 'S', 'T', 'E', 'I', 'N'};
for(int i=0; i<8; i++) {
printf("\nEinstein [%d] = %c", i, name[i]);
}
return 0;
346
}
Question 29
Question:
#include<stdio.h>
int main() {
Solution:
#include<stdio.h>
int main() {
for(int i=1; i<=10; i++) {
printf("Hello World \n");
}
return 0;
}
Question 30
Question:
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:
#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:
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int main() { int num[] = {5, 7, 9, 42};
int a; num[0] = 3;
printf("Enter any number: ");
printf("%d", num[0]);
scanf ("%d", &a);
return 0;
if(a%2 == 0) {
printf("The entered number is even"); }
} Output:
else {
3
printf("The entered number is odd");
}
return 0;
}
Question 33
Question:
349
Solution:
#include<stdio.h>
int main() {
char ch = 'A';
printf("The ASCII value of %c is: %d", ch, ch);
return 0;
}
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder will be 2.
#include<stdio.h> "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:
descending order.
Solution:
#include<stdio.h>
int main() {
int a, b;
printf("\nEnter a pair of numbers (for example 22,12 | 12,22): ");
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
scanf("%d", &b);
if (a>b) {
printf("\nThe two numbers in a pair are in descending order.");
}
else {
printf("\nThe two numbers in a pair are in ascending order.");
}
return 0;
}
351
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
not possible" if that is not possible.
#include<stdio.h>
int main() {
int a = 6;
Solution:
float b = 6.0;
#include<stdio.h> if(a == b) {
int main() { printf("\na and b are equal");
int a, b;
}
float c;
else {
printf("\nEnter the first number: ");
scanf("%d", &a); printf("\na and b are not equal");
352
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int a = 15, b, c;
int main() {
int x, i; b = a = 25;
}
}
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) {
} }
}
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:
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) {
359
}
return 0;
}
Question 46
#include<stdio.h>
int main() {
Question:
int i = 60;
Write a program to print the output:
if(i > 70 && i < 100) {
body [b] = b
printf("i is greater than 70 and less than 100");
body [o] = o
}
body [d] = d
else {
body [y] = y
printf("%d", i);
}
Output:
return 0;
Solution: 60
}
#include <stdio.h>
int main() {
char i;
char body [4] = {'b', 'o', 'd', 'y'};
for(i=0; i<4; i++)
printf("\n body[%c] = %c", body[i] , body[i]);
return 0;
}
360
Question 47
Question:
Write a program to calculate the discounted price and the total price after discount
Given:
#include<stdio.h>
int main() {
Solution:
printf("%%15s = %15s\n", "albert");
361
}
Question 48
Question:
Write a program to print the first ten natural numbers using while loop statement.
Solution: #include<stdio.h>
int main() {
#include<stdio.h>
int i = 12;
int main() {
int i = 1; if(i == 12 && i != 0) {
} Hi
return 0;
Question 49 Einstein
}
Question:
362
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:
Solution:
#include<stdio.h>
int main() {
int x;
printf("Enter the integer from keyboard: ");
scanf("%d",&x);
printf("\nEntered value: %d ",x);
printf("\nThe right shifted data is: %d ", x>>=2);
return 0;
}
363
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
the absolute difference if x is greater than 21.
Output:
25 25
364
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the first number: ");
scanf("%d", &x);
printf("\nEnter the second number: ");
scanf("%d", &y);
if(x % y == 0) {
printf("\n%d is a multiple of %d.\n", x, y);
}
else {
printf("\n%d is not a multiple of %d.\n", x, y);
}
return 0; #include<stdio.h>
} int main() {
int x = 10;
return 0;
Output:
True
365
Question 53
Question:
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:
Solution:
#include<stdio.h>
int main() {
float fahrenheit, celsius;
celsius = 36;
fahrenheit = ((celsius*9)/5)+32;
printf("\nTemperature in fahrenheit is: %f", fahrenheit);
return 0;
}
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
367
Solution:
#include<stdio.h>
int main() {
int x, y;
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if(x == 50 || y == 50 || (x + y == 50)) {
printf("\nTrue");
} #include<stdio.h>
else {
int main() {
printf("\nFalse");
while(!printf("Albert Einstein")){}
}
return 0; return 0;
}
}
Output:
Albert Einstein
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
368
#include<stdio.h>
int main () {
int x, even = 0, odd 0, positive = 0, negative = 0;
printf("\nPlease enter 18 numbers:\n");
#include<stdio.h>
for(int i = 0; i < 18; i++) {
scanf("%d", &x); int main() {
if (x > 0) { int x = 0, y = 1 ;
positive++;
if(x == 0) {
}
(y > 1 ? printf("\nHi") : printf ("\nAlbert"));
if(x < 0) {
negative++; }
} else {
#include<stdio.h>
int main() {
switch(printf("Albert Einstein")){}
return 0;
Output:
}
Albert Einstein
369
Question 57
Question:
#include<stdio.h>
int main() {
Solution:
int x;
} }
return 0; Output:
} David
Question 58
Question:
Write a program that reads a student's three subject scores (0-100) and computes the
average of those scores.
370
Solution:
#include<stdio.h>
int main() {
float score, total_score = 0;
int subject = 0;
printf("Enter three subject scores (0-100):\n");
while (subject != 3) {
scanf("%f", &score);
if(score < 0 || score > 100) {
printf("Please enter a valid score.\n");
}
else {
total_score += score;
subject++;
}
}
printf("Average score = %.2f\n", total_score/3);
return 0;
}
Question 59
Question:
371
#include<stdio.h>
#include<stdio.h>
int main() {
for(int i=1; i<=5; i++) { int main() {
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);
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. }
#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 {
}
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 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;
break;
default:
printf("\nElsa");
Solution:
}
Output:
#include<stdio.h>
#include<stdlib.h> Albert
int main() {
int x=12, y =3;
377
printf("%d\n", abs(-x-y));
return 0;
}
#include<stdio.h>
Solution:
int main() {
15
int x = 5;
switch (x - 6) {
case -1 :
printf("\nAlbert");
#include<stdio.h>
case 0 :
#include<stdlib.h>
printf("\nJohn");
int main() {
int x=12, y =3; case 1 :
return 0;
Solution: }
Output:
15
Albert
John
Mary
#include<stdio.h>
James
#include<stdlib.h>
378
int main() {
int x=12, y =3; #include<stdio.h>
printf("%d\n", x-(-y)); int main() {
return 0;
int y[] = {20, 40, 60, 80, 100};
}
for(int x = 0; x <= 4; x++) {
}
Solution: Output:
return 0;
15 } 20
40
60
80
Question 60
100
Question:
Solution:
#include<stdio.h>
int main() {
int num [] = {11, 22, 33, 44, 55, 66};
int n = sizeof(num) / sizeof(num [0]);
printf("Size of the array is: %d\n", n);
return 0;
}
379
Question 61
Question:
Write a program that prints a sequence from 1 to a given integer, inserts a plus sign
between these numbers, and then removes the plus sign at the end of the sequence.
Solution:
#include<stdio.h>
int main () {
int x, i;
printf("\nEnter a integer: \n");
scanf("%d", &x);
#include<stdio.h>
if(x>0) {
printf("Sequence from 1 to %d:\n", x); int main() {
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
int main() {
#include<stdio.h> i=x%10;
} return 0;
int myfunc(int a, int b) {
}
return a == b ? (a + b)*3 : a + b;
Output:
}
68235
383
Question 65
Question:
Write a program that accepts minutes as input, and display the total number of hours and
minutes.
#include<stdio.h>
int main() {
Question 66
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five.
384
Solution:
#include<stdio.h>
#include<stdio.h>
#define MULT(i) (i*i)
int main() {
int main() {
int x;
printf("\nEnter a number: "); int x = 6;
Question 67
Question:
Write a program to verify whether one of the two entered integers falls within the range
Solution:
#include<stdio.h>
int main() {
int x, y;
385
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if((x >= 100 && x <= 200) || (y >= 100 && y <= 200)) {
printf("True");
#include<stdio.h>
}
else { int main() {
i++;
return 0;
Question 68
}
Question:
Write a program to determine which of the two given integers is closest to the value 100.
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
int main() {
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); }
return 0;
}
388
Question 71
Question:
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int x = 43;
if(x % 12 == 0 || x % 12 == 1) {
printf("True");
}
else {
printf("False");
#include<stdio.h>
}
int main() {
return 0;
printf(6 + "Albert Einstein");
}
return 0;
Output:
Einstein
389
Question 72
Question:
Write a program that accepts two integers and returns true when one of them equals 6, or
when their sum or difference equals 6.
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int x, y;
printf("\nEnter the value for x: ");
scanf("%d", &x);
printf("\nEnter the value for y: ");
scanf("%d", &y);
if(x == 6 || y == 6 || x + y == 6 || abs(x - y) == 6) {
printf("True");
}
#include<stdio.h>
else {
printf("False"); int main() {
Output:
2.500000
390
Question 73
Question:
Write a program to check whether it is possible to add two integers to get the third
integer from three entered integers.
Solution:
#include<stdio.h>
int main() {
int x, y, z;
printf("\nEnter the value for x: ");
scanf("%d", &x); #include<stdio.h>
printf("\nEnter the value for y: ");
int myfunc();
scanf("%d", &y);
int main() {
printf("\nEnter the value for z: ");
scanf("%d", &z); printf("\nAlbert Einstein");
if(x == y + z || y == x + z || z == x + y) { myfunc();
printf("True"); return 0;
}
}
else {
int myfunc() {
printf("False");
} printf("\nElsa Einstein");
return 0; main();
}
391
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
#include<stdio.h>
int main() {
float kmph;
printf("Enter kilometers per hour: ");
scanf("%f", &kmph);
printf("\n%f miles per hour", (kmph * 0.6213712));
return 0;
#include<stdio.h>
}
int main() {
printf("Albert Einstein\n");
main();
Question 75
return 0;
Question:
Solution:
#include<stdio.h>
#define PI 3.141592
392
int main() {
float major, minor;
printf("\nEnter length of major axis: ");
scanf("%f", &major);
printf("\nEnter length of minor axis: ");
scanf("%f", &minor);
printf("\nArea of an ellipse = %0.4f", (PI * major * minor));
return 0;
}
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
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>
int x = 1;
x++;
if(x <= 6) {
Solution:
printf("\nC language");
#include<stdio.h> exit(0);
int main() {
main();
double bytes;
printf("\nEnter number of bytes: "); }
scanf("%lf",&bytes); return 0;
Output:
C language
394
Question 78
Question:
Solution:
#include<stdio.h>
int main() {
double megabytes, kilobytes;
printf("\nInput the amount of megabytes to convert: ");
scanf("%lf",&megabytes);
kilobytes = megabytes * 1024;
printf("\nThere are %lf kilobytes in %lf megabytes.", kilobytes, megabytes);
return 0;
}
Question 79
Question:
Solution:
#include<stdio.h>
395
int main() {
int array[1000], i, arr_size, even=0;
printf("Input the size of the array: ");
scanf("%d", &arr_size);
printf("Enter the elements in array: \n");
for(i=0; i<arr_size; i++) {
scanf("%d",&array[i]);
}
Question 80
Question:
Solution:
#include<stdio.h>
int main() {
396
int array[1000], i, arr_size, odd=0;
printf("Input the size of the array: ");
scanf("%d", &arr_size);
printf("Enter the elements in array: \n");
for(i=0; i<arr_size; i++) {
scanf("%d",&array[i]);
}
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:
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() {
while(putchar(*x++));
Output:
return 0;
Albert Einstein
}
400
Question 85
Question:
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:
Solution:
#include<stdio.h>
int main() {
401
double gigabytes, megabytes;
printf("\nInput the amount of gigabytes to convert: ");
scanf("%lf", &gigabytes);
megabytes = gigabytes*1024;
printf("\nThere are %lf megabytes in %lf gigabytes.", megabytes, gigabytes);
return 0;
}
Question 87
Question:
Solution:
#include<stdio.h>
int main() {
float kg, lbs;
printf("\nEnter Weight in Kilogram: ");
scanf("%f", &kg);
lbs = kg*2.20462;
printf("\n%f Kg = %f Pounds", kg, lbs);
return 0;
}
402
Question 88
Question:
Solution:
#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:
Solution:
403
#include<stdio.h>
int main() {
float pound, gram;
printf("\nEnter Weight in Pounds: ");
scanf("%f", £);
gram = pound*453.592;
printf("\n%f Pound = %f Grams", pound, gram);
return 0;
}
Question 90
Question:
Solution:
#include<stdio.h>
int main() {
int angle1, angle2, angle3, sum;
printf("\nEnter the first angle of the triangle: ");
scanf("%d", &angle1);
printf("\nEnter the second angle of the triangle: ");
scanf("%d", &angle2);
printf("\nEnter the third angle of the triangle: ");
scanf("%d", &angle3);
sum = angle1 + angle2 + angle3;
if(sum == 180) {
404
printf("\nThe triangle is valid.");
}
else {
printf("\nThe triangle is not valid.");
}
return 0;
}
Question 91
Question:
Write a program to add the digits of a two-digit number that is entered by the user.
Solution:
#include<stdio.h>
int main() {
int x, y, sum = 0;
printf("\nEnter a two-digit number: ");
scanf("%d", &x);
y = x;
while(y != 0) {
sum = sum + y % 10;
y = y / 10;
}
printf("\nSum of digits of %d is: %d", x, sum);
return 0;
}
405
Question 92
Question:
Solution:
#include<stdio.h>
int main() {
char ch;
printf("\nEnter a character: ");
scanf("%c", &ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'a' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
406
Question 93
Question:
#include<stdio.h>
int main() {
int i;
Question 94
Question:
Solution:
407
#include<stdio.h>
int main() {
int x[12]={31,28,31,30,31,30,31,31,30,31,30,31}, m;
printf("\nEnter the month number: ");
scanf("%d",&m);
if(m>12 || m<1) {
printf("Invalid input");
}
else if(m==2) {
printf("\nNumber of days in month 2 is either 29 or 28");
}
else {
printf("\nNumber of days in month %d is %d", m, x[m-1]);
}
return 0; #include<stdio.h>
} int main() {
char *names[] = {
"Albert",
Question 95 "Alan",
"John",
"Mary" Albert
Write a program to concatenate two strings.
};
Alan
int i;
John
for(i=0;i<5;i++)
Solution: James
puts(*(names+i));
return(0); Mary
#include<stdio.h>
#include<string.h> }
int main() {
char a[1000], b[1000];
408
printf("\nEnter the first string: ");
scanf("%s", a);
printf("\nEnter the second string: ");
scanf("%s", b);
strcat(a, b);
printf("\nString produced by concatenation is: %s", a);
return 0;
}
Question 96
Question:
#include<stdio.h>
int main() {
Solution:
for(int x=2; x<=25; x=x+2) {
409
return 0;
}
Question 97 #include<stdio.h>
int main() {
printf("*");
Solution:
}
#include<stdio.h>
return 0;
#include<string.h>
int main() { }
} }
return 0;
} Output:
Albert Einstein
410
Question 98
Question:
Write a program to convert the upper case letter to lower case letter.
Solution:
#include<ctype.h>
#include<stdio.h>
int main() {
char ch;
ch = 'G';
printf("%c in lowercase is represented as %c", ch, tolower(ch));
return 0;
}
Question 99
Question:
Write a program to find the quotient and remainder of a entered dividend and divisor.
Solution:
#include<stdio.h>
411
int main() {
int dividend, divisor;
printf("\nEnter dividend: ");
scanf("%d", ÷nd);
printf("\nEnter divisor: ");
scanf("%d", &divisor);
printf("\nQuotient = %d\n", (dividend / divisor));
printf("\nRemainder = %d", (dividend % divisor));
return 0;
}
Question 100
Question:
Write a program to determine the Size of int, float, double and char.
Solution:
#include<stdio.h>
int main() {
printf("Size of char is: %ld byte\n",sizeof(char));
printf("Size of int is: %ld bytes\n",sizeof(int));
printf("Size of float is: %ld bytes\n",sizeof(float));
printf("Size of double is: %ld bytes", sizeof(double));
return 0;
}
412
Question 101
#include<stdio.h>
Question:
|
int main() {
Write a program to verify the password until it is correct.
int i;
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);
scanf("%d", &y);
return 0;
413
Question 102
Question:
Solution:
#include<stdio.h>
#include<stdlib.h>
int main() {
int num;
printf("Input a positive or negative number: \n");
scanf("%d", &num);
printf("\nAbsolute value of |%d| is %d\n", num, abs(num));
return 0;
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
414
#include<stdio.h>
int main() {
float ht;
printf("\nEnter the height (in cm): ");
scanf("%f", &ht);
if(ht < 150.0) {
printf("Dwarf.\n");
}
else if((ht >= 150.0) && (ht < 165.0)) {
printf("Average Height.\n");
}
else if((ht >= 165.0) && (ht <= 195.0)) {
printf("Taller.\n");
#include<stdio.h>
}
else { int main() { Because the condition is
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>
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--) {
* *
*
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
A-B: 12
AXB: 64
Question 108
A/B: 4
Question:
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:
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:
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:
Solution:
422
#include<stdio.h>
int main() {
int x, y; #include<stdio.h>
1
Question 113
0
Question:
Write a program that allows you to enter the cost price and the selling price of a product
and calculate profit or loss.
Solution:
#include<stdio.h>
int main() {
int cp, sp;
printf("\nInput Cost Price: ");
scanf("%d", &cp);
423
printf("\nInput Selling Price: ");
scanf("%d", &sp);
if(sp > cp) { #include<stdio.h>
printf("Profit = %d", (sp - cp)); int main() {
}
int x[25], a;
else if(cp > sp) {
for(a = 0; a <= 24;a++);
printf("Loss = %d", (cp - sp));
} {
else { x[a] = a;
printf("No Profit No Loss.");
printf("\n%d", x[a]);
}
}
return 0;
return 0;
}
}
Output:
25
Question 114
Question:
Write a program that display the pattern like a right angle triangle using an asterisk.
Solution:
#include<stdio.h>
int main() {
int rows;
printf("Input the number of rows: ");
scanf("%d", &rows);
for(int x=1; x<=rows; x++) {
424
for(int y=1; y<=x; y++)
printf("*");
printf("\n");
}
return 0;
}
Question 115
Question:
Write a program that display the pattern like a right angle triangle using a number.
Solution:
#include<stdio.h>
int main() {
int rows;
printf("Input the number of rows: ");
scanf("%d",&rows);
for(int x=1; x<=rows; x++) {
#include<stdio.h>
for(int y=1; y<=x; y++)
static int b;
printf("%d", y);
printf("\n"); int main() {
} static int c;
return 0; printf("%d %d", b, c);
}
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>
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() {
} #include<math.h>
int main() {
Output:
printf("%f\n", log(50.0));
return 0; 3.912023
427
Question 118
Question:
Solution:
#include<stdio.h>
#include<math.h>
int main() {
int x;
printf("Enter any number: ");
scanf("%d",&x);
printf("Square root of %d is %.2lf", x, sqrt(x));
return 0;
}
Question 119
Question:
Solution:
#include<stdio.h>
428
#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:
#include<stdio.h>
int main() {
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:
or not.
#include<stdio.h>
int main() {
#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:
or not.
#include<stdio.h>
#define SIZE 6
int main() {
431
Question 123
Question:
Write a program to check whether the entered character is a graphic character or not.
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
char a;
printf("Enter a character: ");
scanf("%c", &a);
if(isgraph(a)) {
printf("\n%c is a graphic character."
}
Output:
else {
printf("\n%c is NOT a graphic character." 0
} 0
return 0; #include<stdio.h>
}
int main() {
return 0; _____________
432
Question 124
Question:
#include<stdio.h>
In the switch condition,
int main() {
"i" is not an integer. We
Solution: float i = 6.1 ; cannot test floats in
switch statements.
switch (i) {
#include<stdio.h>
#include<ctype.h> case 0.1 :
} case 6.1 :
printf("\nAlbert");
return 0;
Error
Question 125 } 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:
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
int i;
printf("The ASCII value of all control characters are: \n");
434
for(i=0; i<=127; i++) {
if(iscntrl(i)!=0) #include<stdio.h>
printf("\n %d ", i);
int main() {
}
if(printf("Albert Einstein")){}
return 0;
} return 0;
Output:
Albert Einstein
Question 127
Question:
Write a program to check whether the entered character is a white-space character or not.
Solution:
#include<stdio.h>
#include<stdio.h>
typedef int var;
#include<ctype.h>
int main() { var main() {
char c; var i = 6;
printf("Enter a character: "); printf("%d + %d = %d\n", i, i, i+i);
scanf("%c", &c);
return 0;
if(isspace(c) == 0) {
printf("Not a white-space character."); }
}
else { Output:
printf("White-space character.");
6 + 6 = 12
return 0;
435
}
Question 128
Question:
Solution:
#include<stdio.h>
#include<ctype.h>
int main() {
char ch = 'a';
if(isprint(ch)) {
printf("\n%c is printable character.", ch);
}
else {
printf("\n%c is not printable character.", ch);
}
if(iscntrl(ch)) {
printf("\n%c is control character.", ch);
}
else {
printf("\n%c is not control character.", ch);
}
return (0);
436
}
int main() {
Question:
char name[10];
Write a program to calculate surface area of cube. printf("Enter your name: ");
fgets(name,10,stdin);
return 0;
Solution:
}
#include<stdio.h>
int main() {
int side;
long area;
printf("\nEnter the side of cube: ");
scanf("%d", &side);
area = 6*side*side;
printf("\nThe surface area of cube is: %ld", area);
return 0;
}
Question 130
Question:
437
#include<stdio.h>
Solution:
int main() {
#include<stdio.h>
for(int i=12; i<=15; i=i+1) {
#include<stdlib.h>
printf("%d\t", i);
int main() {
int x =6, y=3; }
printf("%d", x+(~y)+1) putchar('\n');
return 0;
return 0;
}
}
Output:
Question 131 12 13 14 15
Question:
#include<stdio.h>
int main() {
Solution: int i;
#include<stdlib.h> return(0);
int main() { Output:
438
Question 132
Question:
#include<stdio.h>
int main() {
Solution:
printf("%d\n", 49);
#include<stdio.h>
printf("%1.2f\n",3.15698222);
int main() {
printf("%d\n", 496596);
int x=2;
printf("%d", x<<1); printf("%1.1f\n",0.00056);
return 0; return 0;
}
}
Question 134
Question:
Solution:
#include<stdio.h>
int main() {
int x=12;
printf("%d", x>>1);
439
return 0;
}
Question 135
Question:
Solution:
#include<stdio.h>
int main() {
int radius;
float PI = 3.141592;
printf("\nEnter the radius of sphere: ");
scanf("%d", &radius);
float volume = (4/3)*(PI*radius*radius*radius);
printf("\nThe volume of sphere is: %f", volume);
return 0;
#include<stdio.h> ?
}
int main() {
■
printf("Enter a character: ");
int c = getc(stdin);
Question 136
printf("You have entered the character '%c'.\n",c);
return 0;
Question:
}
440
Solution:
#include<stdio.h>
int main() {
int r1, r2, r3;
float PI = 3.141592;
printf("\nEnter the radius of the ellipsoid of axis 1: ");
scanf("%d", &r1);
printf("\nEnter the radius of the ellipsoid of axis 2: ");
scanf("%d", &r2);
printf("\nEnter the radius of the ellipsoid of axis 3: ");
scanf("%d", &r3);
float volume = (4/3)*(PI*r1*r2*r3);
printf("\nThe volume of ellipsoid is: %f", volume);
return 0;
}
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
#include<stdio.h>
441
int main() {
int x, y; #include<stdio.h>
Question 138
Question:
Solution:
#include<stdio.h>
int main() {
int a,b,c;
float avg;
printf("\nEnter the first number: ");
scanf("%d", &a);
printf("\nEnter the second number: ");
442
scanf("%d",&b);
printf("\nEnter the third number: ");
scanf("%d",&c);
avg=(a+b+c)/3.0;
printf("\nAverage of three numbers is: %f", avg);
return 0;
}
Question 139
Question:
Write a program to read integer "n" and print first three powers (n1, n2, n3).
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
C Program:
#include<stdio.h>
int main()
{ The fprintf function writes the text C
FILE *fp;
fp = fopen("myfiles.txt","w"); Programming to the file myfiles.txt.
fprintf(fp, "%s", "C Programming");
return 0;
}
444
#include<bits/stdc++.h>
int main() {
swap(a, b);
return 0;
Output:
Value of a: 15
Value of b: 25
445
C++ Exercises
In the 1970s, Bjarne Stroustrup, a Danish computer scientist, created the C++ programming
language. The initial name of C++ was "C with classes." By practicing C++ programs, you can
learn the C++ programming language most effectively. An all-purpose programming language is
C++. It offers facilities for low-level memory manipulation together with imperative, object-
oriented, and generic programming features. It is used to create machine learning tools, web
browsers, video games, and operating systems. Examples on fundamental C++ ideas can be
found on this chapter. It is encouraged that you use the programs as references and test the
concepts on your own. Exercises in C++ are a great way to practise programming, develop your
446
Question 1
Question:
Solution: #include<iostream>
Albert Einstein
Question 2
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
447
int height = 8;
int width = 5;
int perimeter = 2*(height + width);
cout<<"Perimeter of the rectangle is: " << perimeter << " cm\n";
int area = height * width;
cout<<"Area of the rectangle is: "<< area << " square cm\n";
return 0;
}
Question 3
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int radius = 4;
float perimeter = 2*3.14*radius;
cout<<"Perimeter of the circle is: " << perimeter << " cm\n";
float area = 3.14*radius*radius;
cout<<"Area of the circle is: "<< area << " square cm\n";
return 0;
}
448
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
#include<iostream>
int main() {
Solution:
int x= 26; // Now x is 15
x = 56; // Now x is 10
#include<iostream>
using namespace std; cout << x;
449
Question 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;
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;
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:
Solution: #include<iostream>
Question 10
Question:
Solution:
454
#include<iostream>
#include<cmath>
using namespace std;
int main() { #include<iostream>
int a, b;
#include<cstring>
a=2;
using namespace std;
b = pow((a), 2);
cout<<"The square of a is: "<< b; int main() {
return 0; string x = "Albert";
}
cout << x[0];
// Output: A
return 0;
Question 11
}
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
a = 2;
b = 3;
if(a>b) {
cout<<"a is greater than b";
}
else {
455
cout<<"b is greater than a";
}
return 0;
}
Question 12
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, avg, sum = 0;
int num [5] = {16, 18, 20, 25, 36};
for(i=0; i<5; i++) {
sum = sum + num [i];
avg = sum/5;
}
cout<<"\nSum of the Elements in the array is: "<< sum;
cout<<"\nAverage of the elements in the array is: " << avg;
return 0;
}
456
Question 13
Question:
Write a program that prints all even numbers between 1 and 25.
Solution:
#include<iostream>
using namespace std;
int main() {
cout<<"Even numbers between 1 to 25:\n"; #include<iostream>
for(int i = 1; i <= 25; i++) {
#include<cstring>
if(i%2 == 0) {
using namespace std;
cout<< i << endl;
} int main() {
} string x = "Albert";
return 0;
x[0] = 'E';
}
cout << x;
// Output: Elbert
return 0;
Question 14
}
Question:
Write a program that prints all odd numbers between 1 and 50.
Solution:
457
#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
Solution:
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=10; i++) {
cout<<"Number = " << i << " its square = " << i*i << " its cube = " << i*i*i
<<endl;
}
return 0;
458
}
Question 16
#include<iostream>
// Output: 60
return 0;
Solution:
}
#include<iostream>
using namespace std;
int main() {
char M;
cout<<"Enter any character: ";
cin>>M;
cout<<"ch = "<< M;
return 0;
}
Question 17
Question:
Write a program to print the multiplication table of a number entered by the user.
459
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:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, product = 1;
for(i=1; i<=10; i++) {
product = product * i;
460
}
cout<<"The product of the first 10 digits is: " << product;
return 0;
}
Question 19
Question:
Solution:
#include<iostream>
using namespace std;
#include<iostream>
int main() {
int a; #include<cmath>
// Output: 1.38629
return 0;
461
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"Enter the first number: ";
cin>>x;
cout<<"Enter the second number: ";
cin>>y;
if(x-y==0) {
cout<<"The two numbers are equivalent";
}
else {
cout<<"The two numbers are not equivalent"; #include<iostream>
// Output: 1
return 0;
462
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b, c;
cout<<"Enter the first number: ";
cin>>a;
cout<<"Enter the second number: ";
cin>>b;
c = a % b;
cout<<"The remainder of " << a << " and " << b << " = " << c;
return 0;
}
Question 22
Question:
463
Solution: #include<iostream>
#include<cstring>
#include<iostream>
using namespace std;
using namespace std;
int main() {
char i; void myfunc(string name, int age) {
for(i='A'; i<='Z'; i++) {
cout << name << " John. " << age << " years old. \n";
cout << i << endl;
}
}
return 0;
} int main() {
myfunc("Albert", 73);
myfunc("Elsa", 14);
myfunc("David", 30);
Question 23
return 0;
Question: }
Solution:
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char str[1000];
cout<<"Enter a string to calculate its length: ";
cin>>str;
cout<<"The length of the entered string is: "<< strlen(str);
return 0;
464
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
if(islower(ch))
cout<<"The given character is a lower case letter";
else
cout<<"The given character is a upper case letter";
return 0;
}
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
465
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'A';
if(isupper(ch))
cout<<"The given character is a upper case letter";
else
cout<<"The given character is a lower case letter";
return 0;
}
Question 26
Question:
Write a program to convert the lower case letter to upper case letter.
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
char b = toupper(ch);
466
cout<<"Lower case letter "<<ch<<" is converted to Upper case letter "<<b;
return 0;
}
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches.
Solution:
#include<iostream>
using namespace std;
#define x 2.54
int main() {
double inch, cm;
cout<<"Enter the distance in cm: ";
cin>>cm;
inch = cm / x;
cout<<"\nDistance of "<< cm << " cms is equal to " << inch << " inches";
return 0;
}
467
Question 28
Question:
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:
Solution:
#include<iostream>
using namespace std;
int main() {
for(int i=1; i<=10; i++) {
cout<< "Hello World"<< endl;
}
return 0;
}
Question 30
Question:
Solution:
#include<iostream>
using namespace std;
469
int main() {
int i =1;
do {
cout<<" \ni = "<< i++;
} while(i<=5);
return 0;
}
Question 31
Question:
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:
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:
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:
descending order.
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
cout<<"\nEnter a pair of numbers (for example 22,12 | 12,22): ";
cout<<"\nEnter the first number: ";
473
cin>>a;
cout<<"\nEnter the second number: ";
cin>>b;
if (a>b) {
cout<<"\nThe two numbers in a pair are in descending order.";
}
else {
cout<<"\nThe two numbers in a pair are in ascending order.";
}
return 0;
}
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
Solution:
#include<iostream>
using namespace std;
int main() {
int a, b;
float c;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
474
cin>>b;
if(b != 0) {
c = (float)a/(float)b;
cout<<a<<"/"<<b<<" = "<< c;
}
else {
cout<<"\nDivision not possible.\n";
}
return 0;
}
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, i;
cout<<"Enter a number: ";
cin>>x;
for(i=1; i<=50; i++) {
if((i%x)==2 || (i%x) == 3) {
cout<<i<<endl;
475
}
}
return 0;
}
Question 38
Question:
Write a program that adds up all numbers between 1 and 100 that are not divisible by 12.
Solution:
#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:
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:
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:
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:
485
Solution:
#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter the integer from keyboard: ";
cin>>x;
cout<<"\nEntered value: "<< x;
cout<<"\nThe left shifted data is: " << (x<<=2);
return 0;
}
Question 50
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x;
cout<<"Enter the integer from keyboard: ";
cin>>x;
486
cout<<"\nEntered value: "<< x;
cout<<"\nThe right shifted data is: " << (x>>=2);
return 0;
}
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
the absolute difference if x is greater than 21.
#include<iostream>
487
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
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:
using structures.
int myfunc(int x) {
return 15 + x;
}
Solution:
#include<iostream>
int main() {
using namespace std;
int main() { cout << myfunc(13);
489
Question 54
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float fahrenheit, celsius;
celsius = 36;
fahrenheit = ((celsius*9)/5)+32;
cout<<"\nTemperature in fahrenheit is: "<<fahrenheit;
return 0;
}
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
is 50 or if their sum is 50.
490
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
if(x == 50 || y == 50 || (x + y == 50)){
cout<<"\nTrue";
}
else {
cout<<"\nFalse";
}
return 0;
}
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
#include<iostream>
491
using namespace std;
int main () {
int x, even = 0, odd = 0, positive = 0, negative = 0;
cout<<"\nPlease enter 18 numbers: \n";
for(int i = 0; i < 18; i++) {
cin>>x;
if (x > 0) {
positive++;
}
if(x < 0) {
negative++;
}
if(x % 2 == 0) {
even++;
}
if(x % 2 != 0) {
odd++;
}
}
cout<<"\nNumber of even values: "<<even;
cout<<"\nNumber of odd values: "<<odd;
cout<<"\nNumber of positive values: "<<positive;
cout<<"\nNumber of negative values: "<<negative;
return 0;
}
492
Question 57
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
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
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:
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:
#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:
#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:
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
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:
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
Solution:
514
#include<iostream>
using namespace std;
int main() {
int x, y, z;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
cout<<"\nEnter the value for z: ";
cin>>z;
if(x == y + z || y == x + z || z == x + y) {
cout<<"True";
}
else {
cout<<"False";
}
return 0;
}
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
#include<iostream>
515
using namespace std;
int main() {
float kmph;
cout<<"Enter kilometers per hour: ";
cin>>kmph;
cout<<(kmph * 0.6213712)<<" miles per hour";
return 0;
}
Question 75
Question:
Solution:
#include<iostream>
using namespace std;
#define PI 3.141592
int main() {
float major, minor;
cout<<"\nEnter length of major axis: ";
cin>>major;
cout<<"\nEnter length of minor axis: ";
cin>>minor;
cout<<"\nArea of an ellipse = "<< (PI * major * minor);
return 0;
}
516
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
first two values are equal.
Solution:
#include<iostream>
using namespace std;
int myfunc();
int myfunc(int a, int b, int c) {
#include<iostream>
if (a == b && b == c) return 0;
#include<cstring>
if (a == b) return c;
if (a == c) return b; using namespace std;
if (b == c) return a;
else return a + b + c;
void myfunc(string x= "John") {
}
int main() { cout << x;
return 0;
517
Question 77
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int bytes;
cout<<"\nEnter number of bytes: ";
cin>>bytes;
cout<<"\nKilobytes: "<<(bytes/1024);
return 0;
}
Question 78
Question:
Solution:
518
#include<iostream>
using namespace std;
int main() {
double megabytes, kilobytes;
cout<<"\nInput the amount of megabytes to convert: ";
cin>>megabytes;
kilobytes = megabytes * 1024;
cout<<"\nThere are "<<kilobytes<< " kilobytes in " <<megabytes<< "
megabytes.";
return 0;
}
Question 79
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int array[1000], i, arr_size, even=0;
cout<<"Input the size of the array: ";
cin>>arr_size;
cout<<"Enter the elements in array: \n";
for(i=0; i<arr_size; i++) {
cin>>array[i];
519
}
Question 80
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int array[1000], i, arr_size, odd=0;
cout<<"Input the size of the array: ";
cin>>arr_size;
cout<<"Enter the elements in array: \n";
for(i=0; i<arr_size; i++) {
cin>>array[i];
520
}
Question 81
Question:
Write a program that will accept two integers and determine whether or not they are
equal.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"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:
Solution:
#include<iostream>
using namespace std;
int main() {
int year;
cout<<"Enter the year: ";
cin>>year;
if((year % 400) == 0) {
cout<<year<<" is a leap year.";
}
else if((year % 100) == 0) {
cout<<year<<" is a not leap year.";
}
else if((year % 4) == 0) {
cout<<year<<" is a leap year.";
}
else {
cout<<year<<" is not a leap year.";
}
return 0;
}
523
Question 84
Question:
Write a program that reads the candidate's age and determine a candidate's eligibility to
cast his own vote.
Solution:
#include <iostream>
using namespace std;
int main() {
int age;
cout<<"\nEnter the age of the candidate: ";
cin>>age;
if(age<18) {
cout<<"\nWe apologize, but the candidate is not able to cast his vote.";
cout<<"\nAfter "<< (18-age) <<" year, the candidate would be able to cast his
vote.";
}
else {
cout<<"Congratulation! the candidate is qualified to cast his vote.\n";
}
return 0;
}
524
Question 85
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float yard;
cout<<"\nEnter the Length in Yard: ";
cin>>yard;
cout<<yard<<" Yard in Foot is: "<<(3*yard);
return 0;
}
Question 86
Question:
Solution:
525
#include<iostream>
using namespace std;
int main() {
double gigabytes, megabytes;
cout<<"\nInput the amount of gigabytes to convert: ";
cin>>gigabytes;
megabytes = gigabytes*1024;
cout<<"\nThere are "<<megabytes<<" megabytes in "<<gigabytes<<" gigabytes.";
return 0;
}
Question 87
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float kg, lbs;
cout<<"\nEnter Weight in Kilogram: ";
cin>>kg;
lbs = kg*2.20462;
cout<<kg<<" Kg = "<<lbs<<" Pounds";
return 0;
526
}
Question 88
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
float kg, ounce;
cout<<"\nEnter Weight in Kilogram: ";
cin>>kg;
ounce = kg*35.274;
cout<<kg<<" Kg = "<<ounce<< " Ounce";
return 0;
}
Question 89
Question:
527
Solution:
#include<iostream>
using namespace std;
int main() {
float pound, gram;
cout<<"\nEnter Weight in Pounds: ";
cin>>pound;
gram = pound*453.592;
cout<<pound<<" Pound = "<<gram<<" Grams";
return 0;
}
Question 90
Question:
Solution:
#include <iostream>
using namespace std;
int main() {
int angle1, angle2, angle3, sum;
cout<<"\nEnter the first angle of the triangle: ";
cin>>angle1;
528
cout<<"\nEnter the second angle of the triangle: ";
cin>>angle2;
cout<<"\nEnter the third angle of the triangle: ";
cin>>angle3;
sum = 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:
Solution:
#include<iostream>
using namespace std;
int main() {
char ch;
cout<<"\nEnter a character: ";
cin>>ch;
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
cout<<ch<<" is a vowel";
}
else {
530
cout<<ch<<" is a consonant";
}
return 0;
}
Question 93
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, fact=1, num;
cout<<"\nEnter a number: ";
cin>>num;
for(i=1; i<=num; i++) {
fact=fact*i;
}
cout<<"\nFactorial of "<<num<<" is: "<<fact;
return 0;
}
531
Question 94
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x[12]={31,28,31,30,31,30,31,31,30,31,30,31}, m;
cout<<"\nEnter the month number: ";
cin>>m;
if(m>12 || m<1) {
cout<<"Invalid input";
}
else if(m==2) {
cout<<"\nNumber of days in month 2 is either 29 or 28";
}
else {
cout<<"\nNumber of days in month "<<m<< " is: "<<x[m-1];
}
return 0;
}
532
Question 95
Question:
Solution:
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char a[1000], b[1000];
cout<<"\nEnter the first string: ";
cin>>a;
cout<<"\nEnter the second string: ";
cin>>b;
strcat(a, b);
cout<<"\nString produced by concatenation is: "<< a;
return 0;
}
Question 96
Question:
533
Solution:
#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:
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:
Solution:
#include<iostream>
537
using namespace std;
int main() {
int pwd, i;
while (i!=0) {
cout<<"\nEnter the password: ";
cin>>pwd;
if(pwd==1988) {
cout<<"The password you entered is correct";
i=0;
}
else {
cout<<"Incorrect password, try again";
}
cout<<"\n";
}
return 0;
}
Question 102
Question:
Solution:
#include<iostream>
using namespace std;
538
int main() {
int num;
cout<<"Input a positive or negative number: \n";
cin>>num;
cout<<"\nAbsolute value of "<<"|"<<num<<"|"<<" is: "<<abs(num);
return 0;
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
#include<iostream>
using namespace std;
int main() {
float ht;
cout<<"\nEnter the height (in cm): ";
cin>>ht;
if(ht < 150.0) {
cout<<"Dwarf.\n";
}
else if((ht >= 150.0) && (ht < 165.0)) {
cout<<"Average Height.\n";
539
}
else if((ht >= 165.0) && (ht <= 195.0)) {
cout<<"Taller.\n";
}
else {
cout<<"Abnormal height.\n";
}
return 0;
}
Question 104
Question:
Write a program to calculate the area of different geometric shapes using switch
statements.
Solution:
#include<iostream>
using namespace std;
int main() {
int choice;
float r, l, w, b, h;
cout<<"\nEnter 1 for area of circle: ";
cout<<"\nEnter 2 for area of rectangle: ";
cout<<"\nEnter 3 for area of triangle: ";
cout<<"\nEnter your choice : ";
cin>>choice;
540
switch(choice) {
case 1:
cout<<"Enter the radius of the circle: ";
cin>>r;
cout<<"\nArea of a circle is: " << (3.14*r*r);
break;
case 2:
cout<<"Enter the length and width of the rectangle: \n";
cin>>l;
cin>>w;
cout<<"\nArea of a rectangle is: "<<(l*w);
break;
case 3:
cout<<"Enter the base and height of the triangle: \n";
cin>>b;
cin>>h;
cout<<"\nArea of a triangle is: "<<(0.5*b*h);
break;
default:
cout<<"\nPlease enter a number from 1 to 3.";
break;
}
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:
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:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, num, sum=0;
cout<<"Enter a number: ";
cin>>num;
for(i=2; i<=num; i=i+2) {
sum = sum + i;
}
cout<<"\nSum of all even number between 1 to " <<num<< " is: "<< sum;
return 0;
}
546
Question 111
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i, num, sum=0;
cout<<"Enter a number: ";
cin>>num;
for(i=1; i<=num; i=i+2) {
sum = sum + i;
}
cout<<"\nSum of all odd number between 1 to " <<num<< " is: "<< sum;
return 0;
}
Question 112
Question:
547
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
cout<<"Enter any two numbers: \n";
cin>>x;
cin>>y;
switch(x > y) {
case 0: cout<<y<<" is Maximum number";
break;
case 1: cout<<x<<" is Maximum number";
break;
}
return 0;
}
Question 113
Question:
Write a program that allows you to enter the cost price and the selling price of a product
Solution:
#include<iostream>
548
using namespace std;
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:
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x;
cout<<"Enter any number: ";
cin>>x;
cout<<"Square root of "<<x<< " is: "<<(double)sqrt(x);
return 0;
}
Question 119
Question:
553
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int x, y;
cout<<"\nEnter the value for x: ";
cin>>x;
cout<<"\nEnter the value for y: ";
cin>>y;
cout<<x<<"A"<<y<<" = " << (long)pow(x,y);
return 0;
}
Question 120
Question:
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:
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:
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:
Solution:
#include<iostream>
using namespace std;
int main() {
int i;
for(i = 1; i <= 127; i++)
if(isprint(i)!= 0)
cout<<" "<<char(i);
return 0;
}
Question 125
Question:
Write a program to check whether the entered character is a hexadecimal digit character
or not.
Solution:
558
#include<iostream>
using namespace std;
int main() {
char a;
cout<<"Enter a character: ";
cin>>a;
if(isxdigit(a)) {
cout<<a<<" is a hexadecimal digit character.";
}
else {
cout<<a<<" is NOT a hexadecimal digit character.";
}
return 0;
}
Question 126
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int i;
cout<<"The ASCII value of all control characters are: \n";
559
for(i=0; i<=127; i++) {
if(iscntrl(i)!=0) #include<iostream>
cout<<"\n "<< i;
#include<cstring>
}
using namespace std;
return 0;
} int main() {
string x = "Joe"; ?
string* ptr = &x;
}
Question:
Write a program to check whether the given character is a white-space character or not.
Solution:
#include <iostream>
using namespace std;
int main() {
char c;
char ch = ' ';
if(isspace(ch)) {
cout << "\nNot a white-space character.";
}
else {
cout << "\nWhite-space character.";
}
return 0;
560
}
Question 128
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
if(isprint(ch)) {
cout<<ch<<" is printable character."<<endl;
}
else {
cout<<ch<<" is not printable character."<<endl;
}
if(iscntrl(ch)) {
cout<<ch<<" is control character."<<endl;
}
else {
cout<<ch<<" is not control character."<<endl;
}
return (0);
561
}
Question 129
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int side;
long area;
cout<<"\nEnter the side of cube: ";
cin>>side;
area = 6*side*side;
cout<<"\nThe surface area of cube is: "<< area;
return 0;
}
Question 130
Question:
562
Solution:
#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x+(~y)+1;
return 0;
}
Question 131
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int x =6, y=3;
cout<<x-(~y)-1;
return 0;
}
563
Question 132
Question:
#include<iostream>
Solution:
#include<cstring>
#include<iostream>
using namespace std; using namespace std;
int main() {
int main() {
int x=2;
cout<< (x<<1); string x[5] = {"Albert", "John", "Mary", "James"};
return 0;
x[0] = "Joe";
}
cout << x[0]; // Output: Joe
return 0;
Question 134
}
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
564
int x=12;
cout<< (x>>1);
return 0;
}
Question 135
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int radius;
float PI = 3.141592;
cout<<"\nEnter the radius of sphere: ";
cin>>radius;
float volume = (4/3)*(PI*radius*radius*radius);
cout<<"\nThe volume of sphere is: "<< volume;
return 0;
}
565
Question 136
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int r1, r2, r3;
float PI = 3.141592;
cout<<"\nEnter the radius of the ellipsoid of axis 1: ";
cin>>r1;
cout<<"\nEnter the radius of the ellipsoid of axis 2: ";
cin>>r2;
cout<<"\nEnter the radius of the ellipsoid of axis 3: ";
cin>>r3;
float volume = (4/3)*(PI*r1*r2*r3);
cout<<"\nThe volume of ellipsoid is: "<< volume;
return 0;
#include<iostream>
#include<cstring>
int main() {
return 0;
566
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
#include<iostream>
using namespace std;
int main() {
int x, y;
#include<iostream>
long power = 1;
cout<<"\nEnter the value for x: "; #include<cstring>
cin>>x; using namespace std;
cout<<"\nEnter the value for y: ";
cin>>y;
for(int i=1; i<=y; i++) { int main() {
// Output: Albert
return 0;
567
Question 138
Question:
Solution:
#include<iostream>
using namespace std;
int main() {
int a,b,c;
float avg;
cout<<"\nEnter the first number: ";
cin>>a;
cout<<"\nEnter the second number: ";
cin>>b;
cout<<"\nEnter the third number: ";
cin>>c;
avg=(a+b+c)/3.0;
cout<<"\nAverage of three numbers is: "<< avg;
return 0;
}
Question 139
Question:
Write a program to read integer "n" and print first three powers (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>
#include<cstring>
int main() {
using namespace std;
string i[2][4] = {
return 0;
cout << i[0][2];
}
// Output: B
return 0;
569
#include<iostream>
int main() {
string y="programming";
x.append(y);
cout<<" \n "<<x<<'\n';
return 0;
#include<iostream>
// Output: A cout<<x;
} return 0;
// Output: J language
570
#include<iostream>
int main() {
x.erase(8,1);
cout<<x;
return 0;
#include<iostream>
#include<cstring>
int main() {
cout << "The length of the text string is: " << txt.size();
return 0;
571
#include<iostream>
#include<cstring>
int main() {
cout << "The length of the text string is: " << txt.length();
return 0;
#include<iostream>
int main() {
x.erase(x.begin()+0);
cout<<x;
// Output: ++ programming
return 0;
572
C++ Program:
#include<bits/stdc++.h>
using namespace std;
int main()
{ Output:
float a =2.33333;
2
cout << floor(a) << endl;
cout << ceil(a) << endl;
3
cout << trunc(a) << endl;
cout << round(a) << endl; 2
cout << setprecision(2) << a;
return 0; 2
}
2.3
C++ Program:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
Output:
{
float a = -43; 43
cout << abs(a) << endl;
cout << labs(a) << endl; 43
cout << llabs(a)<< endl;
43
return 0;
}
573
JDK JRE JVM
It is the tool necessary to compile, It provides the class libraries and A virtual machine that enables a
document and package Java other resources that a specific Java computer to run Java programs
Inheritance Abstraction
acquires the properties of another implementation details from the user and
only providing the functionality to the
users.
Encapsulation
Polymorphism
574
Java Exercises
Java is the mainstream technology for creating and delivering embedded and mobile software,
games, Internet entertainment, and business software. It serves as the foundation for almost any
sort of networked application. With over 9 million developers across the globe, Java makes it
simple to quickly create, distribute, and use new apps and services. Around 1992, James
Gosling was employed by Sun Labs. A set-top box was being built by Gosling and his team,
who began by "cleaning up" C++ and ultimately came up with a new language and runtime. As a
result, Java or Oak was created. C continues to be the top option among developers when it
comes to programming languages. However, Java is more popular among developers than C. The
second most popular programming language is Java. The common reason for this is because it
facilitates the creation of sophisticated applications that operate well and satisfactorily. In
addition, Java may be installed and operated on any platform. Approximately 3 billion mobile
phones, 125 million TV sets, and every Blu-Ray player currently use Java. You can learn Java
programming and advance your skills by practicing and working through problems. If you learn
best "by example," this is the chapter for you.
575
Question 1
Question:
Solution:
Question 2
Question:
Solution:
576
int perimeter = 2 * (height + width);
System.out.println("Perimeter of the rectangle is: " + perimeter + " cm");
int area = height * width;
System.out.println("Area of the rectangle is: " + area + " square cm");
}
}
Question 3
Question:
Solution:
int x = 65;
x = 80;
System.out.println(x); // Output: 80
577
Question 4
Question:
Write a program that accepts two numbers from the user and calculate the sum of the two
numbers.
Solution:
import java.util.Scanner;
String x = "Einstein";
}
// Output: Albert Einstein
}
578
Question 5
Question:
Write a program that accepts two numbers from the user and calculate the product of the
two numbers.
Solution:
import java.util.Scanner;
Question 6
Question:
Write a program that accepts three numbers and find the largest of three.
579
Solution:
import java.util.Scanner;
580
Question 7
Question:
Write a program that reads three floating values and check if it is possible to make a
triangle with them. Also calculate the perimeter of the triangle if the entered values are
valid.
Solution:
import java.util.Scanner;
581
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 8
Question:
Write a program that reads an integer between 1 and 7 and print the day of the week in
English.
Solution:
import java.util.Scanner;
582
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.print("Enter a number between 1 to 7.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 9
Question:
583
Solution:
Question 10
Question:
Solution:
584
Question 11
Question:
Solution:
Question 12
Question:
585
Solution:
Question 13
Question:
Write a program that prints all even numbers between 1 and 25.
Solution:
586
if(i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
Question 14
Question:
Write a program that prints all odd numbers between 1 and 50.
Solution:
System.out.println(x);
}
// Output: 100
}
587
Question 15
Question:
Write a program to print the first 10 numbers starting from one together with their
squares and cubes.
Solution:
Question 16
Question:
Write a program:
If you enter a character M
588
Solution:
Question 17
Question:
Write a program to print the multiplication table of a number entered by the user.
Solution:
import java.util.Scanner;
589
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 18
Question:
Solution:
Question 19
Question:
590
Solution:
Question 20
Question:
Write a program to check the equivalence of two numbers entered by the user.
Solution:
import java.util.Scanner;
591
System.out.print("\nEnter the first number: ");
x = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second number: ");
y = STDIN_SCANNER.nextInt();
if(x - y == 0) {
System.out.print("\nThe two numbers are equivalent");
} else {
System.out.print("\nThe two numbers are not equivalent");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 21
Question:
Write a program to print the remainder of two numbers entered by the user.
Solution:
import java.util.Scanner;
592
b = STDIN_SCANNER.nextInt();
c = a % b;
System.out.print("\n The remainder of " + a + " and " + b + " is: " + c);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 22
Question:
Solution:
boolean x = true;
boolean y = false;
593
Question 23
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
String a;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Name : ");
a = scan.nextLine();
System.out.println("The length of the String is: " + a.length());
}
}
Question 24
Question:
Write a program to check whether the given character is a lower case letter or not.
Solution:
594
public class MyClass {
public static void main(String[] args) {
char ch = 'a';
if(Character.isLowerCase(ch)) {
System.out.println("The given character is a lower case letter");
}
else {
System.out.println("The given character is a upper case letter");
}
}
}
Question 25
Question:
Write a program to check whether the given character is a upper case letter or not.
Solution:
595
}
}
Question 26
Question:
Write a program to convert the lower case string to upper case string.
Solution:
Question 27
Question:
Write a program that takes a distance in centimeters and outputs the corresponding value
in inches.
596
Solution:
import java.util.Scanner;
Question 28
Question:
Einstein [0] = E
Einstein [1] = I
Einstein [2] = N
Einstein [3] = S
Einstein [4] = T
Einstein [5] = E
Einstein [6] = I
Einstein [7] = N
597
Solution:
}
}
}
598
Question 30
Question:
Solution:
Question 31
Question:
Solution:
599
import java.util.Scanner;
Question 32
Question:
Solution:
import java.util.Scanner;
600
a = STDIN_SCANNER.nextInt();
if(a % 2 == 0) {
System.out.print("The entered number is even");
} else {
System.out.print("The entered number is odd");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 33
Question:
Solution:
601
Question 34
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder will be 2.
Solution:
import java.util.Scanner;
602
Question 35
Question:
Solution:
import java.util.Scanner;
603
Question 36
Question:
Write a program that reads two numbers and divides one by the other. Specify "Division
not possible" if that is not possible.
Solution:
import java.util.Scanner;
604
Question 37
Question:
Write a program that will print all numbers between 1 to 50 which divided by a specified
number and the remainder is equal to 2 or 3.
Solution:
import java.util.Scanner;
double y = 9.78d;
int x = (int) y;
System.out.println(x); // Output: 9
605
Question 38
Question:
Write a program that adds up all numbers between 1 and 100 that are not divisible by 12.
Solution:
Question 39
Question:
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;
607
}
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 41
Question:
Write a program to find the incremented and decremented values of two numbers.
Solution:
608
Question 42
Question:
Solution:
import java.util.Scanner;
609
Question 43
Question:
Write a program that accepts principal amount, rate of interest, time and compute the
simple interest.
Solution:
import java.util.Scanner;
610
Question 44
Question:
Write a program that swaps two numbers without using third variable.
Solution:
import java.util.Scanner;
611
Question 45
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of a side of the hexagon: ");
double s = input.nextDouble();
double area = (6*(s*s))/(4*Math.tan(Math.PI/6));
System.out.print("The area of the hexagon is: " + area);
}
}
Question 46
Question:
body [o] = o
612
body [d] = d
body [y] = y
Solution:
Question 47
Question:
Write a program to calculate the discounted price and the total price after discount
Given:
If purchase value is greater than 1000, 10% discount
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:
614
public static void main(String[] args) { import java.util.ArrayList;
x.add("Mary");
System.out.println(x);
} u
Question 49
Question:
Solution:
import java.util.Scanner;
615
Question 50
Question:
Solution:
import java.util.Scanner;
Question 51
Question:
Write a program to calculate the exact difference between x and 21. Return three times
616
Solution:
import java.util.Scanner;
Question 52
Question:
Write a program that reads in two numbers and determine whether the first number is a
multiple of the second number.
Solution:
617
import java.util.Scanner;
Question 53
Question:
Solution:
618
System.out.format("\nCurrent Date time: %tc%n\n",
System.currentTimeMillis());
}
}
Question 54
Question:
Solution:
int y = 9;
double x = y;
619
Question 55
Question:
Write a program that will examine two inputted integers and return true if either of them
is 50 or if their sum is 50.
Solution:
import java.util.Scanner;
620
Question 56
Question:
Write a program that counts the even, odd, positive, and negative values among eighteen
integer inputs.
Solution:
import java.util.Scanner;
621
System.out.print("\nNumber of odd values: " + odd);
System.out.print("\nNumber of positive values: " + positive);
System.out.print("\nNumber of negative values: " + negative);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 57
Question:
import java.util.ArrayList;
Solution:
public class MyClass {
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
622
}
Question 58
Question:
Write a program that reads a student's three subject scores (0-100) and computes the
Solution:
import java.util.Scanner;
623
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 59
Question:
x.add("Joe");
x.add("Alan");
Solution:
x.add("Mary");
1 x.clear();
2
System.out.println(x);
// Output: []
624
public class MyClass {
public static void main(String[] args) {
System.out.println(-7 + 9 * 5);
System.out.println((68+7) % 8);
System.out.println(50 + -6*5 / 5);
System.out.println(6 + 25 / 3 * 6 - 8 % 2);
}
}
Solution:
38
3
44
54
Solution:
625
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
Solution:
2.010597302504817
626
Solution:
linux
} System.out.println("Access denied");
} else {
System.out.println("Access granted");
Solution:
}
1
}
2
public static void main(String[] args) {
4
myfunc(25); // Call the myfunc method and pass along an age of 25
5
}
627
}
}
Solution:
10
x.add("Albert");
x.add("Joe");
Solution: x.add("Alan");
x.add("Mary");
15
for(int i = 0; i < x.size(); i++) {
System.out.println(x.get(i));
628
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
System.out.print((i & 1) != 0 ? "odd\n" : "even\n");
}
System.exit(0);
}
}
Solution:
odd
even
odd
Solution:
629
|-2.50| = 2.50
} import java.util.Iterator;
}
x.add("John");
15
x.add("James");
x.add("Mary");
Iterator<String> it = x.iterator();
public class MyClass {
public static void main(String[] args) { System.out.println(it.next());
Solution:
630
15
Solution:
15
631
Solution:
Anyone who has never made a mistake has never tried anything new.
Anyone who has never made a mistake has never tried anything new.
Anyone who has never made a mistake has never tried anything new.
Question 60
Question:
Solution:
632
Question 61
Question:
Write a program that prints a sequence from 1 to a given integer, inserts a plus sign
between these numbers, and then removes the plus sign at the end of the sequence.
Solution:
import java.util.Scanner;
633
Question 62
Question:
Write a program to verify whether a triangle's three sides form a right angled triangle or
not.
Solution:
import java.util.Scanner;
634
Question 63
Question:
Write a program that will find the second-largest number among the user's input of three
numbers.
Solution:
import java.util.Scanner;
635
System.out.print("\n" + c + " is second largest number among three
numbers");
} else {
System.out.print("\n" + a + " is second largest number among
three numbers");
}
} else if(a > b) {
System.out.print("\n" + a + " is second largest number among three
numbers");
} else {
System.out.print("\n" + b + " is second largest number among three
numbers");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 64
Question:
Write a program to calculate the sum of the two given integer values. Return three times
the sum of the two values if they are equal.
Solution:
636
System.out.print("\n" + myfunc(6, 6));
}
public static int myfunc(int a, int b) {
return a == b ? (a + b) * 3 : a + b;
}
}
Question 65
Question:
Write a program that accepts minutes as input, and display the total number of hours and
minutes.
Solution:
import java.util.Scanner;
637
Question 66
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five.
Solution:
import java.util.Scanner;
638
Question 67
Question:
Write a program to verify whether one of the two entered integers falls within the range
of 100 to 200 included.
Solution:
import java.util.Scanner;
639
Question 68
Question:
Write a program to determine which of the two given integers is closest to the value 100.
If the two numbers are equal, return 0.
Solution:
int a = 15;
int b = 13;
System.out.println(a == b);
640
Question 69
Question:
Write a program to determine whether a positive number entered by the user is a multiple
of three or five, but not both.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
int x;
System.out.print("\nEnter a number: ");
x = STDIN_SCANNER.nextInt();
if(x % 3 == 0 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 {
int x = 15;
641
Question 70
Question:
Write a program to determine whether two entered non-negative numbers have the same
last digit.
Solution:
import java.util.Scanner;
642
Question 71
Question:
import java.util.ArrayList;
System.out.print("False"); for(int i : x) {
}
System.out.println(i);
} } 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;
Question 73
Question:
Write a program to check whether it is possible to add two integers to get the third
integer from three entered integers.
Solution:
644
import java.util.Scanner;
Question 74
Question:
Write a program that converts kilometers per hour to miles per hour.
Solution:
645
import java.util.Scanner;
Question 75
Question:
Solution:
import java.util.Scanner;
646
minor = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of an ellipse = %.4f", PI * major * minor);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 76
Question:
Write a program to calculate the sum of three given integers. Return the third value if the
Solution:
647
import java.util.ArrayList;
if(a == c) {
public class MyClass {
return b;
public static void main(String[] args) {
}
if(b == c) { ArrayList<String> x = new ArrayList<String>();
return a; x.add("Apple");
} else {
x.add("Lemon");
return a + b + c;
x.add("Kiwi");
}
x.add("Orange");
}
} for(String i : x) {
System.out.println(i);
}
Question 77
}
Question:
Solution:
import java.util.Scanner;
648
}
Question 78
Question:
Solution:
import java.util.Scanner;
649
Question 79
Question:
Solution:
import java.util.Scanner;
650
Question 80
Question:
Solution:
import java.util.Scanner;
651
}
Question 81
Question:
Write a program that will accept two integers and determine whether or not they are
equal.
Solution:
import java.util.Scanner;
652
Question 82
Question:
Write a program to find the third angle of a triangle if two angles are given.
Solution:
import java.util.Scanner;
Question 83
Question:
653
Solution:
import java.util.Scanner;
Question 84
Question:
Write a program that reads the candidate's age and determine a candidate's eligibility to
cast his own vote.
654
Solution:
import java.util.Scanner;
Question 85
Question:
655
Solution:
import java.util.Scanner;
Question 86
Question:
Solution:
import java.util.Scanner;
656
megabytes = gigabytes * 1_024;
System.out.printf("\nThere are %f megabytes in %f gigabytes.", megabytes,
gigabytes);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 87
Question:
Solution:
import java.util.Scanner;
657
Question 88
Question:
Solution:
import java.util.Scanner;
Question 89
Question:
658
Solution:
import java.util.Scanner;
Question 90
Question:
Solution:
import java.util.Scanner;
659
int angle1, angle2, angle3, sum;
System.out.print("\nEnter the first angle of the triangle: ");
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;
660
int x, y, sum = 0;
System.out.print("\nEnter a two-digit number: ");
x = STDIN_SCANNER.nextInt();
y = x;
while(y != 0) {
sum = sum + y % 10;
y = y / 10;
}
System.out.print("\nSum of digits of " + x + " is: " + sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 92
Question:
Solution:
import java.util.Scanner;
661
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'a' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) {
System.out.println(ch + " is vowel");
}
else {
System.out.println(ch + " is consonant");
import java.util.ArrayList;
}
public class MyClass {
}
} public static void main(String[] args) {
x.add("Apple");
x.add("Lemon");
x.add("Kiwi");
Question 93
x.add("Mango");
System.out.println(x.size());
Question:
// Output: 4
Write a program to find factorial of a number.
}
Solution:
import java.util.Scanner;
662
}
System.out.print("\nFactorial of " + num + " is: " + fact);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 94
Question:
Solution:
import java.util.Scanner;
663
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 95
Question:
Solution:
}
String y = x.toString();
}
System.out.println(y.length());
// Output: 5
Question 96 }
}
Question:
664
Solution:
import java.util.Scanner;
665
Question 97
Question:
Solution:
666
}
else {
System.out.println("The 2 strings are not equal.");
}
}
}
Question 98
Question:
Write a program to convert the upper case string to lower case string.
Solution:
String a = "20";
int b = 30;
String c = a + b;
667
Question 99
Question:
Write a program to find the quotient and remainder of a entered dividend and divisor.
Solution:
import java.util.Scanner;
Question 100
Question:
Write a program to determine the Size of int, float, double and char.
668
Solution:
Question 101
Question:
Solution:
import java.util.Scanner;
669
inputPass = input.nextLine();
if (inputPass.equals(password)) {
System.out.println("Welcome User!");
}
else {
for(int i = 0; i < 3; i++) {
System.out.println("Enter Your Password:");
inputPass = input.nextLine();
}
System.out.println("Access Denied! Try again");
}
}
}
Question 102
Question:
Solution:
import java.util.Scanner;
670
num = STDIN_SCANNER.nextInt();
System.out.println("\nAbsolute value of |" + num + "| is " + Math.abs(num));
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
public class MyClass {
public static void main(String args[]) {
int x = 820;
int y = -985;
float z = -8.1f;
System.out.printf( "Absolute Value of x: %d \n", Math.abs(x) );
System.out.printf( "Absolute Value of y: %d \n", Math.abs(y) );
System.out.printf( "Absolute Value of z: %f \n", Math.abs(z) );
}
}
Question 103
Question:
Write a program that will accept a person's height in cm and classify the person based on
it.
Solution:
import java.util.Scanner;
671
float ht;
System.out.print("\nEnter the height (in cm): ");
ht = STDIN_SCANNER.nextFloat();
if(ht < 150.0) {
System.out.println("Dwarf.");
} else if(ht >= 150.0 && ht < 165.0) {
System.out.println("Average Height.");
} else if(ht >= 165.0 && ht <= 195.0) {
System.out.println("Taller.");
} else {
System.out.println("Abnormal height.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 104
Question:
Write a program to calculate the area of different geometric shapes using switch
statements.
Solution:
import java.util.Scanner;
672
int choice;
float r, l, w, b, h;
System.out.print("\nEnter 1 for area of circle: ");
System.out.print("\nEnter 2 for area of rectangle: ");
System.out.print("\nEnter 3 for area of triangle: ");
System.out.print("\nEnter your choice : ");
choice = STDIN_SCANNER.nextInt();
switch(choice) {
case 1:
System.out.print("Enter the radius of the circle: ");
r = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a circle is: %f", 3.14 * r * r);
break;
case 2:
System.out.println("Enter the length and width of the rectangle: ");
l = STDIN_SCANNER.nextFloat();
w = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a rectangle is: %f", l * w);
break;
case 3:
System.out.println("Enter the base and height of the triangle: ");
b = STDIN_SCANNER.nextFloat();
h = STDIN_SCANNER.nextFloat();
System.out.printf("\nArea of a triangle is: %f", 0.5 * b * h);
break;
default:
System.out.print("\nPlease enter a number from 1 to 3.");
break;
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
673
}
Question 105
Question:
Write a program to accept a character from the keyboard and print "Yes" if it is equal to y.
Solution:
System.out.println(Math.random());
674
Question 106
Question:
Write a program that uses bitwise operators to multiply an entered value by four.
Solution:
import java.util.Scanner;
Question 107
Question:
Write a program to check whether a number entered by the user is power of 2 or not.
675
Solution:
import java.util.Scanner;
Question 108
Question:
Solution:
import java.util.Scanner;
676
public class MyClass {
public static void main(String[] args) {
int side1, side2, side3;
System.out.print("\nEnter the first side of the triangle: ");
side1 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the second side of the triangle: ");
side2 = STDIN_SCANNER.nextInt();
System.out.print("\nEnter the third side of the triangle: ");
side3 = STDIN_SCANNER.nextInt();
if(side1 == side2 && side2 == side3) {
System.out.print("\nThe given Triangle is equilateral.");
} else if(side1 == side2 || side2 == side3 || side3 == side1) {
System.out.print("\nThe given Triangle is isosceles.");
} else {
System.out.print("\nThe given Triangle is scalene.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 109
Question:
Write a program to print ASCII values of all the letters of the English alphabet from A to Z.
677
Solution:
Question 110
Question:
Solution:
import java.util.Scanner;
678
System.out.print("\nSum of all even number between 1 to " + num + " is: " +
sum);
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 111
Question:
Solution:
import java.util.Scanner;
679
Question 112
Question:
Write a program that accepts an integer (x) and computes the value of x+xx+xxx.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
int x;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
x = in .nextInt();
System.out.printf("%d + %d%d + %d%d%d\n", x, x, x, x, x, x);
}
}
Question 113
Question:
Write a program that allows you to enter the cost price and the selling price of a product
and calculate profit or loss.
680
Solution:
import java.util.Scanner;
Question 114
Question:
Write a program that display the pattern like a right angle triangle using an asterisk.
681
Solution:
import java.util.Scanner;
Question 115
Question:
Write a program that display the pattern like a right angle triangle using a number.
Solution:
682
import java.util.Scanner;
Question 116
Question:
Write a program to determine the number and sum of all integers between 50 and 100
Solution:
683
int sum = 0;
System.out.println("Numbers between 50 and 100, divisible by 2: ");
for(int x = 51; x < 100; x++) {
if(x % 2 == 0) {
System.out.printf("%5d", x);
sum += x;
}
}
System.out.print("\nThe sum: " + sum);
}
}
Question 117
Question:
Write a program that uses the function to determine whether an entered number is even
or odd.
Solution:
import java.util.Scanner;
684
int x;
System.out.print("Enter any number: ");
x = STDIN_SCANNER.nextInt();
if(myfunc(x) != 0) {
System.out.print("\nThe number you entered is odd.");
} else {
System.out.print("\nThe number you entered is even.");
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 118
Question:
Solution:
import java.util.Scanner;
685
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}
Question 119
Question:
Solution:
import java.util.Scanner;
686
Question 120
Question:
Write a program to read 10 numbers from the keyboard and find their sum and average.
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String [] args) {
int N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, sum;
float X;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any ten Numbers: ");
N1 = scan.nextInt();
N2 = scan.nextInt();
N3 = scan.nextInt();
N4 = scan.nextInt();
N5 = scan.nextInt();
N6 = scan.nextInt();
N7 = scan.nextInt();
N8 = scan.nextInt();
N9 = scan.nextInt();
N10 = scan.nextInt();
sum = N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 + N10;
X = sum /10;
System.out.println("The sum of 10 numbers = " + sum);
System.out.println("The average of 10 numbers = " + X);
}
}
687
Question 121
Question:
or not.
Solution:
Question 122
Question:
688
Solution:
Question 123
Question:
Solution:
689
}
Question 124
Question:
Solution:
Question 125
Question:
Solution:
690
public class MyClass {
public static void main(String[] args) {
String x = "Hai this is Alan";
String [] y = x. split(" ", 3);
for(String i : y)
System. out. println(i);
}
}
Question 126
Question:
Solution:
691
Question 127
Question:
Solution:
Question 128
Question:
Solution:
692
String a=String.join("-","Java","Programming");
System.out.println(a);
}
}
Question 129
Question:
Solution:
import java.util.Scanner;
693
Question 130
Question:
Solution:
Question 131
Question:
Solution:
694
}
}
Question 132
Question:
Solution:
Question 134
Question:
Solution:
695
public class MyClass {
public static void main(String[] args) {
int x = 12; public class MyClass {
System.out.print(x >> 1);
public static void main(String[] args) {
}
String x = "Albert";
}
String y = "ALBERT";
System.out.println(x.equalsIgnoreCase(y))
Question 135 ;
// Output: true
Question:
}
Solution:
import java.util.Scanner;
696
Question 136
Question:
Solution:
import java.util.Scanner;
697
Question 137
Question:
Write a program that uses a for loop to determine power of a number entered by the
user.
Solution:
import java.util.Scanner;
698
Question 138
Question:
Solution:
import java.util.Scanner;
699
Question 139
Question:
Write a program to read integer "n" and print first three powers (n1, n2, n3).
Solution:
import java.util.Scanner;
Question 140
Question:
700
Solution:
Question 141
Question:
Solution:
701
Question 142
Question:
Write a program to check if the string starts with the given prefix.
Solution:
Question 143
Question:
Solution:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
702
char ch;
Scanner x=new Scanner(System.in);
System.out.print("Enter a character: ");
ch=x.next().charAt(0);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) {
System.out.println(ch+" is Alphabet.");
}
else if(ch>='0'&&ch<='9') {
System.out.println(ch+" is Digit.");
}
else {
System.out.println(ch+" is Special Character.");
}
}
}
Question 144
Question:
Solution:
703
System.out.println("Java Home: "+System.getProperty("java.home"));
System.out.println("Java Vendor: "+System.getProperty("java.vendor"));
System.out.println("Java Vendor URL:
"+System.getProperty("j ava.vendor.url"));
System.out.println("Java Class Path:
"+System.getProperty("java.class.path")+"\n");
}
}
Question 145
Question:
Solution:
704
}
Question 146
Question:
Write a program to get the current system environment and system properties.
Solution:
import java.lang.*;
public class Main {
public static void main(String[] args) {
System.out.println("\nCurrent system environment:");
System.out.println(System.getenv());
System.out.println("\n\nCurrent system properties:");
System.out.println(System.getProperties());
}
}
Question 147
Question:
705
Solution:
import java.lang.*;
public class Main {
public static void main(String[] args) {
long startTime = System.nanoTime();
int i;
System.out.println ("The first 5 natural numbers are:\n");
for (i=1;i<=5;i++) {
System.out.println(i);
}
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Estimated time (in nanoseconds) to get the first 5
natural numbers: "+estimatedTime);
}
}
Question 148
Question:
Solution:
706
a = a.replace(' ', ch);
System.out.println("String after replacing spaces with the character '-': ");
System.out.println(a);
}
}
Question 149
Question:
Solution:
707
}
Question 150
Question:
Solution:
Question 151
Question:
Solution:
708
public class MyClass {
public static void main(String args[]){
System.out.println(Integer.toOctalString(8));
System.out.println(Integer.toOctalString(19));
System.out.println(Integer.toOctalString(81));
Question 152
Question:
Solution:
709
Question 153
Question:
Solution:
System.out.println(myfunc.x);
// Output: 15
Question 154 }
Question:
Solution:
710
public class MyClass {
public static void main(String args[]){
String hex="a";
int decimal=lnteger.parselnt(hex, 16);
System.out.println(decimal);
}
Question 155
Question:
Solution:
if(x.indexOf(y) != -1)
711
System.out.println("Second string is a rotation of first
string");
else
System.out.println("Second string is not a rotation of first
string");
}
}
}
Question 156
Question:
Solution:
Float a = Float.NaN;
Float b = 6.0f;
System.out.println(a +" - " + a.isNaN());
System.out.println(a +" - " + Float.isNaN(a));
System.out.println(b +" - " + Float.isNaN(b));
}
712
}
Question 157
Question:
Solution:
Float a = Float.NaN;
Float b = 6.0f;
System.out.println(a +" - " + a.isNaN());
System.out.println(a +" - " + Float.isNaN(a));
System.out.println(b +" - " + Float.isNaN(b));
} I----------------
public class MyClass {
for (String i : x) {
System.out.println(i);
} ?
713
Question 158
Question:
Solution:
import java.util.Scanner;
char operator;
Double number1, number2, result;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
switch (operator) {
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
714
break;
case '-':
result = 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();
}
}
System.out.println(x[1][2]); // Output: 17
715
Question 159
Question:
Solution:
x[0] = "Elsa";
716
public class MyClass {
String x = "Einstein";
System.out.println(x.charAt(1));
// Output: i
double x =56.698;
double y =-56.898;
double z =56.45;
System.out.println(Math.round(x)); // Output: 57
System.out.println(Math.round(z)); // Output: 56
717
public class MyClass {
System.out.println(x.substring(15));
System.out.println(x.substring(26));
// Output: Concepts
System.out.println(x.substring(15, 26));
// Output: Programming
System.out.println(x.substring(0, 5));
// Output: Most
718
public class MyClass {
int a = i; 10
System.out.println(a);
} -------------------------------------
buffer.append(" Programming");
Output:
System.out.println(buffer);
Java Programming
}
Overloading provides
• code clarity
• reduce complexity
719
public class MyClass {
builder.append(" Programming");
System.out.println(builder);
}
Output:
Java Programming
720
Python Exercises
721
Question 1
Question:
import numpy as np
Solution:
x= np.ones([2,4])
a = 1
b = 2 print(x)
c= a+b print(x.dtype)
print(c)
print(x.shape) —
# Output:
a = int(input("Enter a number: "))
b = int(input("Enter a number: ")) [[1. 1. 1. 1.]
c= a+b [1. 1. 1. 1.]]
print(c)
float64
(2, 4)
Question 2
Question:
Write a program to find whether a given number (accept from the user) is even or odd,
722
Solution:
import sys
a = int(input("Enter a number: "))
if a % 2 == 0: print("Albert (Einstein)")
print("This is an even number.")
# Output: Albert (Einstein)
else:
print("This is an odd number.") print("Elsa (Einstein)", file=sys.stderr)
sys.stderr.write("David Einstein")
Question 3
# Output: David Einstein
Question:
Write a program to check whether a number entered by the user is positive, negative or
zero.
Solution:
723
Question 4
Question:
names[0] = "David"
import calendar
yy = int(input("Enter year: ")) print(names)
mm = int(input("Enter month: "))
# Output: ['David', 'Paul', 'John']
print(calendar.month(yy, mm))
Question 5
Question:
Write a program to ask the user to enter the string and print that string as output of the
program.
x = ("ball", "bag", "bat")
y = iter(x)
# Output:
ball
Solution: print(next(y))
bag
x= input("Enter string: ") print(next(y))
bat
print("You entered:", x) print(next(y))
724
Question 6
Question:
Solution:
Question 7
Question:
Solution: x = abs(-9.78)
print(x)
x = ["ball", "book", "pencil"]
i = input("Type item to check: ") # Output: 9.78
if i in x:
print("Item exists in the list.")
else:
print("Item does not exist in the list.")
725
Question 8
Question:
Solution:
Question 9
print(x)
Question:
# Output: 15
Write a program to calculate cube of a number.
print(y)
# Output: 215
Solution:
import math
x = int(input("Enter a number: "))
y=math.pow(x,3)
print(y)
726
Question 10
Question:
x = math.ceil(6.8)
y = math.floor(6.8)
Solution:
print(x) # Output: 7
import math
print(y) # Output: 6
x = int(input("Enter a number: "))
y=math.sqrt(x)
print(y)
Question 11
Question:
Write a program that takes a list of numbers (for example, i = [6, 10, 75, 60, 55]) and
makes a new list of only the first and last elements of the given list.
Solution:
727
Question 12
Question:
Take a list, say for example this one: x = [1, 1, 2, 3, 2, 8, 18, 31, 14, 25, 78] and write a
program that prints out all the elements of the list that are less than 4.
x = "alan"
Solution:
y = iter(x) # Output:
x = [1, 1, 2, 3, 2, 8, 18, 31, 14, 25, 78]
a
for i in x:
l
if i < 4: print(next(y))
print(i) a
print(next(y))
n
print(next(y))
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
Solution:
728
y = [i for i in a if i % 2 == 0]
print(y)
Question 14
Question:
Ask the user for a string and print out whether this string is a palindrome or not (A
palindrome is a string that reads the same forwards and backwards).
Solution:
import math
Question 15
Question:
Take two lists, say for example these two: x = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] y = [1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only
729
the elements that are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes.
Solution:
Question 16
Question:
for i in x:
file = open("testfile.txt","w")
file.write("Albert Einstein") print(i)
file.write("Elsa Einstein") if i == "john":
file.write("David Einstein.")
break
file.write("Why E=mc squared?.")
file.close()
# Output:
albert
john
730
Question 17
Question:
Solution:
with open('testfile.txt') as f:
i = f.readline() A program to split the string
while i: at every white-space character
print(i)
import re
line = f.readline()
x = re.split("\s", str)
Question 18 print(x)
Take two sets, say for example these two: x = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89} y = {1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} and write a program that returns a set that contains only
Solution:
731
Question 19
Question:
Write a program to split the characters of the given string into a list.
Solution:
Question 20 print(x)
# Output: Stephen+William+Hawking
Question:
Create a program that asks the user for a number and then prints out a list of all the
divisors of that number.
Solution:
732
print(i)
Question 21
Question:
Solution:
largest = y
else: import re
largest = z
str = "Albert Einstein"
print("The largest number is", largest)
x = re.findall("in", str)
print(x)
Question:
733
Solution:
if x:
print("YES! We've got a match!")
else:
Question 23
^^^B print("No match")
Solution:
734
Question 24
Question:
A program to capitalize
Solution: the first letter of each
word in the string
x = int(input("Please Enter any Number: "))
for i in range(1, x+1):
print(i) import camelcase
c = camelcase.CamelCase()
str = "albert einstein"
print(c.hump(str))
Question 25
# Output: Albert Einstein
Question:
Write a program to calculate the sum and average of natural numbers from 1 to x.
Solution:
735
Question 26
Question:
print(type(True))
Solution:
# Output: <class 'bool'>
x = int(input("Please Enter any Number: "))
for i in range(x): print(type(False))
print("Albert Einstein")
# Output: <class 'bool'>
print(type([1,2]))
Question:
# Output: <class 'set'>
Solution:
def myfunc():
x = int(input("Enter a number: "))
y=int(input("Enter a number: "))
z= x*y
return z
736
i = myfunc()
print(i)
x = 6
y = 2
print(x+y)
Question 28
# Output: 8
Question:
print(x-y)
print(x*y)
# Output: 12
Solution:
print(x/y)
x = ["pen", "book", "ball"]
# Output: 3.0
x.append("bat")
print(x)
x = "23"
Question 29
y = "54"
z = x + y
Question:
print(z)
Write a program to remove an item from the list.
# Output: 2354
Solution:
737
print(x)
Question 30
Question:
Solution:
sys.stdout.write("Einstein")
Question:
Write a program to calculate the variance and standard deviation of the elements of the
list.
Solution:
import numpy as np
x= [2,6,8,12,18,24,28,32]
738
variance= np.var(x)
std = np.std(x) def main():
print(variance) print("Albert Einstein")
print(std)
main()
Question 32
Solution:
x = [4, 5, 6, 7]
y = [4, 5]
print(list(set(x) - set(y)))
Question 33
Question:
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:
Solution:
x = "science.com"
print(x.startswith("phy"))
print("Albert ", end="")
print("Einstein")
Question:
Solution:
741
print(x,'x',i,'=',x*i)
Question 38
Question:
Question 39
Question:
Write a program to sum of two given integers. However, if the sum is between 15 to 20 it
will return 20.
742
Solution:
print(z)
main()
# Output: 4
Question 40
Question:
# Output:
albert
david
743
Question 41
Question:
def main():
Solution:
a = 2.5
import random
b = 2.9
print(random.randint(0,9))
print(float(a) + float(b))
main()
Question 42
# Output: 5.4
Question:
Solution:
744
Question 43
Question:
Given a list of numbers, iterate it and print only those numbers which are divisible of 2.
Solution: x = '2'
print(x)
x = [10, 20, 33, 46, 55]
for i in x: # Output: 2
if (i % 2 == 0): print(x.isdecimal())
print(i)
# Output: True
print(x.isnumeric())
# Output: True
Question 44
if x.isdecimal():
Question:
y = int(x)
# Output: 2
Solution:
import numpy
x = [1, 2, 3]
y = numpy.prod(x)
print(y)
745
Question 45
Question:
print(type(x))
A program to convert
Question 46
'string' to 'int'
Question:
x = 56.39
Solution:
print(type(x))
for x in range(0, 5):
print('#', end="") # Output: <class 'float'>
print("\n")
y = int(x)
A program to convert
746
Question 47
Question:
Solution: print(int(float(5.6)))
# Output: 5
x = "546.11235"
print(float(x)) print(int(float("5")))
print(int(float(x)))
# Output: 5
print(int(float(5)))
# Output: 5
Question 48
Question:
Solution:
# Define a dictionary
customers = {'1':'Mehzabin Afroze','2':'Md. Ali',
'3':'Mosarof Ahmed','4':'Mila Hasan', '5':'Yaqub Ali'}
747
print("The customer names are:")
# Print the values of the dictionary
def main():
for customer in customers:
print(customers[customer]) x = input('First number: ')
Question 49
Question:
Solution:
import math
print(dir(math))
748
Question 50
Question:
# Exception block
except (ValueError):
# Print error message
print("Enter a numeric value")
Output:
11
import array 13
x = array.array('i', [11,13,15,17,19]) 15
for i in x:
17
print(i)
19
749
Question 51
Question:
a = 4
Solution: b = 2
if passwd == "albert":
a += 2 # is the same as a = a + 2
print("You are authenticated")
else: print(a)
b -= 1 # is the same as b = b - 1
print(b)
Question 52 # Output: 1
Question:
750
Solution:
Question 53
Question:
Write a program that sorts three integers without the need of loops or conditional
statements.
import random
x = "123456789"
# Output: 3
a = int(input("Enter the first number: ))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))
x = min(a, b, c)
z = max(a, b, c)
y = (a + b + c) - x - z
print("Numbers in sorted order: ", x, y, z)
751
import random
print(random.randrange(1, 3))
Question 54
Question:
Solution:
Question 55
Question:
Write a program to take in the marks of 5 subjects and display the grade.
752
Solution:
Question 56
Question:
Solution:
753
x=int(input("Enter lower range limit: "))
y=int(input("Enter upper range limit: "))
n=int(input("Enter the number to be divided by: "))
for i in range(x,y+1):
if(i%n==0):
print(i)
Question 57
Question:
Write a program to read two numbers and print their quotient and remainder.
Solution:
754
Question 58
Question:
Solution: x = 0
if x:
Question 59
x = 1
if x:
Question:
print("Albert Einstein")
Write a program to print odd numbers within a given range.
else:
print("Elsa Einstein")
Solution:
# Output: Albert Einstein
755
x=int(input("Enter the lower limit for the range: "))
y=int(input("Enter the upper limit for the range: "))
for i in range(x,y+1):
if(i%2!=0):
print(i)
Question 60
Question:
for i in range(5):
Solution:
print(i)
else:
n=int(input("Enter an integer: "))
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:
y = 56
print(x == y)
Solution:
# Output: False
i=0
# Output: True
while(n>0):
i=i+1 print(y == 56.0)
n=n//10
# Output: True
print("The number of digits in the number are:", i)
print(None == None)
# Output: True
print(None == False)
Question 62
# Output: False
Question:
Write a program to read a number n and print and compute the series "1+2+...+n=".
Solution:
757
x=[]
for i in range(1, n+1):
a = 16
print(i, sep=" ", end=" ")
if(i<n): b = 4
print()
Question 63
Question:
Write a program to read a number n and print the natural numbers summation pattern.
Solution:
758
print()
Question 64
Question:
Write a program to read a number n and print an identity matrix of the desired size.
Solution:
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:
print(x)
Question:
Solution:
760
z = sqrt(x**2 + y**2)
print("The length of the hypotenuse is: ", z)
Question 67
x = .. Stephen
Question:
William
print(x)
Solution:
# Output:
x=[] Stephen
n=int(input("Enter number of elements: "))
William
for i in range(1, n+1):
Hawking
y=int(input("Enter element: "))
x.append(y)
x.sort()
print("Largest element is: ",x[n-1])
Question 68
Question:
761
Solution:
x=[]
n=int(input("Enter number of elements: ")) x = 3 * 'Alan '
for i in range(1,n+1):
print(x)
y=int(input("Enter element: "))
# Output: Alan Alan Alan
x.append(y)
x.sort()
print("Second largest element is: ",x[n-2])
Question 69
Question:
Write a program to put the even and odd elements in a list into two different lists.
x = "Einstein"
Solution:
a = x[0]
a=[]
n=int(input("Enter number of elements:")) print(a)
for i in range(1,n+1):
# Output: E
b=int(input("Enter element:"))
a.append(b) b = x[3]
even=[]
print(b)
odd=[]
for j in a: # Output: s
762
if(j%2==0):
even.append(j)
else:
str = "wxyz"
odd.append(j)
print("The even list", even) print(str)
print("The odd list", odd)
# Output: wxyz
print(str)
Question:
Write a program to concatenate all elements in a list into a string and return it.
x = ["Alan", "Albert"]
y = ["Turing", "Einstein"]
Solution:
def myfunc(list):
for a in x:
result= ''
for i in list: for b in y:
Alan Einstein
Albert Turing
Albert Einstein
763
Question 71
Question:
Write a program to add the three integers given. However, the sum will be zero if two
values are equal.
Solution:
else:
print(y)
sum = a + b + c
return sum # Output: ALBERT
Question 72
Question:
764
Solution: x = "Einstein"
if "ein" in x:
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:
765
Question 74
Question:
Write a program to create a list of all numbers in a range which are perfect squares and
the sum of the digits of the number is less than 10.
Solution:
print(x, chr(x))
Question 75
Question:
Write a program to convert a distance (in feet) to inches, yards, and miles.
Solution:
766
n = int(input("Enter the distance in feet: "))
x = n * 12
y = n / 3.0
x = "Albert Einstein"
z = n / 5280.0
print(x[1:4])
print("The distance in inches is: %i inches." % x)
# Output: lbe
print("The distance in yards is: %.2f yards." % y)
print("The distance in miles is: %.2f miles." % z) print(x[2:])
print(x[:2])
# Output: Al
Question 76
Question:
Write a program to generate random numbers from 1 to 20 and append them to the list.
Solution:
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
767
Question 77
Question:
Write a program to sort a list of tuples in increasing order by the last element in each
tuple.
import numpy as np
x = np.array([2, 4, 8])
y = np.array([3, 6, 12])
Solution:
print(x)
# Output: [2 4 8]
def last(n):
print(y)
return n[-1]
# Output: [3 6 12]
# Output: 126
Output
import array
19
x = array.array('i', [11,13,15,17,19])
17
x.reverse()
15
for i in x:
13
print(i)
11
768
Question 78
Question:
for i in x:
if i == ' ':
Solution:
break
Question 79 t
Question:
Solution:
769
import sys
x = ', '.join(sorted(sys.builtin_module_names))
print("The available built-in modules are: ")
print()
print(x) x = 2
i = x == 2
print(i)
if i:
Question:
print("Albert Einstein")
print("Elsa Einstein")
import sys
x = "three"
y = 154
z = [11, 12, 13, 'Ball', 'Bat']
print("Size of ",x,"=",str(sys.getsizeof(x))+ " bytes")
print("Size of ",y,"=",str(sys.getsizeof(y))+ " bytes")
print("Size of ",z,"=",str(sys.getsizeof(z))+ " bytes")
770
Question 81
Question:
x = 'Albert Einstein'
if i ==
continue
Solution:
print(i)
t
Question 82
E
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))
Solution:
pi=22/7
r = 8.0
V = 4.0/3.0*pi*r**3
print('The volume of the sphere is: ',V)
Question 84
Question:
Write a program to check whether every number in a list exceeds a specific number.
Solution:
772
x = [12, 33, 44, 55]
print()
print(all(i > 11 for i in x))
print(all(i > 100 for i in x))
print()
x = 1915
y = 'Albert'
Write a program that count the occurrences of a particular character within a given string.
Solution:
x = "Albert Einstein."
print("Number of occurrence of 'e' in the given string: ")
print(x.count("e"))
Question 86
Question:
Write a program to compute simple interest given all the required values.
773
Solution:
x = 1915
y = 'Albert'
Solution:
774
Question 88
Question:
Solution:
import os
path="1.txt"
if os.path.isdir(path):
print("It is a directory")
elif os.path.isfile(path):
print("It is a regular file")
else:
print("lt is a unique file (socket, FIFO, device file)" )
print()
x = 1915
y = 'Albert'
Question:
Solution:
775
x=int(input("Enter an integer: "))
print("The divisors of", x, "are: ")
for i in range(1, x+1):
if(x%i==0):
print(i)
x = 1915
y = 'Albert'
Question:
Solution:
Question 91
Question:
776
Solution:
x = 1915
y = 'Albert'
Solution:
import site
print(site.getsitepackages())
777
Question 93
Question:
Solution:
x 1915
y = 'Albert'
Solution:
778
x = 'Albert Einstein'
x=int(input("Enter the first number: "))
for i in x:
y=int(input("Enter the second number: "))
if(x>y): if i == ' ':
min=x
else: continue
min=y if i == 'n':
while(1):
if(min%x==0 and min%y==0): break
print("LCM is:",min)
print(i)
break
min=min+1 print('NSTEIN')
# Output:
A
Question 95
l
b
Question:
e
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]
["Mary", 39]
Question:
["James", 44]
print(type(x))
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:
Solution:
780
y=int(input('Enter number 2: '))
sum1=0 x = "Albert"
sum2=0
for i in range(1,x): print("'{}'".format(x))
if x%i==0:
print("'{:12}'".format(x))
sum1+=i
for j in range(1,y): print("'{:<12}'".format(x))
if y%j==0:
print("'{:>12}'".format(x))
sum2+=j
if(sum1==y and sum2==x): print("'{: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))
Write a program to find the gravitational force acting between two objects.
Solution:
Question 100
Question:
782
Solution:
a = 549.9678962314589
print("{:e}".format(a))
x = 'x549'
try: # Output: 5.499679e+02
i = float(x)
print("{:E}".format(a))
print('Numeric')
except (ValueError, TypeError): # Output: 5.499679E+02
print('Not numeric')
print("{:f}".format(a))
print()
# Output: 549.967896
print("{:.2f}".format(a))
# Output: 549.97
# Output: 549.967896
Question:
print("{:g}".format(a))
Write a program to find out which host the routine is running on. # Output: 549.968
print("{:G}".format(a))
# Output: 549.968
Solution:
print("{:n}".format(a))
# Output: 549.968
import socket
x = socket.gethostname()
print("Host name: ", x)
783
Question 102
Question:
Solution:
print("Albert " + x)
myfunc("Einstein")
784
Question 103
Question:
Write a program to find the sum of series: 1 + 1/2 + 1/3 +...... + 1/n.
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[::])
Question 104
# Output: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Question:
Write a program to get numbers divisible by 12 from a list using an anonymous function.
Solution:
785
Question 105
Question:
pi = 3.141592653589793
Solution:
r = 6
Question:
Write a program that accepts a number as input and returns an error if it is not a number.
Solution:
786
while True:
try:
x 68
a = int(input("Enter a number: "))
print("This is a number") print("<%s>" % x)
break
# Output: <68>
except ValueError:
print("This isn't a number") print("<%10s>" % x)
print()
# Output: < 68>
print("<%-10s>" % x)
print("<%c>" % x)
Question 107
# Output: D
print("<%d>" % x)
Question:
# Output: <68>
Write a program to filter the negative numbers from a list.
print("<%0.5d>" % x)
# Output: <00068>
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(num[::1])
# Output: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
787
Question 108
Question:
Solution:
import array
x = array.array('i', [11,13,15,17,19,13])
print("Number of times the number 13 appears in the above array is: ", x.count(13))
# Output: Number of times the number 13 appears in the above array is: 2
788
Question 109
Question:
Solution:
a, b = 2, 4
result = a * a - 2 * a * b + b * b
print("({} - {}) 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:
Solution:
def myfunc(y):
def myfunc(x):
i = 0
for x in y: return 6 * x
if x == 5:
i = i + 1
print(myfunc(6))
# Output: 36
return i
790
Question 112
Question:
Question:
Solution:
791
print(x)
Write a program to calculate the product of a list of numbers (without using for loop).
Solution:
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Question 115
print(num[1:20:3])
Solution:
792
x=input("Enter first string: ")
y=input("Enter second string: ")
if(sorted(x)==sorted(y)):
print("The 2 strings are anagrams.")
else:
print("The 2 strings aren't anagrams.")
x[1:3] = ['john']
Question:
Write a program to form a string where the first character and the last character have
been exchanged.
Solution:
def change(x):
return x[-1:] + x[1:-1] + x[:1]
x=input("Enter a string: ")
print("Modified string: ")
print(change(x))
print(x)
793
Question 117
Question:
Solution:
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='i' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
x = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
print(x)
# Output: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
Question: # Output: [11, 10, 13, 10, 15, 10, 17, 10, 19, 10, 21, 10]
Write a program to take a string and replace every blank space with a hyphen.
Solution:
794
string=input("Enter a string: ")
a = ['alan', 'john', 'mary', 'david']
string=string.replace(' ','-')
print("Modified string:") b = a
print(string) a[0] = 'computer'
1print(a)
X z
print(b)
Question 119
# Output: ['computer', 'john', 'mary', 'david']
Question:
Write a program to calculate the length of a string without using library functions.
Solution:
import array
x = array.array('i', [11,13,15,17,19,22])
795
Question 120
Question:
b = deepcopy(a)
x = 'Albert Einstein'
print(any(i.islower() for i in x)) a[0] = 'albert'
print(a)
print(b)
Question:
Write a program to calculate the number of words and characters present in a string.
796
if(i==' '):
word=word+1
print("Number of words in the string: ")
print(word)
print("Number of characters in the string: ")
print(char)
Question:
places.
print('%f' % x)
# Output: albert:1915:john
print('%.2f' % x)
print()
def myfunc(x,y):
print(x+y) # Output: 58
myfunc("5","8")
797
Question 123
Question:
Solution:
count=0
# Output: ['xy', 'wz', 'pq']
for i in x:
if(i.islower()):
count=count+1
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:
print(x.index('orange' ))
count1=0
count2=0
for i in x:
if(i.isdigit()):
799
count1=count1+1
count2=count2+1
print("The number of digits is: ")
print(countl)
print("The number of characters is: ")
print(count2)
x.insert(2, 'fig')
print(x)
Question 126
# Output: ['apple', 'orange', 'fig', 'mango', 'kiwi']
Question:
Write a program to form a new string made of the first 2 characters and last 2 characters
Solution:
x.insert(len(x), 'papaya')
print(x)
800
Question 127
Question:
Solution:
Question:
Solution:
x = 60
if x.bit_length() <= 63:
801
print((-2 ** 63).bit_length())
print((2 ** 63).bit_length()) x = [17, 22, -44, 38, 6]
print(x)
x.sort(reverse=True)
Write a program that returns true if the two given integer values are equal, or if their sum
or difference is 10.
Solution:
802
Question 130
Question:
Write a program to add two objects if they are both of the integer type.
Solution:
x.sort(key=len)
Question 131
print(x)
Solution:
803
x='122.22'
x = x.ljust(8, '0')
print(x)
x = ['alan', 'albert', 'james', 'bob']
x = x.ljust(10, '0')
print(x) x.sort(key=len, reverse=True)
print(x)
Question 132
Question:
Solution:
import json
print(json.dumps({'Albert': 1, 'Alan': 2, 'Alex': 3}))
Question 133
Question:
804
Solution:
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else: for x in range(10, 19, 5):
print("Key isn't present!")
print(x)
# Output:
10
Question 134 15
Question:
Solution:
d={'A':100,'B':540, 'C':239}
print("Total sum of values in the dictionary is: ")
print(sum(d.values()))
805
Question 135
Question:
y = ['david']
d={'A':10,'B':10,'C':239} print(x)
x=1
for i in d: # Output: ['albert', 'elsa']
x=x*d[i]
print(x * 2)
print(x)
# Output: ['albert', 'elsa', 'albert', 'elsa']
print(x + y)
Question:
Solution:
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
806
print(d)
a, b = 11, 12
key=input("Enter the key to delete(a-d):")
if key in d: print(a)
del d[key]
# Output: 11
else:
print("Key not found!") print(b)
exit(0)
# Output: 12
print("Updated dictionary")
print(d) a, b = b, a
print(a)
# Output: 12
print(b)
Question 137
# Output: 11
Question:
Write a program to list the home directory without using an absolute path.
Solution:
import os.path
print(os.path.expanduser('~'))
x = [5,8,57,35,44,14,28]
807
Question 138 x = [0] * 5
0 0
1 0
Solution:
2 0
>
3 0
print("Enter the value of a and b: ")
4 0
a, b = map(int, input().split())
print("The value of a and b are: ", a, b)
print([2] * 5)
Question 139
# Output: [2, 2, 2, 2, 2]
Question:
Solution:
a = 'true'
a = int(a == 'true')
print(a)
a = 'xyz'
808
a = int(a == 'true')
print(a)
y = 'AB+CD+EF+GH+IJ+KL+MN'
x = y.split('+')
x.sort(key=len, reverse=True)
print(x)
Question 140
# Output: ['AB', 'CD', 'EF', 'GH', 'IJ', 'KL', 'MN']
Question:
Solution:
print(isinstance(16,int) or isinstance(16,str))
print(isinstance("16",int) or isinstance("16",str))
Question 141
Question:
Write a program to count the number of vowels present in a string entered by the user
using sets.
809
Solution:
x.extend(y)
Solution:
810
Question 143
Question:
Write a program to display which letters are in the first string but not in the second string.
Solution:
Question 144
Question:
Solution:
811
i = ['list', True, 8.9, 6] import numpy as np
if type(i) is list:
x = np.random.randint(10, size=(2, 3))
print('i is a list')
elif type(i) is set: print(x)
print('i is a set')
elif type(i) is tuple:
print('i is a tuple')
else:
print('Neither a set, list, or tuple.')
Question 145
Question:
# Output:
albert => 46
Solution: x = {
bob => 18
"albert" : "46",
john => 68
def myfunc(n): "bob" : "18",
if (n < 2): "john" : "68",
return (n % 2 == 0)
}
return (myfunc(n - 2))
n=int(input("Enter a number: "))
if(myfunc(n)==True): for name, age in x.items():
print("Number is even!")
print("{} => {}".format(name, age))
else:
812
print("Number is odd!")
Question 146
Question:
Write a program that examines a list of numbers to see if they are all distinct from one
another. x = {}
x['name'] = 'albert'
print(x)
Solution:
# Output: {'name': 'albert'}
x['email'] = 'albert_john@gmail.com'
def myfunc(x):
if len(x) == len(set(x)): print(x)
x = "Albert "
print(x + y)
813
Question 147
Question:
Write a program to add two positive numbers without using the ' + ' operator.
Solution: x = {
'name': 'Albert',
print(x.get('age'))
# Output: 26
print(x.get('email'))
# Output: None
Question 148
print(x.get('address'))
Solution:
814
def myfunc(n): x = {
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
# Output: True
Question:
Write a program to determine whether a right triangle is formed by three given side
lengths. If the specified sides make a right triangle, print "Yes," otherwise print "No."
Solution:
815
Question 150
Question:
Write a program to find the number of equal numbers among three given integers.
x = {
Solution:
'name': 'Albert',
def myfunc(a, b, c):
'age': 26,
result= set([a, b, c])
if len(result)==3: 'email': None
return 0 }
else:
return (4 - len(result))
print(x)
Question 151
Question:
Solution:
816
def myfunc(x):
result = [int(x) for x in x.split() if x.isdigit()]
return result
x = "5 bags, 10 pencils and 55 books"
print(myfunc(x))
Question 152
Question:
x = {}
x['A'] = 11
Solution:
x['B'] = 12
x = list[0]
x['D'] = 14
for i in list:
if i < x: print(x)
x = i
return x
print(myfunc([11, 22, -28, 3])) # Output: {'A': 11, 'B': 12, 'C': 13, 'D': 14}
817
Question 153
Question:
Write a program to determine whether every string in a list is equal to a given string..
x = {
Solution:
'name': 'Albert',
# Output:
U
name -> Albert
Solution:
818
with open(x, 'r') as f:
for line in f: import numpy as np
num_words += len(line.split())
x = np.random.random((3, 6))
print("Number of words: ", num_words)
print(x)
Question 155
Question:
Solution:
y = 12.5
z = "Albert"
819
Question 156
Question:
x = set()
# Output: set()
x.add('Mary')
Solution:
print(x)
x.add('Mary')
print(x)
# Output: {'Mary'}
Question 157
x.add('John')
Question: print(x)
Write a program that computes the average of two lists. # Output: {'John', 'Mary'}
Solution:
820
print("The Average of two lists: ", myfunc(x, y))
Question 158
Question:
Write a program to determine the maximum and minimum value in the three given lists.
Solution:
x = [12,13,15,28,27,32,53]
y = [54,32,91,0,41,13,19]
z = [12,11,51,16,15,58,49]
print("Maximum value in the three given lists is: ")
print(max(x+y+z))
print("Minimum value in the three given lists is: ")
print(min(x+y+z))
x = int(5)
y = int(5.2)
w = float(5.6)
z = int("6")
print(x) # Output: 5
print(y) # Output: 5
print(z) # Output: 6
821
Question 159
Question:
Solution:
Question 160
Question:
import numpy as np
# Output:
x = np.eye(2)
Solution: [[1. 0.]
print(x)
[0. 1.]]
print()
x = [{},{},{}]
y = [{2:6},{},{}] y = np.eye(2, 4) [[1. 0. 0. 0.]
print(all(not i for i in x)) [0. 1. 0. 0.]]
print(y)
print(all(not i for i in y))
822
Question 161
Question:
Write a program that takes two lists and returns True when at least one of the elements in
x = 5
Solution:
def myfunc(i):
i = i+1
def myfunc(A, B):
return i
result = False
for x in A:
for y in B: print(x)
if x == y: # Output: 5
result = True
print(myfunc(x))
return result
# Output: 6
print(myfunc([21,22,23,24,25], [25,26,27,28,29]))
print(myfunc([31,32,33,34,35], [36,37,38,39])) print(x)
# Output: 5
x = "Albert Einstein"
823
Question 162
Question:
Solution: x = lambda a, b, c: a + b + c
print(x(2, 2, 2))
x = []
# Output: 6
if x:
print("List is not empty")
else:
print("List is empty")
Question 163
Question:
Write a program to read a file and capitalize the first letter of every word in the file.
Solution:
824
set(['John', 'Mary'])
print(x)
print(y)
Question 164
# Output: {'Joe', 'Bob', 'Mary', 'Albert'}
Question:
c = a + b
x=input("Enter the file name: ") return c
for line in reversed(list(open(x))):
print(line.rstrip())
print(myfunc(12, 33))
# Output: 45
print(myfunc(28, 93))
Question:
825
Solution:
x :int = 6
print(x)
# Output: 6
Question 166
Question:
Solution:
def myfunc(x):
x :str = "Albert"
x = x.replace(' ','')
return x print(x)
# Output: Albert
print(myfunc("a lbe rt ein stein"))
print(myfunc("a l a n"))
826
Question 167
Question:
Write a program that calculate the difference between a given number and 10, returning
double the absolute difference if the value is higher than 10.
Solution:
def myfunc(x):
if x <= 10: x float = 26.69
return 10 - x
print(x)
else:
return (x - 10) * 2 # Output: 26.69
print(myfunc(8))
print(myfunc(16))
Question 168
Question:
Write a program that adds three given numbers, returning three times their sum if the
values are equivalent.
827
Solution:
if a == b == c:
sum = sum * 3 print(myfunc(12, 13))
return sum
# Output: 25
Question 169
Question:
Solution:
import platform
print(platform.architecture()[0])
828
Question 170
Question:
import os
birthdays = {
'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
829
Question 171
Question:
Write a program to find the name and location of the file that is currently running.
Solution:
import os
print("Current File Name : ", os.path.realpath(__file__ ))
import platform
print(platform.system())
print(platform.release())
Question:
# Output: 10
Write a program to implement password generator.
Solution:
import random
x =
"abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%A&*O?"
830
passlen = 8
print("".join(random.sample(x, passlen)))
831
Question 174
from functools import reduce
Question:
print(reduce(lambda a, b: a+b, [], 1))
# Output: 10
Solution:
print(reduce(lambda a, b: a*b, [5, 6], 0))
x='Albert Einstein\n'
# Output: 0
print(x.rstrip())
print(reduce(lambda a, b: a*b, [6, 5], 1))
# Output: 30
Question:
Write a program to remove existing indentation from all of the lines in a given text.
Solution:
import textwrap
x = '''
Albert Einstein was a German-born theoretical physicist,
widely acknowledged to be one of the greatest and most
influential physicists of all time. Einstein is best known
for developing the theory of relativity, but he also made
832
important contributions to the development of the theory of
quantum mechanics.
'''
print(x)
print(textwrap.dedent(x))
Question 176
Question:
print(multiprocessing.cpu_count())
Question 177
Question:
833
Solution:
def myfunc(x):
if len(x) % 6 == 0:
return ''.join(reversed(x))
return x
print(myfunc('alan'))
print(myfunc('albert'))
y = [1, 2, 3, 4, 5]
Question 178
print(list(zip(x, y)))
# Output: [('Mon', 1), ('Tue', 2), ('Wed', 3), ('Thru', 4), ('Fri', 5)]
Question:
Put "xyz" at the end of the specified string (length should be at least 3). If the provided
string already ends with "xyz," add "123" to it. If the specified string's length is less than
import numpy as np
Solution:
x= np.zeros(5, dtype='float32')
print(x)
def myfunc(x):
i = len(x) # Output: [0. 0. 0. 0. 0.]
print(x.dtype)
if i > 2:
if x[-3:] == 'xyz': # Output: float32
x += '123'
834
else:
x += 'xyz'
return x
print(myfunc('xy'))
print(myfunc('xyz'))
print(myfunc('morning'))
y = [1, 2, 3, 4, 5]
print(dict(zip(x, y)))
Question 179
# Output: {'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thru': 4, 'Fri': 5}
Question:
import random
print(x /2)
x = [11, 12, 13, 14, 15]
random.shuffle(x) # Output: [3. 4. 5.]
print(x)
print(x.dtype)
# Output: int8
835
Question 180
Question:
Three positive numbers are present in a list. Write a program to determine whether the
sum of the digits in each number is equal or not. If true, return true; otherwise, return
false.
x = [True, True]
y = [True, False]
Solution:
z = [False, False]
print(all(x))
def myfunc(x):
return x[0] % 9 == x[1] % 9 == x[2] % 9 # Output: True
x = [14, 5, 23]
print(all(y))
print(myfunc(x))
# Output: False
print(all(z))
# Output: False
Question 181
print()
print(any(x))
Question:
# Output: True
Write a program to get IP address of your computer.
print(any(y))
# Output: True
Solution: print(any(z))
836
y = socket.gethostbyname(x)
print("Your Computer Name is: " + x)
print("Your Computer IP Address is: " + y)
Question 182
Question:
Write a program to determine whether a series of integers has an increasing trend or not.
Solution:
def myfunc(x):
if (sorted(x) == x): print(12 > 10)
return True
# Output: True
else:
return False print(10 > 15)
# Output: False
print(myfunc([11,12,13,14]))
print(myfunc([11,12,15,13,14]))
x.clear()
print(x) # Output: []
837
Question 183
Question:
x = [12, 14]
Solution:
print(all(map(lambda i: i > 5, x)))
import random
min = 1 # Output: True
max = 6
print(all(map(lambda i: i > 13, x)))
Question 184
Question:
838
Solution:
Question 185
Question:
import numpy as np
# Output: int32
Question:
Write a program to check whether the given integer is a multiple of both 3 and 5.
839
Solution:
Question 187
Question:
Write a program to display all the multiples of 5 within the range 10 to 70.
for i in x:
for i in range(10,70):
if (i%5==0): print(i)
print(i)
print(x)
Question 188
Question:
Write a program to display all integers within the range 50-100 whose sum of digits is an
even number.
840
Solution:
for i in range(50,100):
num = i
sum = 0 x = lambda a: a + 5
while(num!=0):
print(x(2))
digit = num%10
sum = sum + digit # Output: 7
num = num//10
if(sum%2==0):
print(i)
Question 189
Question:
Write a program to print the numbers from a given number n till 0 using recursion.
841
myfunc(9)
from functools import reduce
x = 5
Question:
Solution:
num = [8,3,1,6,2,4,5,9]
count = 0
for i in range(len(num)):
if(num[i]%2!=0):
count = count+1
print("The number of odd numbers in the array are: ", count)
Question 191
Question:
Solution:
842
import numpy as np
def myfunc(x):
x = np.array([
return x[::-1].lower()
x = "JAVASCRIPT" [ 11, 12, 13, 14, 15],
])
print(x)
print(x * 6)
Question 192 print(x + 5)
Question:
import itertools
if a >= b: 11
break
return a 12
else:
13
return b
14
a = 3 15
b = 5
16
print(maximum(a, b))
Solution:
843
a = 3
b = 5
Solution:
print(issubclass(GeneratorType, Iterator))
a = 3
# Output: True
b = 5
print(issubclass(Iterator, Iterable))
print(a if a >= b else b)
# Output: True
• A generator is an iterator
• An iterator is an iterable
Question 193
Question:
y = x[2:5]
Solution: print(y)
x[2] = 99
if a <= b:
print(x)
return a
else: # Output: [11, 11, 99, 13, 15, 18, 19, 35, 64]
return b print(y)
844
import itertools
a = 3
b = 9 i = 0
print(minimum(a, b))
for x in itertools.cycle(['A', 'B', 'C']):
print(x)
i = i+1 # Output:
Question 194
A
if i >= 4:
B
Question:
break
C
Write a program to calculate Profit or Loss. print('')
A
12
Question 195 14
845
Solution:
def myfunc():
total = physics + math + chemistry
percentage = (total / 300) * 100 yield 24
yield 48
print("Total Marks = %.2f" %total)
yield 64
print("Percentage = %.2f" %percentage)
x = 5
y = 100
# Output: Y
846
Question 196 def myfunc():
yield 24
Question:
yield 48
x = myfunc()
Solution:
print(type(x))
x = int(input(" Enter the Value of N : "))
for i in x:
<class 'generator'>
24
Question 197
48
64
Question:
Solution:
847
Question 198
Question:
def myfunc(name):
def x():
Solution: print(f"Albert {name}")
total = 0 y = myfunc("Einstein")
y()
for num in range(1, x+1):
# Output: Albert Einstein
if(num % 2 == 0):
print("{0}".format(num))
total = total + num
Question 199
Question:
Solution:
848
x = int(input(" Enter the Value of N : "))
total = 0
Question 200
Question:
Solution:
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print(ch, "is an Alphabet.")
else: x = 21
print(ch, "is Not an Alphabet.")
y = 5
z = 35
849
Question 201
Question:
Solution:
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print(ch, "is an Alphabet.")
elif(ch >= '0' and ch <= '9'):
print(ch, "is a Digit.")
else:
print(ch, "is a Special Character.") say = print
say("Albert Einstein")
Question:
Solution:
850
if(ch.islower()):
print(ch, "is a Lowercase character")
else:
print(ch, "is Not a Lowercase character")
def myfunc():
Question 203
x = 2
yield x
Question:
yield x
Solution:
x += 2
if(ch.isupper()):
for i in myfunc():
print(ch, "is a Uppercase character")
else: print(i)
# Output:
Question 204 2
Question: 6
851
Solution:
while True:
yield x
Question 205
x += 1
Question:
for i in myfunc():
Write a program to convert string to Uppercase.
print(i)
if i >= 5:
break
Solution:
1
string = str.upper()
2
852
Question 206
def myfunc():
Question: i = 0
return i
Solution:
print(myfunc())
2
Question 207
Question:
Solution:
binary = bin(decimal)
853
octal = oct(decimal)
hexadecimal = hex(decimal)
Question 208
Question:
Solution:
i = 0
i += 1 # Output:
if total == 180:
print("\nThis is a Valid Triangle") print(i) 1
else:
if i > 0:
print("\nThis is an Invalid Triangle")
break
854
Question 209
Question:
Write a program that inputs an age and print age after 20 years .
Solution:
print(i)
Question:
if i == 12:
Write a program to print the number of seconds in year. x.remove(12)
# Output:
print(x)
11
12
Solution:
13
days=365
14
hours=24
[11, 13, 14]
minutes=60
seconds=60
print("Number of seconds in a year : ",days*hours*minutes*seconds)
855
Question 211
Question:
Write a program that inputs a string and then prints it equal to number of times its
length. i = 0
def myfunc():
global i # Output:
Solution:
i += 1 1
str = input("Enter string: ")
return i 2
b = len(str)
3
a = str * b
print(a)
print(myfunc())
print(myfunc())
Question:
Write a program to convert a given list of strings and characters to a single list of
characters.
Solution:
def myfunc(x):
result = [i for y in x for i in y]
return result
856
x = ["alan", "john", "w", "p", "james", "q"]
print(myfunc(x))
x = 22
y = 5
z = 73
if x > y or x > z:
x = 1
857
say = print
import numpy as np
def mult(x, y):
x = np.array([11, 11, 12, 13, 15, 18, 23, 31, 65])
return x * y
print(x)
print(x[2:5])
# Output: 36
# Output: [12 13 15]
import numpy as np
print(x) # Output:
[[ 2 4 6]
---------------- ►
[ 8 10 12]]
print(y)
# Output:
[[ 3 6 12]
[15 18 21]]
print(x*y)
# Output:
[[ 6 24 72]
858
print(np.multiply(x, y))
# Output:
[[ 6 24 72]
import numpy as np
print(x.dtype)
# Output: bool
print(x)
import numpy as np
print(x)
print(np.vectorize(len)(x))
# Output: [6 5 4 8 3]
def myfunc():
# Output:
return 26
26
print(myfunc())
26
print(myfunc())
26
print(myfunc())
859
a = ['pqrs', 'wxyz']
print(a)
def myfunc():
# Output: ['pqrs', 'wxyz'] return 26
print(a[0:1]) return 27
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
# Output: [(6, 'Albert'), (5, 'James'), (4, 'Mary'), (8, 'Einstein'), (3, 'Bob')]
import multiprocessing as mp
# Output: 4
860
x = complex(5, 6)
return y
print(x.real)
# Output: 5.0
print(f(11))
print(x.imag)
print(f(12))
# 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)
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
0 11
print(x)
1 11
----------------------------------------►
2 12
print(x.values)
3 13
print(x.sum()) 5 18
dtype: int64
# Output: 80
print(x.count())
# Output: 6
print(x.mean())
# Output: 13.333333333333334
print(x.median())
# Output: 12.5
print(x.std())
# Output: 2.7325202042558927
862
import numpy as np
for _ in range(10): ______________
x = np.array([112], 'uint8' ) print('Albert')
print(x.dtype) ?
# Output: uint8
print(x)
# Output: [112]
x[0] += 1
import numpy as np
print(x)
x = np.array([11, 12, 13])
# Output: [113]
y = np.array([14, 15, 16])
x[0]-=1
z = np.array([17, 18, 19])
print(x)
print(x)
# Output: [112]
# Output: [11 12 13]
x[0] = 126
print(y)
print(x)
# Output: [14 15 16]
# Output: [126]
print(z)
x[0]+=1
# Output: [17 18 19]
■
print(x)
w = np.hstack([x, y])
# Output: [127]
print(w)
1
# Output: [11 12 13 14 15 16]
q = np.hstack([w, z])
print(q)
863
for i in [1, 2, 3]:
1
print(i)
Albert
print('Albert' * i)
2
AlbertAlbert
3
# Output:
AlbertAlbertAlbert
print(6, type(6))
print(6.8, type(6.8)) b = 1
print(False, type(False))
print(None, type(None))
def x(i):
# Output: None <class 'NoneType'>
return 5*i
b = 3
print(x(b) + x(3*b-1))
# Output: 55
864
print(format(.1, '.20f'))
# Output: 0.10000000000000000555
print(format(.2, '.20f'))
# Output: 0.20000000000000001110
# Output: 0.30000000000000004441
print(format(.3, '.20f'))
# Output: 0.29999999999999998890
▼
str: Bob, int: 53, formatted float: 6.169.
865
Best Linux Books that Every Superuser Should Read:
• Linux in a Nutshell
• Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security
in Kali
Book by OccupyTheWeb
• Linux Command Line and Shell Scripting Bible
• Linux Administration: The Linux Operating System and Command Line Guide for
Linux Administrators
• Linux Bible
• Linux administration
• Linux Essentials
example in the sense that it shows you can set people to work in
- James Surowiecki
Best Programming Books that Every Programmer Should Read:
C:
• Head First C
• Expert C Programming
Book by K. N King
• Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep
Avoiding (Like C)
• Let Us C
• A Book on C: Programming in C
• Extreme C: Taking You to the Limit in Concurrency, OOP, and the Most Advanced
Capabilities of C
Book by Kamran Amini
• Let Us C Solutions
• Introduction to C Programming
• C - In Depth
• C How to Program
• Understanding Pointers In C & C++: Fully Working Examples and Applications of Pointers
C++:
• C++ Primer
• A Tour of C++
• More Effective C++: 35 New Ways To Improve Your Programs And Designs
• C++ Programming
Book by D. S. Malik
• Professional C++
• C++ High Performance: Master the Art of Optimizing the Functioning of Your C++ Code
• Data Parallel C++: Mastering DPC++ for Programming of Heterogeneous Systems using
Book by James Brodman, Michael Kinsner, Xinmin Tian, Ben Ashbaugh, John Pennycook,
James Reinders
• Modern CMake for C++: Discover a Better Approach to Building, Testing, and Packaging
Your Software
• Expert C++: Become a Proficient Programmer by Learning Coding Best Practices with
• Learn C++ Quickly: A Complete Beginner's Guide to Learning C++, Even If You're New to
Programming
• Hands-On Design Patterns with C++: Solve Common C++ Problems with Modern Design
JAVA:
• Effective Java
• Thinking in Java
Book by Bruce Eckel
• Core Java
• Test Driven: Practical TDD and Acceptance TDD for Java Developers
• Spring in Action
• Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D
• Java Performance: The Definitive Guide: Getting the Most Out of Your Code
• OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
• Java Performance
PYTHON:
• Fluent Python
• Learn Python the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful
• Automate the Boring Stuff with Python: Practical Programming for Total Beginners
Book by Al Sweigart
• Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython
• Learning Python
Book by Al Sweigart
• Python Data Science Handbook: Essential Tools for Working with Data
• Python in a nutshell
Book by Al Sweigart
• Python Programming for the Absolute Beginner
• The Python Bible 7 in 1: Volumes One To Seven (Beginner, Intermediate, Data Science,
• Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities
• Learn More Python 3 the Hard Way: The Next Step for New Python Programmers
HTML:
Book by Jo Foster
Textbook by M. G. Martin
CSS:
• CSS in Depth
• CSS mastery
• Learn CSS in One Day and Learn It Well: CSS for Beginners With Hands-On Project
• CSS Master
JAVASCRIPT:
• JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language
• Programming JavaScript Applications: Robust Web Architecture with Node, HTML5, and
Modern JS Libraries
• JavaScript Enlightenment
• Beginning JavaScript
• JavaScript Patterns
• Object-Oriented JavaScript
• Maintainable JavaScript
Book by Nicholas C. Zakas
• DOM Enlightenment
• Testable JavaScript
Book by Al Sweigart
• The Road to Learn React: Your Journey to Master Plain Yet Pragmatic React. Js
• Learning TypeScript
Functional Techniques
PHP:
• The Joy of PHP: A Beginner's Guide to Programming Interactive Web Applications with
• Learning PHP, MySQL, JavaScript, CSS and HTML5: A Step-by-Step Guide to Creating
Dynamic Websites
• Programming PHP
Book by Rasmus Lerdorf
• PHP and MySQL: Novice to Ninja: Get Up to Speed With PHP the Easy Way
• Learning PHP, MySQL & JavaScript: With JQuery, CSS & HTML5
• PHP and MySQL in easy steps, 2nd Edition: Updated to cover MySQL 8.0
• Mastering PHP 7
• PHP 8 Programming Tips, Tricks and Best Practices: A Practical Guide to PHP 8 Features,
• PHP: Learn PHP in One Day and Learn It Well. PHP for Beginners with Hands-on Project
• PHP Cookbook
• Drupal 9 Module Development: Get Up and Running with Building Powerful Drupal
• WordPress Complete
• Learning PHP 7
• Mastering The Faster Web with PHP, MySQL, and JavaScript: Develop State-of-the-art
• PHP Microservices
• Professional CodeIgniter
• PHP Programming for Beginners: Key Programming Concepts. How to use PHP with
ALGORITHMS:
• Introduction to Algorithms
• Grokking Algorithms: An Illustrated Guide for Programmers and Other Curious People
Book by Aditya Bhargava
• Algorithms
• Algorithm Design
• Algorithms in a nutshell
• Data structures and algorithms made easy in Java: data structure and algorithmic puzzles
Programming Skills
Contests
• Algorithms Unlocked
• The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake
Our World
• Spies, Lies, and Algorithms: The History and Future of American Intelligence
• Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services
• A Programmer's Guide to Computer Science: A virtual degree for the self-taught developer
• Concrete Mathematics
Textbook by Donald Knuth, Oren Patashnik and Ronald Graham
DATA STRUCTURES:
Book by J. R Hubbard
• Java Structures
LINUX:
• Linux bible
• Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali
Book by OccupyTheWeb
• Linux Administration: The Linux Operating System and Command Line Guide for Linux
Administrators
• Linux in a Nutshell
• Learn Linux Quickly: A Beginner-friendly Guide to Getting Up and Running with the
World's Most Powerful Operating System
• The Ultimate Kali Linux Book: Perform Advanced Penetration Testing Using Nmap,
Metasploit, Aircrack-Ng, and Empire
Programming
• Linux Kernel Debugging: Leverage Proven Tools and Advanced Techniques to Effectively
• Bash cookbook
• Linux for Beginners: A Practical and Comprehensive Guide to Learn Linux Operating
• Kali Linux Hacking: A Complete Step by Step Guide to Learn the Fundamentals of Cyber
• Bash Pocket Reference: Help for Power Users and Sys Admins
DATABASE:
• Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and
Maintainable Systems
• Database Internals: A Deep Dive Into How Distributed Data Systems Work
• Database Design and Relational Theory: Normal Forms and All That Jazz
Book by Christopher J. Date
• Learning SQL
• Foundations of databases
• Pro SQL Server Relational Database Design and Implementation: Best Practices for
• Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement
• Refactoring databases
• SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and
• SQL Cookbook
• SQL Queries for Mere Mortals: A Hands-on Guide to Data Manipulation in SQL
Performance
build bigger and better idiot-proof programs, and the Universe trying to
- Andrew Hunt
One final thought:
If you feel that this information has been useful to you, please take a
moment to share it with your friends on LinkedIn, Facebook and
Twitter. Consider writing a brief review on Google Play Books if you
feel that this book has helped you in your programming career and you
have learned something worthwhile.
Thank you!
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