COMPUTER CONCEPTS AND FUNDAMENTALS OF PROGRAMMING Ganesh B. Ingle, Vishwanath Mishra, Ms. G. Sridevi Devasena, Smt. Unnati Nitin Chaudhari, Wallace Jacob M A L AY S I AS I N G A P O R EI N D I A
Notion Press Old No. 38, New No. 6 McNichols Road, Chetpet Chennai - 600 031 First Published by Notion Press 2018 Copyright © Ganesh B. Ingle, Vishwanath Mishra, G. Sridevi Devasena, Unnati Nitin Chaudhari, Wallace Jacob 2018 All Rights Reserved. ISBN 978-1-644291-23-8 This book has been published with all efforts taken to make the material error-free after the consent of the author. However, the author and the publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause. No part of this book may be used, reproduced in any manner whatsoever without written permission from the author, except in the case of brief quotations embodied in critical articles and reviews.
Preface We will remain indebted to the luminaries of the ilk of Wilhelm Schickard, Blaise Pascal, Guglielmo Marconi, Samuel F. B. Morse, Nikola Tesla, Charles Babbage, Lady Ada Lovelace, John von Neumann, Alan Turing, Grace Hopper, Edsger W. Dijkstra, Claude Shannon, Edgar F. Codd, Dennis Ritchie, Bjarne Stroustrup, Vint Cerf, Tim Berners-Lee, Sergey Brin, Larry Page, Steven Paul Jobs, and their like, who framed and changed the landscape of electronics, telecommunications and computing forever. We are also thankful to Vijay Mukhi (and his team), Yashvant Kanetkar whose books on BASIC, C, C++, UNIX, and JAVA, explored acres and acres of uncharted territory. We feel that their contribution cannot be measured. We have drawn inspiration from them and hence written this book. This book is a humble endeavor on our part to help the IMU Marine Engineering and Nautical Science students appreciate and comprehend the very important subject: Computer Science. Indubitably ‘computer science and technology’ has invaded and pervaded our lives and the best course of action would be to understand it and use it for the benefit of every living and non-living being. As frail human beings, we might be lacking in many spheres. However, we are open to constructive criticism and humbly solicit suggestions for improvement of the text from the esteemed readers of our book.
CONTENT Chapter – 1 1 INTRODUCTION TO COMPUTER Chapter – 2 11 COMPUTER SOFTWARE Chapter – 3 18 INTRODUCTION Chapter – 4 24 DATA TYPES AND OPERATORS Chapter – 5 35 DECISION CONTROL INSTRUCTIONS Chapter – 6 46 DECISION MAKING AND LOOPING Chapter – 7 59 ARRAYS Chapter – 8 75 STRINGS Chapter – 9 79 USER DEFINED FUNCTIONS Chapter – 10 83 POINTERS Chapter – 11 89 STRUCTURES AND UNIONS Chapter – 12 148 ELECTRONIC COMMERCE
Chapter – 1 INTRODUCTION TO COMPUTER 1.1  Computer Introduction It is an electronic device capable of performing complex arithmetical and logical operations to give desired output. 1.1.1  Characteristics of Computer are as follows: • Speed • Arithmetical and Logical Operations • Accuracy • Reliability • Storage • Retrieving Data and Program • Automation • Versatility (Flexible) • Consistency • Communications 1.1.2 Hardware/Software Computer Hardware Parts of computer, which can be touch is called hardware.(Physical Parts) • Monitor • CPU • Key Board • Mouse • Speaker Computer Software Parts of computer, which cannot be touch is called software. These are set of instructions or programs written in any computer programming language. Operating System Software: Windows, MAC, Linux Application Software: MS Office, Photoshop, Media Player Internet Browser Software: Internet Explorer, Google Chrome, Mozilla Firefox, etc.
Computer Concepts and Fundamentals of Programming 2 1.1.3  Generations of computer i. First(1945-1955): Used vacuum tubes. Were very large. Generated immense heat. Very expensive. ii. Second(1955-1965):Used transistors. Continued to be large andexpensive. iii. Third(1965-1975):Used integrated circuits. Significant reduction in size and cost iv. Fourth(1975-1995): Uses Very Large Scale Integration. Desktop computers would not have been possible without VLSI. It used Microprocessor minimizing the size of P.C. v. Fifth: Will provide us with Artificial intelligence. Also called knowledge information processing system Fig: Generations of computer 1.2  Classification of Computers Computers are classified depending upon the types of electronics/hardware and processing power Depending on hardware they are classified in to • Analog, • Digital and • Hybrid Depending on processing power and speed they are classified in to Personal computer • A single-user computer • Can be useful at School, Home, etc. • Known as Micro Computer • Laptop, Desktop Workstation • A powerful, single-user computer. • A workstation is like a personal computer, but it has a more powerful microprocessor • higher-quality monitor. • Can be found in companies etc. Minicomputer • A multi-user computer • Capable of supporting from 10 to hundreds of users simultaneously. • Can be found in banks, government departments etc.
Introduction to computer 3 Mainframe • A powerful multi-user computer • Capable of supporting hundreds or thousands of users simultaneously. Supercomputer • An extremely fast computer • Can perform hundreds of millions of instructions per second • Weather, scientific research can be done by these types of computer 1.3  Basic internet terminology Host A computer that is used to transfer data on the Internet. Web Hosting To store and make web pages available and ready for inquiries, or a computer that has a consistent connection to the Internet. Domain A domain name is a description or representation of a computer's location on the Internet. It is usually separated by a dot. For example: http://www.imu.edu.in DNS DNS (Domain Name System) is a large database of domain names and their correspondent Internet (IP Addresses). IP address This 32 bit address mechanism for addressing the devices on the network. Different classes of IP address as per the IPV4 standard are as follows: i. Class A –(0-126) ii. Class B-(128-191) iii. Class C-(192-223) iv. Class D-(224-239) v. Class E-(240-255) The 127 is used by the local host as loop back adapter and for the inter processes communication. In the above list class D and E are used for the experimental purpose. HTML Hypertext Markup Language is a coding language used to tell a browser how to place pictures, text, multimedia and links to create a web page. FTP File Transfer Protocal is a method of transferring files between two computers on the Internet InterNic InterNic is governs and maintains the name and host registration on the Internet.
Computer Concepts and Fundamentals of Programming 4 URL Uniform Resource Locator is a web address used to connect website on the World Wide Web. For example: http://www.imu.edu.in Port The total nober of ports are 0-65535.A a Port is a channel that a server software would listen to, for any inquiries. Bit Bit is a single digit base 2. For example: 1 is a bit or 0 is a bit. Byte A Byte generally consists of eight bits. Server The server computer coupled with server software, listens for inquiries from a client computer. Upload To upload is to transfer data from your computer to another computer. Download To download is to transfer data from another computer to your computer. sss 1.4  Basic computer organization Following points are important points as far as computer organization is concern Fig: CPU and main memory • Processor system and its operations: Data Movement Operations. It is moving data from memory to the CPU It is moving data from memory to memory. It performs all input and output. Arithmetic and Logical Operations. It performs all integer arithmetic. It compares two quantities shifting, rotating bits in a quantity, testing, comparing, and converting bits • CPU: manages the instruction-execution cycle. FETCH – DECODE – EXECUTE. Coordinates the activities of other devices. Different types of CPU operations are, starting a program Halting a program, skipping to other instructions, testing data to decide whether to skip over some instructions.
Introduction to computer 5 Fig: inside CPU • Memory: (fast access) storage device for preserving binary data and instructions. Memory is divided into units or words. Each is usually a standard size or fixed-length. Each memory word has a unique address for random access. It has two types RAM and ROM. Random Access Memory (RAM). It is readable, writeable, usually volatile (e.g., Dynamic RAM or DRAM) used as general storage. ROM is Read Only Memory (ROM).It is readable, permanent, nonvolatile,Special-purpose storage for data and instructions. • Input/output system • Input/output devices • Secondary storage i. Main memory is organization ii. Types of instructions for a typical processor iii. Scale and performance factors 1.5  Number systems The “base” or a “radix” is the number of different digits or combination of digits and letters that a system of counting uses to represent numbers. There are different types of number systems depending upon the base or radix. There are different types of number systems are as follows: • Binary (radix=2): 1000111101 (radix = 2) • Ternary (radix=3): 0 to 3 • Octal (radix=8): 0 to 7 • Decimal (radix=10): 0 to 9 • Hexadecimal (radix=16): 0 to 9 and A, B, C, D, E, F • BCD, EBCD, Excess3, BCO(Binary Coded Octal), BCH(Binary Coded Hexadecimal) • Binary, octal, decimal and hexadecimal are called positional number system
Computer Concepts and Fundamentals of Programming 6 1.5.1  Decimal to binary conversion: 1)	(37)10 = (100101)2 q r 2 37 1 2 18 0 2 9 1 2 4 0 2 2 0 2 1 1 2 0 2)	(41.68755)10 = (101001.1011)2 q r 2 41 1 2 20 0 2 10 0 2 5 1 2 2 0 2 1 1 2 0 Note: conversion from radix 10 to any base –r system similar to the above example only 2 will replaced by r 1.5.2  Decimal to Octal Conversion	(153.153)10 = (231.406517)8 q r 8 19 1 8 2 3 8 0 2 1.5.3  Decimal to Hexadecimal Conversion	(253)10 = (FD)16 q r 16 253 13(D) 16 15 15(F) 100101 101001 0.68755 × 2 = 1.3750 0.3750 × 2 = 0.7500 0.7500 × 2 = 1.5000 101 231 0.153 × 8 = 4.104 0.104 × 8 = 0.832 0.832 × 8 = 6.656 0.656 × 8 = 5.248 0.248 × 8 = 1.984 0.984 × 8 = 7.872 0.406517 FD
Introduction to computer 7 1.5.4  Binary to Decimal Conversion (101101)2 = 25 × 1+24 × 0 +23 × 1 + 22 × 1 + 21 × 1 + 20 × 1 (101101)2 = 32 + 8 + 4 + 1 = (45)10 1.5.5  Binary to Hexadecimal conversion (1100101001010010)2 = (CA52)16 i. First, split the binary number into groups of four digits, starting with the least significant digit. ii. Next, convert each group of four binary digits to a single hex digit. iii. Put the single hex digits together in the order in which they were found, and you’re done! 1100 1010 0101 00102 C A 5 2 1.5.6  Hexadecimal to Decimal Conversion A hexadecimal number can be converted into its equivalent number in decimal system by calculating the sum of the products of each symbol multiplied by its corresponding place value. Examples (6B39)16 = (27449)10 (6 × 163 ) + (11 × 162 ) + (3 × 161 ) + (9 × 160 ) = 24567 + 2816 +48 + 9 = 27449 1.5.7  Octal to Decimal conversion An octal number can be converted into its equivalent number in decimal system by calculating the sum of the products of each digit multiplied by its corresponding place value. (13256)8 = (5806)10 into its equivalent in decimal systems (1 × 84 ) + (3 × 83 )+(2 × 82 ) + (5 × 81 )+(6 × 80 ) = 4096 + 1536 + 128 + 40 + 6 = 5806 1.5.8  Octal to Hexadecimal conversion The given octal number can be converted into its equivalent hexadecimal number in two different steps: i. Convert the given octal number into its binary equivalent by representing each digit in the octal number to its equivalent 3-bit binary number. ii. Divide the binary number into 4-bit sections starting from the least significant bit Example: (365)8 = (F5)16 3 6 5 011 110 101 0000 1111 0101 0 F 5 } } } }
Computer Concepts and Fundamentals of Programming 8 1.5.9  Binary coded decimal The BCD system is employed by computer systems to encode the decimal number into its equivalent binary number. This is generally accomplished by encoding each digit of the decimal number into its equivalent binary sequence. The main advantage of BCD system is that it is a fast and efficient system to convert the decimal numbers into binary numbers as compared to the pure binary system. The 4-bit BCD system is usually employed by the computer systems to represent and process numerical data only. In the 4-bit BCD system, each digit of the decimal number is encoded to its corresponding 4-bit binary sequence. The two most popular 4-bit BCD systems are: • Weighted 4-bit BCD code • Excess-3 (XS-3) BCD code 1.5.10 EBCDIC The EBCDIC code is an 8-bit alphanumeric code that was developed by IBM to represent alphabets, decimal digits and special characters, including control characters. The EBCDIC codes are generally the decimal and the hexadecimal representation of different characters. This code is rarely used by non IBM-compatible computer systems. 1.5.11  ASCII code The ASCII code is pronounced as ASKEE and is used for the same purpose for which the EBCDIC code is used. However, this code is more popular than EBCDIC code as unlike the EBCDIC code this code can be implemented by most of the non-IBM computer systems. Initially, this code was developed as a 7-bit BCD code to handle 128 characters but later it was modified to an 8-bit code. 1.5.12  Gray Code Gray code is another important code that is also used to convert the decimal number into 8-bit binary sequence. However, this conversion is carried in a manner that the contiguous digits of the decimal number differ from each other by one bit only. Decimal Number 8-Bit Gray Code 0 00000000 1 00000001 2 00000011 3 00000010 4 00000110 5 00000111 6 00001111 7 00001011 8 00001001 9 00001101 We can convert the Gray coded number to its binary equivalent by remembering the following two major rules: • The Most Significant Bit (MSB) of the Gray coded number and the equivalent binary number is always the same. • The next-to-most significant bit of the binary number can be determined by adding the MSB of the binary number to the next-to-most significant bit of the gray coded number.
Introduction to computer 9 1.5.12  1! and 2 ! Complement Fixed point representation and floating point representation +ve numbers are stored in register of digital computer in sign magnitude form Negative numbers are stored in three different way a. Signed magnitude representation b. Signed 1s complement representation c. Signed 2s complement representation Why do we require 1! and 2! Complement? One’s complement and two’s complement are two important binary concepts. Two’s complement is especially important because it allows us to represent signed numbers in binary, and one’s complement is the interim step to finding the two’s complement.Two’s complement also provides an easier way to subtract numbers. Example (9)10 to binary is (0 0001001)2 Note: here MSB 0 indicate + sign (-9)10 to binary is a. 1 0001001 signed magnitude b. 1 1110110 signed 1s complement c. 1 1110111 signed 2s complement Note: 2s complement can be formed by leaving LSB unchanged and remaining taking 1s complement 1.5.13  Rules for binary addition and subtraction a. Addition b. Subtraction 0 + 0 = 0 0 - 0 = 0 0 + 1 = 1 0 - 1 = 1 borrow 1 1 + 0 = 1 1 - 0 = 1 1 + 1 = 1 carry 0 1 - 1 = 0 Example 1. Addition 2. Subtraction 1 0 1 1 0 1 (Augend) 1 0 1 1 0 1 (Minuend) 1 0 0 1 1 1 (Addend) 1 0 0 1 1 1 (Subtracted) 1 1 1 1 1 0 1 0 1 0 0 0 0 0 1 1 0 Sum = 1010100 Difference=1010100 1.5.14  Binary Multiplication The multiplication of two binary numbers can be carried out in the same manner as the decimal multiplication. Unlike decimal multiplication, only two values are generated as the outcome of multiplying the multiplication bit by 0 or 1 in the binary multiplication. These values are either 0 or 1.
Computer Concepts and Fundamentals of Programming 10 The binary multiplication can also be considered as repeated binary addition. Therefore, the binary multiplication is performed in conjunction with the binary addition operation. A B A×B 0 0 0 0 1 0 1 0 0 1 1 1 1 1 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 1.5.15  Binary Division Binary division is also performed in the same way as we perform decimal division. Like decimal division, we also need to follow the binary subtraction rules while performing the binary division. The dividend involved in binary division should be greater than the divisor. The following are the two important points, which need to be remembered while performing the binary division. If the remainder obtained by the division process is greater than or equal to the divisor, put 1 in the quotient and perform the binary subtraction. If the remainder obtained by the division process is less than the divisor, put 0 in the quotient and append the next most significant digit from the dividend to the remainder. Example Perform the binary division of the decimal numbers 18 and 8. The equivalent binary representation of the decimal number 18 is 10010. The equivalent binary representation of the decimal number 8 is 1000. 1.2.16  Floating point representation 1 0 0 0 ) 1 0 0 1 0 ( 1 0 → Quotient 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 → Remainder Floating-point numbers are the numbers containing two different parts, integer part and fractional part. The floating-point numbers are also referred as real numbers. A notation known as scientific notation is used to represent the real numbers in the computer system. The scientific notation, also called exponential notation, represents the real numbers in the following form: 325.123 → 3.25123 × 102 0.000000245 → 2.45 × 10-7 1000.0101 → 1.0000101 × 23 4333.123 4.333123 × 103 43.33123 × 102 433.3123 × 101
CHAPTER – 2 COMPUTER SOFTWARE 2.1  Computer software Computer software is software programs, applications, scripts, code written in any computer language which can be executed and instruction. In order to access hardware directly it requires software. In other word various kinds of programs used to operate computers and related devices can be also termed as software. 2.2  Types of software i. System software a. Operating system	Operating system is an interface between the hardware and the user. b. System utility ii. Application software a. Word processing b. Spread sheets c.	Database d. Web browser 2.3  Compter networking 2.3.1  Types of computer networks i. LAN • This is a local area network up to 100 meters with speed of 100 Mbps to 1000 Mbps • Any computer network for business, school, and college is termed as local area network. • LAN can bet connected to other LAN by means of bridges • Multiple LAN connected forms a WAN • On LAN users can share expensive devices, such as laser printers, as well as data.  • It works much faster as compared to traditional telephone network • Topology, Protocol and media distinguishes one LAN from another • Number of devices are connected by means of switch, or stack of switches, using a private addressing scheme. • The media generally used for LAN is twisted pair cables or coaxial cables • Less congestion in the network
Computer Concepts and Fundamentals of Programming 12 ii. MAN • This A metropolitan area network. It is larger than LAN or group of LAN • A network up to a city, big university, telephone company network is termed as MAN • It interconnect several local area networks by bridging them with backbone lines • Less fault tolerance and more congestion in the network • It is costlier than Lan for implementation • Devices used are Modem ,Wire/Cable, repeaters • It’s hard to design and maintain a Metropolitan Area Network. • Data transfer rate and the propagation delay is moderate iii. WAN • This a wide area network • Data speed is lower 1/10 th of LAN • Propagation delay is one of the biggest problems • It has two types asynchronous transfer mode (ATM) network and Point-to-Point WAN • Devices used in WAN are Optic wires, Microwaves and Satellites.  • Communication medium used is PSTN or Satellite Link. • More noise and error in data transmission There are other types of networks other than this are as follows i. PAN (Personal Area Network) ii. SAN (Storage Area Network) iii. EPN (Enterprise Private Network) iv. VPN (Virtual Private Network) 2.3.2 Topology Method of arranging and connecting different computer on the network with different way is termed as topology. There are different topologies as follows: Fig: 5.1
Computer software 13 i. BUS topology • All computers are connected by means of single backbone cable • Terminators are used to avoid the bouncing of the signals • There is no dedicated client server architecture existing in this topology • All computers are connected by means of T connectors to the backbone cable • Failure of backbone cable bring down the complete network ii. STAR topology • All computers are connected in star fashion by means of switch • Message is being broadcasted • Wastage of bandwidth • Failure of centralize switch bring down the complete network • Switch/hub can act as repeater or signal booster. • Unshielded Twisted Pair (UTP) Ethernet cable is used to connect computers. • Failure of one node does not affect the network • Performance such topology is depended on capacity of central device iii. RING topology • All the devices are connected to each other in the shape of a ring or a loop. • It connects all nodes and forms a closed loop. • Here new term token is used • Computer wants to pass a message, then it catches the token, attaches a message, and then transmits around the network. When its transmission is complete, the device passes the token to the next. • It much secure way of communication • Moving, adding and changing devices may affect the network • No need for network server to control the connectivity • A dual ring topology can be used as a backup if the first ring fails. • Slower than a star topology. iv. MESH topology • It has two types full mesh and partial mesh topology • In full mesh topology every node is connected with rest of the node • It is very expensive topology.it will need a lot of capital to invest • A broken node won’t distract the transmission of data in a mesh network. • It has huge bandwidth • It makes large data center • Maintaining mesh networks can be very hard to manage. • Network redundancy problem v. TREE topology • Its combination of BUS and Star topology • It is highly scalable topology • Identifying the faulty is easy • Best for implementation of temporary networks.
Computer Concepts and Fundamentals of Programming 14 • Point to point connection for every devices • If one device is damaged it doesn’t affect the network • Failure of backbone cable bring down the complete network • This network is insecure, anybody can see transmitted data. • As more and more nodes maintenance becomes difficult vi. CELLULAR topology • This topology is mainly used for mobile communication. • It forms cellular structure and any authentic mobile device comes in vicinity of the network gets connected with the network. • Every cell represents cell represents a portion of the total network area. • In this topology every node transmits in a certain area called a cell. • Data transmission is in the form of cellular digital packet data. 2.3.3  Computer network devices i. HUB • Hub is generally used in LAN. • There are two types of hub active (with external power supply) and passive(without external power supply). • It handles a data types like frames then transmits to the destination port • Hub broadcasts the data • Hubs are stupid devices as they cannot distinguish between data ,which port a frame should be sent to • Passive hub don’t amplify the signals • Hubs works in data link layer of OSI reference model. ii. Switch • Switches is generally used in LAN. • Switches works in data link layer of OSI reference model. • It handles a data types like frames then transmits to the destination port • It filters the packets and regenerating forwarded packets. • It reduces the collision rate. • Many switches are self-learning. • Switches may have different port with different speed of transmission. • Almost one-half of the nodes connected to a switch can send data at the simultaneously. iii. Router • It works in the network layer of OSI reference model • It filter out network traffic • It dividing networks logically instead of physically. • Ip router divides network into many segments • It routs the packet to the particular network • There are two types of router static and dynamic • For every packet it calculate checksum, and rewrite the MAC header
Computer software 15 iv. Bridge • It connects two or more LAN networks • It works in data link layer of OSI reference model • It segment’s the larger network • It has the capacity to block the incoming flow of data. • It can build a list of the MAC addresses • The types of bridges are Transparent Bridge, Source Route Bridge, Translational Bridge v. Gateway • It is a stopping point for data from other networks • This is a specialized computer.It also operates as a firewall and a proxy server. • It controls all of the data traffic your Internet Service Provider (ISP) • It keeps out unwanted traffic to get in private network. • Network interface cards (NIC/LAN card) • This is also called as LAN card, Ethernet card ,interface controller card, expansion card, network card, network adapter or network adapter card (NAC) • This is working in the physical layer of OSI reference model • It has RJ45 port through which it gets connected to network 2.3.4  OSI reference model Fig: OSI reference model
Computer Concepts and Fundamentals of Programming 16 2.3.5 TCP/IP TCP/IP is normally considered to be a 4 layer system. The 4 layers are as follows: i. Application layer ii. Transport layer iii. Network layer iv. Data link layer Application layer This layer includes applications or processes that use transport layer protocols to deliver the data to destination computers. The list of application layer protocols are: i. HTTP (Hypertext transfer protocol) ii. FTP (File transfer protocol) iii. SMTP (Simple mail transfer protocol) iv. SNMP (Simple network management protocol) etc. Transport layer: This is a backbone to data flow between two hosts. This layer receives data from the application layer above it. There are many protocols that work at this layer but the two most commonly used protocols at transport layer are TCP and UDP. Network layer: The main purpose of this layer is to organize or handle the movement of data on network. The main protocol used at this layer is IP. While ICMP (used by popular ‘ping’ command) and IGMP are also used at this layer. Data link layer: This layer mainly consists of device drivers in the OS and the network interface card attached to the system. Both the device drivers and the network interface card take care of the communication details with the media being used to transfer the data over the network. Fig: TCP/IP layered model 2.3.6 Firewall A firewall is a protective barrier between your PC and internet. When you are connected to the Internet, you are a potential target to of cyber threats, such as hackers that attack through security loopholes. Types of firewall are as follows Hardware: A hardware firewall can be a router or any other security product that is placed between your PC and the outside world. More than one PC can be connected with that security device or router, and each will be protected by the firewall.
Computer software 17 Software: A software firewall is installed on your PC, it will deflect incoming attacks and hide open ports. It will warn you about suspicious outgoing traffic. You can have a software firewall on each computer for strong protection. By installing software firewall, an attacker will have to cross two level security to access your PC. Fig: Firewall 2.3.7  IP and classes of IP(IPV4) This 32 bit address mechanism for addressing the devices on the network. Different classes of IP address as per the IPV4 standard are as follows: v. Class A –(0-126) vi. Class B-(128-191) vii. Class C-(192-223) viii. Class D-(224-239) ix. Class E-(240-255) The 127 is used by the local host as loop back adapter and for the inter processes communication. In the above list class D and E are used for the experimental purpose.
CHAPTER – 3 INTRODUCTION 3.1  Origin of C language ‘C’ is a multi-purpose language (including system programming) whose development is linked to UNIX operating system. Many of the features of ‘C’ language stem from BCPL (developed by Martin Richards) and B (developed by Ken Thompson). Both BCPL and B are “type less” languages while C provides a variety of data types. It may not be an exaggeration to say that 'C' programming language, developed by Dennis Ritchie, circa 1969-1973 (although quite a few book quote the year as 1972), is one of the most powerful, general-purpose programming languages which has also inspired many other languages. In 1978, Dennis Ritchie and Brian W. Kernighan published the seminal book The C Programming Language (the version of the language described in the book is known as KR C) which served as a language definition and a formal reference that helped in vast popularization of the 'C' language. In 1983, ANSI instituted the X3J11 committee which was assigned a goal of developing a 'C' standard. The X3J11 committee produced its report by the end of 1989 – ANSI X3.159- 1989 “Programming Language C”. This version of 'C' is known as C89. This standard was ratified by ISO as ISO/IEC 9899-1990 (sometimes referred to as C90). In fact, C89 and C90 refer to the same language. In 1995, ISO released an extension to the internationalization support to the standard. This version is known as C95. A revised standard was again released in 1999 (now known as C99). In 2007, work began on yet another revision of the C standard resulting in the development of the C11 standard which was approved in December 2011. C89 contains 32 keywords which are given below: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C99 has 37 keywords. The five new keywords which were added are: _Bool, _Complex, _Imaginary, inline, restrict C11 has 44 keywords. The seven new keywords which have been added are: _Alignas, _Alignof, _Atomic, _Generic, _Noreturn, _Thread_local, _Static_assert Interestingly, 'C' language used to include a reserved keyword called entry, which in fact was never implemented and now has been removed as a reserved word.
Introduction 19 3.2  Why C? 3.3  Structure of C program 3.3.1  Performing addition of two numbers with following constraint a) do not use –(-) operation b) do not use *(-1) operation c) do not use (a2-b2)/a-b operation #includestdio.h main() { int add ,diff, a,b; printf(nEnter the value of two numbersn ); scanf(%d%d,a,b); add = 2*a; diff = a - b; add=add-diff; printf(nThe addition of 2 nos without using + is:==%d ,add); } 3.3.2  The first function to be executed in a ‘C’ program: All 'C' programmers know that the main() function is the entry point for a 'C' program. Can a user-defined function be executed before the main() function in a 'C' program? Can a user-defined function be executed after the last statement in main() function in a 'C' program? Can the main() function be called explicitly from within another function? Can the return value from the main() function be utilised in a program? These questions often pose a serious challenge to a 'C' programmer. The program below (compiled using gcc) answers the aforementioned questions: /*The code below is explained in greater detail in Chapter 2*/ #includestdio.h void func1(void) __attribute__((constructor)); void func2(void) __attribute__((destructor)); main() { printf(nWithin main()); return -8; } void func1() { system(clear); printf(nWithin func1()); }
Computer Concepts and Fundamentals of Programming 20 void func2() { int k = main(); printf(nWithin func2(), k = %d, k); } A sample output of the program is given below: Within func1() Within main() Within main() Within func2(), k = -8 The output of the above code testifies that func1() is called first, after which main() function is executed, after which func2() function is called, which in turn explicitly calls main() function which in turn returns -8 which is stored in integer variable k. [N.B. Two underscores precede the word attribute and two underscores follows the word attribute in the statements: void func1(void) __attribute__((constructor)); and void func2(void) __attribute__((destructor));] For those working on the TurboC compiler, the following program can be used: #includestdio.h void func1(); void func2(); #pragma startup func1 #pragma exit func2 main() { printf(nWithin main()); return -8; } void func1() { system(clear); printf(nWithin func1()); } void func2() { int k = main(); printf(nWithin func2(), k = %d, k); }
Introduction 21 3.4.2  Executing a ‘C’ program using gcc Open an editor like gedit, kwrite Type the c program and save it with the extension .c if no error(s) then type the command: ./a.out Open terminal and type command gcc filename.c Compiling a 'C' program using gcc: exploring a few switches The gnu C compiler is widely used because of its versatility (it can carry out preprocessing, compilation, assembly and linking) and also it has set unmatched standards in terms of reliability. The gnu C compiler actually works in stages. The stages are as follows: the Source Code is converted into Translation Unit the Translation Unit is converted into Assembly Code the Assembly Code is converted into Object Code the Object Code is converted into an Executable File. As an instance, if a program is saved by the name test57.c, then on issuing the command: gcc test57.c the intermediate stages might be visualized as follows: test57.c → test57.i → test57.s → test57.o → a.out The following switches can be used with the gcc command line in order to examine the intermediate stages: gcc –E test57.c (in order to obtain the Translation Unit equivalent. In short the –E option tells gcc to stop compilation after preprocessing) gcc –S test57.c (in order to obtain the Assembly Code) gcc –c test57.c (in order to obtain the Object Code). gcc test57.c (in order to obtain the executable file a.out) [NOTE: The options –E and –S are in uppercase] Let us consider the code snippet (saved in a file test57.c, for instance) shown below: #includestdio.h main() { printf(Computer Science); return 0; }
Computer Concepts and Fundamentals of Programming 22 In order to examine the intermediate assembly language file, the following commands can be used. $ gcc -S test57.c $ cat test57.s will produce the intermediate assembly language listing of the above code snippet. The command $ gcc -o test test57.c makes an executable file by the name of test. In order to look at the output now, the user can type the following command at the command line: $./test instead of typing./a.out. The GNU Compiler Collection (gcc) can compile programs written in several high level languages such as FORTRAN, C, C++, Java, Objective-C, etc. In order to determine languages whose programs can be compiled using gcc, the Package Manager rpm* can be used as illustrated below: $ rpm -qa | grep gcc A sample interaction with rpm (using it as suggested above) might appear as follows: compat-gcc-34-g77-3.4.6-4 gcc-4.1.2-14.el5 gcc-gfortran-4.1.1-52.el5 compat-gcc-34-c++-3.4.6-4 gcc-java-4.1.1-52.el5 compat-gcc-34-3.4.6-4 gcc-c++-4.1.1-52.el5 compat-libgcc-296-2.96-138 libgcc-4.1.2-14.el5 gcc-objc-4.1.1-52.el5 *rpm is a package manager which can be used to build, install, update, query and erase individual software packages. [N.B. gcc used to be the GNU 'C' Compiler, but is now used for GNU Compiler Collection.] In order to compile the program, the following instruction needs to be typed: gcc program-name.c -trigraphs To find out the version of gcc, one can use gcc -v The gdb utility in Linux gdb (GNU debugger) is an efficient utility for debugging a program that has been compiled by gcc (GNU compiler collection). In order to start gdb the user is only required to type gdb and press ENTER at the command line (although there are many alternatives of starting gdb). Let us understand using gdb through a sample program (Program listing one) Program listing one
Introduction 23 #includestdio.h main() { double num1, num2, quot; printf(Enter the numerator: ); scanf(%lf, num1); printf(Enter the denominator: ); scanf(%lf, num2);	quot=num1/num2; printf(n%lf/%lf=%lf, num1, num2, quot); return 0; } Suppose the above program is stored in a file by the name of test.c. In order to compile the program, the user may type: $ gcc -g test.c -o test It may not be meaningful to use gdb by compiling the program without the -g switch, since gdb will not have information related to variable names, function names, line numbers, etc. Once the program is compiled, the user can type $ gdb test Now, in order to run the program, the user can type run (or r) at the gdb prompt and press ENTER. [NOTE: The user can also type gdb -quiet test or gdb -q test in order to suppress the introductory and copyright messages which are displayed when gdb is invoked.] In order to list the program, the user can type list (or l) at the gdb prompt and press ENTER. In order to set a breakpoint at line number 10, the user can type b 10 at the gdb prompt and press ENTER. Function name can also be used for setting a breakpoint at the first executable statement within the function. After pausing at the indicated line, the user can type continue (or c) in order to continue executing the program. The breakpoint(s) can be deleted through the delete command. Once a breakpoint has been set, then the commands n (for next) and s (for step) can also be used to execute the next line of the program. The commands n and s work differently if the next line happens to be a function call. If n is used then the next pause will be at the statement following the function call, whereas, if s is used then the next pause will be at the first line of the function which is invoked. The bt command can be used for printing the current location within the program and the stack trace showing how the current location was reached if a function calls another function or itself i.e. there has been a series of function calls. The kill command can be used in order to terminate the program being executed in gdb. The help command can be typed at the gdb prompt if the user feels stuck anywhere. If the user wants to quit the gdb utility then the user should type q and press ENTER.
CHAPTER – 4 DATA TYPES AND OPERATORS 4.1  Data Types Data (singular: datum, plural: data) are a collections of facts and figures. Data will be of particular type. For instance, 786 is an integer, 0.23 is a fractional value and ‘x’ is a letter of the English alphabet. The built-in data types in ‘C’ are as follows: Type Example Format specifier char char c = ‘a’; %c int int num = 786; %d, %i float float f = 0.3f %f, %e, %E, %g, %G double double d = 0.9876 %lf void Used with functions and pointers. It is wrong to write void a. Format specifiers are also known as conversion characters/format code. In ‘C’, a string is an array of characters terminated by the NULL character ‘0’ – backslash zero. The format specifier for string is %s. Use of Format specifiers %o and %x
Data types and operators 25 Sample Program 4.1 /* for printing octal and hexadecimal equivalents of an integer */ #includestdio.h main() { int num = 9123; printf(nIn base 10, num = %d, num); printf(nIn base 8, num = %o, num); printf(nIn base 16, num = %x, num); return 0; } A sample output is shown below: In base 10, num = 9123 In base 8, num = 21643 In base 16, num = 23a3 Sample Program 4.2 /*When 0 (zero) and 0x precede an integer*/ #includestdio.h main() { int num1 = 03672; /* when an integer begins with 0, then it implies that it is an octal integer*/ int num2 = 0x3672; /* when an integer begins with 0x, then it implies that it is an hexadecimal integer*/ int num3 = 3672; printf(nnum1 = %d, num1); printf(nnum2 = %d, num2); printf(nnum3 = %d, num3); return 0; } A sample output is shown below: num1 = 1978 num2 = 13938 num3 = 3672 In C99, _Bool is also a data type. _Bool is a datatype for Boolean (true/false). The stdbool.h header files defines an alias bool for _Bool. Arrays, structures, enumerations are derived data types in ‘C’. ‘C’ language supports user-defined datatypes also. A variable declaration statement such as int n = 953; means four bytes will be given the name n and the integer 953 will be stored in these four bytes.
Computer Concepts and Fundamentals of Programming 26 Escape sequences in ‘C’ An escape sequence in ‘C’ usually begins with the backslash () and is a sequence of two or more characters which when used inside a character or string literal is translated into another character or sequence of characters. Escape sequence Character represented a alarm i.e. a beep sound or a bell sound b backspace f formfeed n linefeed i.e. new line r carriage return t horizontal tab v vertical tab backslash ’ single quotation mark ” double quotation mark ? question mark printf(): A function for displaying output; scanf(): A function for accepting input. Obtaining an integer as input from the user: Sample Program 4.3 #includestdio.h main() { int num; printf(Enter an integer: ); scanf(%d, num); printf(nThe integer you entered is: %d, num); return 0; }
Data types and operators 27 A sample output is shown below: Enter an integer: 786 The integer you entered is: 786 Sample Program 4.4 Obtaining a fractional number as input from the user: #includestdio.h main() { float num; printf(Enter a fractional value: ); scanf(%f, num); printf(nThe fractional value you entered is: %f, num); return 0; } A sample output is shown below: Enter a fractional value: 0.34 The fractional value you entered is: 0.340000 The sizeof() operator [sizeof() is an unary operator] in C can be used to determine the size (in bytes) of a variable, constant or datatype. Sample Program 4.5 #includestdio.h main() { printf(nsizeof(0.93) = %d, sizeof(0.93)); printf(nsizeof(0.93f) = %d, sizeof(0.93f)); printf(nsizeof(71) = %d, sizeof(71)); printf(nsizeof(71L) = %d, sizeof(71L)); /*lowercase L can also be used*/ return 0; } Obtaining a string as input from the user: Sample Program 4.6 #includestdio.h main() { char name[80]; printf(Enter your name: ); scanf(%s, name); printf(nThe name you entered is: %s, name); return 0; }
Computer Concepts and Fundamentals of Programming 28 Enter your name: Ganesh Ingle The name you entered is: Ganesh When reading a string through scanf(%s, name); The scanf() stops reading after the first whitespace (tab, space or Enter). Therefore Ingle was not stored in name. In order to read blank spaces into a string variable, the scanf() function can be used as illustrated below: Sample Program 4.7 #includestdio.h main() { char name[81]; printf(nEnter your name: ); scanf(%[^n]s, name); /* whatever you type before pressing the ENTER key will be stored in name*/ printf(nYou entered: %s, name); return 0; } Enter your name:Ganesh Ingle You entered: Ganesh Ingle Sample program 4.8 /* Program illustrating the use of sizeof() operator */ #includestdio.h main() { printf(nsizeof(char) = %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(long int) = %d, sizeof(long int)); return 0; } sizeof(char) = 1 sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 sizeof(long int) = 4 sample program 4.9: The program below exemplifies the use of long long in 'C' langauage. Program listing #includestdio.h main() { long long n=1; /* The range of long long is from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 */ int i;
Data types and operators 29 system(clear); for(i=1;i11;i++) { printf(n%lld,n*n); n=n*10+1; } return 0; } Sample program 4.10. To print the message I am the one without using any semicolon through out the program #includestdio.h main() { if(printf(I am the one)) { } } 4.11 The program to print message without using {,} in the program using di graph. #includestdio.h main() % printf(nhello welcome to TMIn); printf(nGMn); printf(nnCompletedn); % Sample program 4.12The program to print message without using {,} in the program using tri-graph characters. #includestdio.h main() ?? printf(nhello welcome to TMIn); printf(nGMn); printf(nnCompletedn); ?? 4.2  Data models The choices made by each implementation about the sizes of the fundamental types are collectively known as data model. Four data models found wide acceptance: 32 bit systems: • LP32 or 2/4/4 (int is 16-bit, long and pointer are 32-bit) • Win16 API
Computer Concepts and Fundamentals of Programming 30 • ILP32 or 4/4/4 (int, long, and pointer are 32-bit); • Win32 API • Unix and Unix-like systems (Linux, Mac OS X) 64 bit systems: • LLP64 or 4/4/8 (int and long are 32-bit, pointer is 64-bit) • Win64 API • LP64 or 4/8/8 (int is 32-bit, long and pointer are 64-bit) • Unix and Unix-like systems (Linux, Mac OS X) Other models are very rare. For example, ILP64 (8/8/8: int, long, and pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. Unicos on Cray). 4.3 Constants Constants are of two types a. Numeric Constants • Integer Constants (eg. 1,-15, 045, 0X6) • Real Constants (eg.3.14) b. Character Constants • Single Character Constants(eg. ‘5’ ,’z’) • String Constants (eg. “IMU” • Backslash Character Constants Eg: Constants Meaning a beep sound b backspace f form feed n new line r carriage return t horizontal tab v vertical tab ' single quote double quote backslash 0 null
Data types and operators 31 4.4 Operators 4.4.1  Arithmetic Operators Operator Description Example + Adds two operands. A + B = 30 − Subtracts second operand from the first. A − B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 -- Decrement operator decreases the integer value by one. A-- = 9 4.4.2  Relational Operators Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A B) is not true. Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A B) is true. = Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A = B) is not true. = Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A = B) is true. 4.4.3  Logical Operators Operator Description Example Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A B) is true. Sample Program 4.13 /*illustration of postfix and prefix */ #includestdio.h main() { int num1 = 7; int num2, num3; num2 = num1++; /*first assign the value of num1 (7 in this case) to num2 and thereafter increment the value of num1*/ printf(nnum1 = %d, num1); printf(nnum2 = %d, num2); num3 = ++num1; /*first increment the value of num1, and then assign the value of num1 to num3*/ printf(nnum1 = %d, num1);
Computer Concepts and Fundamentals of Programming 32 printf(nnum3 = %d, num3); return 0; } A sample output is shown below: num1 = 8 num2 = 7 num1 = 9 num3 = 9 Sample program 4.14 /* to find the angle between the hour hand and the minute hand*/ #includemath.h #includestdio.h main() { int h, m; double a1, a2; system(clear); printf(nthis code determines the angle between the hour hand and the minute hand); printf(Enter time (h m): ); scanf(%d %d, h, m); a1 = fabs(((h * 30) + (m * 1/2.0)) - (m * 6)); a2 = 360 - a1; printf(nTime = %d:%d, h,m); printf(nAngle between the hour hand and minute hand: %lf %lf, a1,a2); printf(nnCompletedn); return 0; } 4.4.4  Ternary operator Conditional operators return one value if condition is true and returns another value is condition is false.This operator is also called as ternary operator. Syntax: (Condition? true_value: false_value); Example:	(A 100? 0: 1); 4.4.5  Bitwise Operator p q p q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
Data types and operators 33 Operator Description Example Binary AND Operator copies a bit to the result if it exists in both operands. (A B) = 12, i.e., 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -61, i.e,. 1100 0011 in 2's complement form. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A 2 = 240 i.e., 1111 0000 Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A 2 = 15 i.e., 0000 1111 4.4.6  Assignment operator Operator Description Example Binary AND Operator copies a bit to the result if it exists in both operands. (A B) = 12, i.e., 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -61, i.e,. 1100 0011 in 2's complement form. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A 2 = 240 i.e., 1111 0000 Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A 2 = 15 i.e., 0000 1111 4.4.7  Programs for practice Write a C program to solve following problems 1. To find the square of the number given by user. 2. To perform addition of two numbers entered by user. 3. To perform addition of two numbers without using + operator. 4. To calculate average of three real numbers entered by user. 5. To input a single character and display it with proper message. 6. To show the effect of various escape sequences. 7. To swap the values of two variables without using third variable. 8. To input the rainfall of three consecutive days in cms and find its a average. Print the output with proper messages. 9. Find the simple interest. Inputs are principal amount, period in year and rate of interest. 10. To enter a integer number and carry out modular division operation by 2,3 and 6 and display the result. 11. To find the average temperature of five sunny days. Assume the temperature in Celsius. 12. Find the area and perimeter of a) Square b) Rectangle c) triangle Accept the sides as input from user. 13. The speed of a van is 75 km/hr. Write a program to find the number of hours required for covering a distance of 500 km. 14. Write a program to evaluate the following expressions and display their results. 15. x2 + 2x3*(2*x) 16. (x+y+z)2 17. Write a program to read three integers from the keyboard using one scanf statement and output them on one line using: 18. Three printf statements, 19. Only one printf with conversion specifiers.
Computer Concepts and Fundamentals of Programming 34 20. Calculate the volume and area of a sphere using the formulas: 21. V = 4µr3/3 22. A = 4µr2 23. test the program using the values for the radius. 24. WAP to Calculate the mass of air in an automobile tire, using the formula PV = 0.37m(T + 460)where P = pressure in pounds per square inch, V= volume in cubic feet, m=mass of air in pounds, T=temp. In Fahrenheit. The tire contains two cubic feet of air. Assume that the pressure is 32psi at room temperature.
CHAPTER – 5 DECISION CONTROL INSTRUCTIONS The decision control instructions are broadly classified as: 1. if statement 2. if else statement 3. switch case statement 5.1  if statement if (test condition) { Statement 1; Statement 2; Statement 3; …………. …………. Statement n; } 5.2  if else statement if (test condition) { Statement 1; Statement 2; …………. …………. Statement n; } else { Statement 1; Statement 2; …………. …………. Statement n; }
Computer Concepts and Fundamentals of Programming 36 5.3  nested if else statement if(condition) { //Nested if else inside the body of if if(condition2) { //Statements inside the body of nested if } else { //Statements inside the body of nested else } } else { //Statements inside the body of else } 5.4  if elseif else statement if (test condition) { Statement 1; Statement 2; …………. …………. Statement n; } else if { Statement 1; Statement 2; …………. …………. Statement n; } else { Statement 1; Statement 2; …………. …………. Statement n; }
Decision control instructions 37 5.5  switch case statement The syntax of switch case construct is as follows Switch ( expression ) // this expression can int or char it should not be float or string { case value-1:	block-1;	break; case value-2:	block-2;	break; case value-3:	block-3;	break; case value-4:	block-4;	break; default:	default-block;	break; } 5.6  goto statement Generally goto is a unconditional jumping statement. It can be used as a loop statement as well. Beacusae of unconditional jumping it is not advised to use goto statement. Sample code that illustrates goto statement as follows #includestdio.h #includeconio.h void main() { int number; clrscr(); printf(“Mango”); goto x; // here x is a label not a variable of any type ,program jumps to the label x abruptly. y: printf(“Orange”); goto z; // here z is a label not a variable of any type ,program jumps to the label z abruptly. x: printf(“Banana”); goto y; // here y is a label not a variable of any type ,program jumps to the label z abruptly. z: printf(“Apple”); getch(); }
Computer Concepts and Fundamentals of Programming 38 Sample Program 5.1 Write a program to check whether the entered year is a leap year or not considering century year condition (IMU question paper May June 2016) #include stdio.h #include conio.h int main() { int year; printf(Enter a year: ); scanf(%d,year); if(year%4 == 0) { if( year%100 == 0) { // year is divisible by 400, hence the year is a leap year if ( year%400 == 0) printf(%d is a leap year., year); else printf(%d is not a leap year., year); } else printf(%d is a leap year., year ); } else printf(%d is not a leap year., year); getch(); return 0; } Or Other logic #include stdio.h #include conio.h int main() { int year; printf(Enter a year: ); scanf(%d,year); if(year=1752) { if(year%4 == 0) printf(%d is a leap year., year ); else printf(%d is not a leap year., year ); } else {
Decision control instructions 39 if( year%100 == 0 year%400 != 0) printf(%d is not a leap year., year); else if( year%100 == 0 year%400 != 0) printf(%d is a leap year., year); else if(year%4 == 0) printf(%d is a leap year., year ); else printf(%d is not a leap year., year ); } getch(); return 0; } Or other logic /** * C program to check Leap Year */ #include stdio.h main() { int year; /* Read year from user */ printf(Enter year: ); scanf(%d, year); /* * Check for leap year */ if(((year%4 == 0) (year%100 !=0)) || (year%400==0)) { printf(LEAP YEAR); } else { printf(COMMON YEAR); } } Sample Program 5.2 Write program to device a calculator with menu driven program # include stdio.h # include conio.h int main() { char operator; double firstNumber,secondNumber; printf(Enter an operator (+, -, *, /): );
Computer Concepts and Fundamentals of Programming 40 scanf(%c, operator); printf(Enter two operands: ); scanf(%lf %lf,firstNumber, secondNumber); switch(operator) { case '+': printf(%.1lf + %.1lf = %.1lf,firstNumber, secondNumber, firstNumber+secondNumber); break; case '-': printf(%.1lf - %.1lf = %.1lf,firstNumber, secondNumber, firstNumber-secondNumber); break; case '*': printf(%.1lf * %.1lf = %.1lf,firstNumber, secondNumber, firstNumber*secondNumber); break; case '/': printf(%.1lf / %.1lf = %.1lf,firstNumber, secondNumber, firstNumber/firstNumber); break; // operator is doesn't match any case constant (+, -, *, /) default: printf(Error! operator is not correct); } getch(); return 0; } Sample program 5.3 Program to print three digit number in words #includestdio.h main() { int num, t, d1, d2, d3; system(clear); printf(This program is for printing a three digit integer in words: n); printf(Enter an integer: ); scanf(%d, num); if(num0) { t=-num; printf(minus ); } else if(num==0) { printf(zero); t=num; } else
Decision control instructions 41 t=num; d1=t/100; d2=(t%100)/10; d3=t%10; if(d1==1) printf(One hundred ); else if(d1==2) printf(Two hundred ); else if(d1==3) printf(Three hundred ); else if(d1==4) printf(Four hundred ); else if(d1==5) printf(Five hundred ); else if(d1==6) printf(Six hundred ); else if(d1==7) printf(Seven hundred ); else if(d1==8) printf(Eight hundred ); else if(d1==9) printf(Nine hundred ); if(d2==1) { if(d3==1) printf(Eleven); else if(d3==2) printf(Twelve); else if(d3==3) printf(Thirteen); else if(d3==4) printf(Fourteen); else if(d3==5) printf(Fifteen); else if(d3==6) printf(Sixteen); else if(d3==7) printf(Seventeen); else if(d3==8) printf(Eighteen); else if(d3==9) printf(Nineteen); } else { if(d2==2) printf(Twenty );
Computer Concepts and Fundamentals of Programming 42 else if(d2==3) printf(Thirty ); else if(d2==4) printf(Forty ); else if(d2==5) printf(Fifty ); else if(d2==6) printf(Sixty ); else if(d2==7) printf(Seventy ); else if(d2==8) printf(Eighty ); else if(d2==9) printf(Ninty ); } if(d2!=1) { if(d3==1) printf(One); else if(d3==2) printf(Two); else if(d3==3) printf(Three); else if(d3==4) printf(Four); else if(d3==5) printf(Five); else if(d3==6) printf(Six); else if(d3==7) printf(Seven); else if(d3==8) printf(Eight); else if(d3==9) printf(Nine); } printf(nnCompletedn); } Sample program 5.4 Write a program to Find the roots of quadratic equation using switch case construct /** * C program to find all roots of a quadratic equation using switch case */ #include stdio.h #include math.h //Used for sqrt() main() {
Decision control instructions 43 float a, b, c; float root1, root2, imaginary; float discriminant; printf(Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ); scanf(%f%f%f, a, b, c); discriminant = (b*b) - (4*a*c); /* * Computes roots of quadratic equation based on the nature of discriminant */ switch(discriminant 0) { case 1: //If discriminant is positive root1 = (-b + sqrt(discriminant)) / (2*a); root2 = (-b - sqrt(discriminant)) / (2*a); printf(Two distinct and real roots exists: %.2f and %.2fn, root1, root2); break; case 0: //If discriminant is not positive switch(discriminant 0) { case 1: //If discriminant is negative root1 = root2 = -b / (2*a); imaginary = sqrt(-discriminant) / (2*a); printf(Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2fn, root1, imaginary, root2, imaginary); break; case 0: //If discriminant is zero root1 = root2 = -b / (2*a); printf(Two equal and real roots exists: %.2f and %.2fn, root1, root2); break; } } } Sample program 5.5 Write a program to count minimum number of notes in an amount /** * C program to count minimum number of notes in an amount */ #include stdio.h main() { int amount;
Computer Concepts and Fundamentals of Programming 44 int note500, note100, note50, note20, note10, note5, note2, note1; note500 = note100 = note50 = note20 = note10 = note5 = note2 = note1 = 0 ; /* Reads amount from user */ printf(Enter amount: ); scanf(%d, amount); if(amount = 500) { note500 = amount/500; amount -= note500 * 500; } if(amount = 100) { note100 = amount/100; amount -= note100 * 100; } if(amount = 50) { note50 = amount/50; amount -= note50 * 50; } if(amount = 20) { note20 = amount/20; amount -= note20 * 20; } if(amount = 10) { note10 = amount/10; amount -= note10 * 10; } if(amount = 5) { note5 = amount/5; amount -= note5 * 5; } if(amount = 2) { note2 = amount /2; amount -= note2 * 2; } if(amount = 1) { note1 = amount; } printf(Total number of notes = n); printf(500 = %dn, note500); printf(100 = %dn, note100); printf(50 = %dn, note50);
Decision control instructions 45 printf(20 = %dn, note20); printf(10 = %dn, note10); printf(5 = %dn, note5); printf(2 = %dn, note2); printf(1 = %dn, note1); } Sample program 5.6 Write a program to check given number is even or odd using switch case /** * C program to check Even or Odd number using switch case */ #include stdio.h main() { int num; /* * Reads a number from user */ printf(Enter any number to check even or odd: ); scanf(%d, num); switch(num % 2) { //If n%2 == 0 case 0: printf(Number is Even); break; //Else if n%2 != 0 case 1: printf(Number is Odd); break; } } 5.7  Programs for practice 1. WAP to find the roots of a quadratic equation by using if...else condition. 2. WAP to read six numbers and find the largest one by using ladder of if...else. 3. WAP to find the average of six subjects and display the results. 4. WAP to check whether the entered year is a leap year or not with all check points 5. WAP (a menu driven)to display the names of the days of a week. 6. WAP Read the values of a,b,c through keyboard. Add them and after addition check if it is in the range of 100 200 or not. Print separate message of each. 7. WAP to convert integer to character using if condition. 8. WAP to calculate the sum of the remainders obtained by dividing with modular division operations by 2 on 1 to 9 numbers.
CHAPTER – 6 DECISION MAKING AND LOOPING 6.1  The for() loop The for() loop can be used for executing a statement/statements a specific (or infinite) number of times. The general form of the for() loop is as follows: for(expr1; expr2; expr3)	{	code block;	} expr1 is executed only once when the for() loop is executed for the first time. expr2 is evaluated every time before entry into the loop till the time it does not evaluate to false. expr3 is evaluated every time except for the first time. The for() loop is an entry-controlled loop. Different constructs of for loop (these syntax are correct syntax) • for( ;condition;) { Increment / decrement; } • for(i=0,j=0,k=100; i=200;i++,j++,k++) { } • for(;i10;i++ ) { } • for(;i10;i++ ); { } [N.B.: These programs have been executed using Dev-C++ Version 5.11] #includestdio.h main() {
Decision making and looping 47 /* printing the integers from 1 to 10 using a for() loop */ int i; for(i=1;i11;i++) { printf(ni = %d, i); } return 0; } 6.2  The while () loop: The general form of the while() loop is: while (expr) { code-block; } If the expr after while evaluates to true then the body of the while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The while() loop is an entry-controlled loop, which implies that if the expr evaluates to false right at the beginning then the body of the while loop will not be executed even once. #includestdio.h main() { /* printing the integers from 11 to 20 using a while() loop */ int j=11; while(j21)
Computer Concepts and Fundamentals of Programming 48 { printf(nj = %d, j); j++; } return 0; } 6.3  The do... while() loop The general form of the while() loop is: do { code-block; }while (expr); If the expr after while evaluates to true then the body of the do... while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do... while(); loop will be necessarily executed at least once. The do... while() loop is an exit-controlled loop. #includestdio.h main() { /* printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++;
Decision making and looping 49 }while(k=30); return 0; } 6.4  Difference between while and do while loop while do while It is entry controlled loop It is exit controlled loop The may not be executed if the condition is false to start with The loop will executed at least once while(condition) { Statement 1; Statement 2 ; Statement 3; } do { Statement 1; Statement 2 ; Statement 3; } while(condition); Sample program 6.1 Program to illustrate tribonacci series #includestdio.h int main() {int num,a=0,b=1,c=2,d=0,i; printf(nEnter the number:); scanf(%d,num); printf(%dt%dt%d,a,b,c); for(i=3;inum;i++) {
Computer Concepts and Fundamentals of Programming 50 d=a+b+c; printf(t%d ,d); a=b; b=c; c=d; } } Sample program 6.2 Tetranacci series #includestdio.h int main() {int num,a=0,b=1,c=2,d=3,e=0,i; printf(nEnter the number:); scanf(%d,num); printf(%dt%dt%d,a,b,c); for(i=3;inum;i++) { e=a+b+c+d; printf(t%d ,e); a=b; b=c; c=d; d=e; } } Sample program 6.3 Lucas series #includestdio.h main() {  int x,y,z,num;  printf(Enter the limit of Lucas number: );  scanf(%d,num);  x=2;  y=1;  while(num=x)  {    printf( %d,x);    z=x+y;    x=y;    y=z;  }
Decision making and looping 51 } Sample program 6.4 Palindrome number #includestdio.h void pal(); main() { pal(); } void pal() { int n,x,mod,rev=0; printf(nEnter No.); scanf(%d,n); x=n; while(n) { mod=n%10; rev=rev*10+mod; n=n/10; } if(rev==x) printf(n PAL n); else printf(n NOT PAL n); } Sample program 6.5 Special number #includestdio.h void sp(); main() { sp(); } void sp() { int n,x,mod,sum=0,f; printf(n Enter no.); scanf(%d,n); x=n; int i; while(n) { mod=n%10; f=1;
Computer Concepts and Fundamentals of Programming 52 for(i=1;i=mod;i++) f=f*i; sum=sum+f; n=n/10; } if(sum==x) printf(n SPL); else printf(n NOT SPL); } Sample program 6.6 Write a program to check whether the number is n- Narcissistic number #includestdio.h main() { long int cube,n,mod,sum=0,temp; printf(Enter the any number: ); scanf(%d,n); cube=n*n*n; temp=cube; digit=0; while(cube) { mod=cube%10; digit++; cube=cube/10; } cube=x; while(cube) { mod=cube%10; sum=sum+pow(mod,digit); cube=cube/10; } if(sum==n) printf(“The given number: = %d is a n- Narcissistic number”,sum); else printf(“The given number: = %d is a n- Narcissistic not number”,sum); } Sample program 6.7 Armstrong number is also n- Narcissistic page #includestdio.h main() { int mod,n,x,arm1=0; printf(enter the val of n);
Decision making and looping 53	scanf(%d,n);	x=n;	while(n)	{ mod=n%10;	arm1=arm1+mod*mod*mod;	n=n/10;	} if(arm1==x) printf(nnyes armstrong hai!!!!!nn); else printf(nnyes armstrong nahi hai!!!!!nn); } Sample program 6.8 Write a program to check whether the number is Prime number or not #includestdio.h main() { int n, i = 3, count, c; printf(Enter the number of prime numbers requiredn); scanf(%d,n); if ( n = 1 ) { printf(First %d prime numbers are:n,n); printf(2n); } for ( count = 2 ; count = n ; ) { for ( c = 2 ; c = i - 1 ; c++ ) { if ( i%c == 0 ) break; } if ( c == i ) { printf(%dn,i); count++; } i++; } } Sample program 6.9 Write a program to check whether the entered number is a.Magic number or not //magic number 82=8+2=10=1+0=1
Computer Concepts and Fundamentals of Programming 54 #includestdio.h main() { int n,x,mod,rev=0; printf(nEnter the limitn); scanf(%d,n); TMI: for(x=n;n;n=n/10) {mod=n%10;rev+=mod;} if(rev=10) {n=rev;rev=0; goto TMI; } else if(rev==1) printf(Entered number is a magic no ); else printf(Entered number is not a magic no ); } Sample program 6.10 Write a program to print the following Pattern /* * * * * * * * * * * * * * * *	*/	#includestdio.h	main()	{ int n,i,j,k,l; printf(nEnter the limitn); scanf(%d,n); // work for the rows	for(i=1;i=n;i++)	{	for(k=1;k=10000000;k++); for(l=40;l=i;l--)// work for the spaces	{printf( );}	for(j=1;j=i;j++)	{printf( *);}	printf(n);	}	}
Decision making and looping 55 6.5  Programs for practice 1. WAP to find and print the sum of digits of a number entered by user. 2. WAP to find and print the greatest digit of a number entered by user. 3. WAP to find and print the smallest digit of a number entered by user. 4. WAP to find and print all even digits of a number entered by user. 5. WAP to Print the square root of each digit of any number. Consider each digit as perfect square. For example 494 the square roots to be printed should be 232. 6. WAP to enter two integer values through keyboard. Using while loop, perform the product of the two integers. In case product is zero, loop should be terminated otherwise loop will continue. 7. To enter integer number and find the largest and smallest digit of that number based on user choice. 8. To find and print the Fibonacci series till n where n is user defined. 9. To condense the number to a single digit. 10. To check whether the number entered by user is Arm-strong number or not. 11. To check whether the number entered by user is perfect number or not. 12. To check whether the number entered by user is magic number or not. 13. To check whether the number entered by user is palindrome number or not. 14. To check whether the number entered by user is special number or not. 15. To find and print the Factorial of a number entered by user. 16. Write a program in ‘C’ to generate the following output: (a). 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 (b). 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 (c). 5 4 3 2 1 5 4 3 2 5 4 3 5 4 (d). * ** ***
Computer Concepts and Fundamentals of Programming 56 **** ***** **** *** ** * (e). C CO COM COMP COMPU COMPUT COMPUTE (f). C COO COOMMM COOMMMPPPP COOMMMPPPPUUUUU COOMMMPPPPUUUUUTTTTTT COOMMMPPPPUUUUUTTTTTTEEEEEEE (g). C CCO CCCOOM CCCCOOOMMP CCCCCOOOOMMMPPU CCCCCCOOOOOMMMMPPPUUT CCCCCCCOOOOOOMMMMMPPPPUUUTTE (h). C CCOO CCCOOOMMM CCCCOOOOMMMMPPPP CCCCCOOOOOMMMMMPPPPPUUUUU CCCCCCOOOOOOMMMMMMPPPPPPUUUUUUTTTTTT CCCCCCCOOOOOOOMMMMMMMPPPPPPPUUUUUUUTTTTTTTEEEEEEE
Decision making and looping 57 (i). 1 121 12321 1234321 123454321 12345654321 1234567654321 (j). 9 989 98789 9876789 987656789 98765456789 9876543456789 987654323456789 98765432123456789 (k) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 (l). 1 23 456 78910 (m). ( )( )() ()() ()()( (n). 1
Computer Concepts and Fundamentals of Programming 58 232 34543 4567654 567898765 (o). 1 232 34543 4567654 567898765 67890109876 7890123210987 890123454321098
CHAPTER – 7 ARRAYS 7.1 Arrays Suppose we want to obtain 10 integer values, perform mathematical or other operations on them and then print the results, then we might require ten integer variables: var1, var2, var3,... , var10, for instance. Several programming languages provide the concept of arrays which help in reducing the number of variables because of a common name and indices for referencing individual elements. Let us consider an example: #includestdio.h main() { int num[10]; int i; printf(nNow obtaining 10 integer values: n);	for(i=0;i10;i++)	{ printf(Enter %dth integer: , i);	scanf(%d, num[i]);	} printf(nThe 10 integer values which you entered are as follows:);	for(i=0;i10;i++) printf(nnum[%d] = %d, i, num[i]); return 0; }
Computer Concepts and Fundamentals of Programming 60 A sample interaction with the program might appear as follows: How arrays are stored in memory? The declaration int num[10]; indicates to the ‘C’ compiler that memory is to be reserved (continuous locations) for storing 10 integer values. The locations are individually identified as num[0], num[1], num[2],... , num[9]. If an integer requires 4 bytes for storage, and if the first integer is being stored in locations identified as 2358932, 2358933, 2358934, 2358935; then the second integer would be stored in the locations: 2358936, 2358937, 2358938 and 2358939. In the diagram below, the numbers on the right indicate the address of the individual array elements. num[0] 2358932 num[1] 2358936 num[2] 2358940 num[3] 2358944 num[4] 2358948 num[5] 2358952 num[6] 2358956 num[7] 2358960 num[8] 2358964 num[9] 2358968 A few important points pertaining to arrays: If an array is declared as:
Arrays 61 int num[10]; (i) then the first element of the array will be referred to as num[0] and the last element of the array will be referred to as num[9]; (ii) If an array is declared as a global array [above main() ], then (a) It will be initialized with NULL values in case it is a char type array (b) It will be initialized with 0 (zero) in case it is a numeric array (iii) If an array is declared as a static array, then (a) It will be initialized with NULL values in case it is a char type array (b) It will be initialized with 0 (zero) in case it is a numeric array (iv) If a numeric type array is partially initialized at the place where it is declared, then the rest of the elements are automatically set to zero. (v) An array name is a pointer to itself. Thus num[0] and num would be the same. Two-dimensional arrays A declaration such as: int num[4][5]; creates an array of 4 rows and 5 columns and might be visualized as follows: Col 0 Col 1 Col 2 Col 3 Col 4 Row 0 Row 1 Row 2 Row 3 The individual elements might be accessed as follows: num[0][0] num[0][1] num[0][2] num[0][3] num[0][4] num[1][0] num[1][1] num[1][2] num[1][3] num[1][4] num[2][0] num[2][1] num[2][2] num[2][3] num[2][4] num[3][0] num[3][1] num[3][2] num[3][3] num[3][4] The program below demonstrates how to enter values into a two-dimensional array and then print the values. #includestdio.h #define ROWS 3 #define COLS 4 main() { int mat[ROWS][COLS]; int i, j; printf(nNow obtaining integers for %d X %d matrix:n, ROWS, COLS); for(i=0;iROWS;i++)
Computer Concepts and Fundamentals of Programming 62 {	for(j=0;jCOLS;j++)	{ printf(Enter integer for %dth row and %dth column: ,i,j); scanf(%d, mat[i][j]);	} } printf(nThe matrix is as follows:n);	for(i=0;iROWS;i++)	{ for(j=0;jCOLS;j++)	{ printf(%8d, mat[i][j]);	} printf(n); } printf(nThe addresses of the matrix elements are as follows:n); printf(nAddress (matrix element)n); for(i=0;iROWS;i++) {	for(j=0;jCOLS;j++)	{ printf(%u (%d) , mat[i][j], mat[i][j]);	} printf(n); } return 0; }
Arrays 63 A sample output is shown below: Sample program 7.1 Program to illustrate matrix multiplication of two matrices of same order Matrix multiplication #include stdio.h main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10]; printf(Enter the number of rows and columns of first matrixn); scanf(%d%d, m, n); printf(Enter the elements of first matrixn); for ( c = 0 ; c m ; c++ ) for ( d = 0 ; d n ; d++ ) scanf(%d, first[c][d]); printf(Enter the number of rows and columns of second matrixn); scanf(%d%d, p, q); if ( n != p ) printf(Matrices with entered orders can't be multiplied with each other.n); else { printf(Enter the elements of second matrixn); for ( c = 0 ; c p ; c++ )
Computer Concepts and Fundamentals of Programming 64 for ( d = 0 ; d q ; d++ ) scanf(%d, second[c][d]); for ( c = 0 ; c m ; c++ ) { for ( d = 0 ; d q ; d++ ) { for ( k = 0 ; k p ; k++ ) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf(Product of entered matrices:-n); for ( c = 0 ; c m ; c++ ) { for ( d = 0 ; d q ; d++ ) printf(%dt, multiply[c][d]); printf(n); } } } Sample program 7.2 Write a first category function program to read a two matrices A and B of order 9x9 and print the following. a)A+B and b)A-B #includestdio.h main() { int a[3][3],b[3][3],c[3][3],i,j; printf(Enter the First 3x3 Matrix: ); for(i=0;i3;i++) { for(j=0;j3;j++) scanf(%d,a[i][j]); } printf(Enter the Second 3x3 Matrix: ); for(i=0;i3;i++) { for(j=0;j3;j++) scanf(%d,b[i][j]); } printf(nThe Sum of Matrices is: ); for(i=0;i3;i++)
Arrays 65 { printf(n); for(j=0;j3;j++) { c[i][j]=a[i][j]+b[i][j]; printf(%d ,c[i][j]); } } printf(nnThe Difference of Matrices is: ); for(i=0;i3;i++) { printf(n); for(j=0;j3;j++) { c[i][j]=a[i][j]b[ i][j]; //2 mark printf(%d ,c[i][j]); } } } Sample program 7.3 Write a program that will put 8 queens on a Chessboard so that no queen can capture another. The size of the board is 8 x 8. One queen can capture another if it is standing in the same row (horizontal), or in the same column (vertical), or on the same diagonal as the other queen. #includestdio.h #includemath.h int a[30],count=0; int place(int pos) { int i; for(i=1;ipos;i++) { if((a[i]==a[pos])||((abs(a[i]a[pos])==abs(ipos)))) return 0; } return 1; } void print_sol(int n) { int i,j; count++; printf(nnSolution #%d:n,count);
Computer Concepts and Fundamentals of Programming 66 for(i=1;i=n;i++) { for(j=1;j=n;j++) { if(a[i]==j) printf(Qt); else printf(*t); } printf(n); } } void queen(int n) //1 mark { int k=1; a[k]=0; while(k!=0) { a[k]=a[k]+1; while((a[k]=n)!place(k)) //1 mark a[k]++; if(a[k]=n) //1 mark { if(k==n) print_sol(n); else { k++; a[k]=0; //1 mark } } else k; } } main() //1 mark { int i,n; printf(Enter the number of Queensn); scanf(%d,n);
Arrays 67 queen(n); printf(nTotal solutions=%d,count); } Selection Sort In Selection Sort, the element at the zeroth position is compared with all the elements below it and an interchange performed as and when required (depending on whether the elements have to be arranged in ascending or descending order). Thereafter, the element at the first position is compared with all the elements below it and an interchange performed as and when required. Similarly, the elements at the second, third,... position are compared with all the elements below them and an interchange performed as and when required. The program below is an implementation of Selection Sort: #includestdio.h #define SIZE 10 main() { int array[SIZE]; int i, j, t; printf(nNow obtaining %d integers: n, SIZE);	for(i=0;iSIZE;i++)	{ printf(Enter %dth integer: , i);	scanf(%d, array[i]);	} printf(nnBefore sorting:);	for(i=0;iSIZE;i++) printf(n%d, array[i]);	for(i=0;iSIZE-1;i++)	{	for(j=i+1;jSIZE;j++)	{	if(array[i]array[j])	{	t=array[i];	array[i]=array[j];	array[j]=t;	}	}	} printf(nnAfter sorting:);	for(i=0;iSIZE;i++) printf(n%d, array[i]); return 0; }
Computer Concepts and Fundamentals of Programming 68 A sample output is shown below: Bubble sort In Bubble sort two successive elements are compared with each other and an interchange performed as and when required (depending on whether sorting is required in ascending or descending order). #includestdio.h #define SIZE 10 main() { int num[SIZE]; int i, j; int t;	for(i=0;iSIZE;i++)	{
Arrays 69 printf(Enter %dth integer: , i);	scanf(%d, num[i]);	} printf(nBefore sorting: ); for(i=0;iSIZE;i++) printf(n%d, num[i]);	for(i=0;iSIZE-1;i++)	{	for(j=0;jSIZE-1;j++)	{	if(num[j]num[j+1])	{	t = num[j];	num[j]=num[j+1];	num[j+1]=t;	}	}	} printf(nAfter sorting: );	for(i=0;iSIZE;i++) printf(n%d, num[i]); return 0; }
Computer Concepts and Fundamentals of Programming 70 A sample output is shown below: Suppose the integers are entered in the following order: 9012 481 916 -9129 0 -873 3782 6712 -865 -2 After 0th run of the outer for(i...) loop 481 916 -9129
Arrays 71 0 -873 3782 6712 -865 -2 9012 (The largest integer in the array is at the bottom of the array) After 1th run of the outer for(i...) loop 481 -9129 0 -873 916 3782 -865 -2 6712 (The second highest integer in the array is in the second last position in the array) 9012 After 2th run of the outer for(i...) loop -9129 0 -873 481 916 -865 -2 3782 (The third highest integer in the array is in the third last position in the array) 6712 9012 After 3th run of the outer for(i...) loop -9129 -873 0 481 -865 -2 916
Computer Concepts and Fundamentals of Programming 72 3782 6712 9012 After 4th run of the outer for(i...) loop -9129 -873 0 -865 -2 481 916 3782 6712 9012 After 5th run of the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 6th run of the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 7th run of the outer for(i...) loop
Arrays 73 -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 8th run of the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After sorting: -9129 -873 -865 -2 0 481 916 3782 6712 9012 7.3  Programs for practice 1. To read 10 integers in an array and print all the values stored in the array. 2. To read 10 integers in an array and print all the values in reverse order stored in the array. 3. To read 10 integers in an array and Find the largest and smallest number from the array. 4. To read 10 fractions in an array and print alternate array elements.
Computer Concepts and Fundamentals of Programming 74 5. To print all even numbers stored in an array of size n, where n is user defined. 6. To accept an array of n elements, n user defined. Increase each value by 100 and print the new array. 7. To read 10 integers in an array. Find and print the largest and smallest number. 8. To accept an array of n numbers. Check value, if an even number is found, increase its value by 10, if odd decrease its value by 5and print both odd as well as new array. 9. To find and print all arm-strong numbers stored in an array of size n, where n is user defined. 10. To find and print all prime numbers stored in an array of size n, where n is user defined. 11. To find sum and average of any n values stored in an array. 12. To accept any n value,store them in the array and check the presence of any number entered by user in the array. If present, print the number, its first location and how many times it occurs in the array. 13. To read a number containing five digits. Perform square of each digit. 14. To read a number of any length. Perform the addition and subtraction on largest and smallest digits of it
CHAPTER – 8 STRINGS String functions in ‘C’ In ‘C’ language a string is an array of characters terminated by ‘0’ (the null character). Some of the most commonly used string functions in ‘C’ are: strcat(): for concatenating two strings, strchr(): used for locating the first occurrence of the character (second argument) in the string (first argument), strcmp(): used for comparing two strings, strcpy(): used for copying the string contained as the second argument to the function, in the first argument to the function, strncpy(): used for avoiding buffer overflow when copying, strlen(): for computing the length of the string, strncat(): for appending n bytes, strlwr(): for converting a string to lowercase strupr(): for converting a string to uppercase The programs below demonstrate the use of a few string functions. #includestdio.h #includestring.h main() { char str[80]; printf(nEnter any string:); scanf(%[^n], str); printf(nstr = %s, str); printf(nstrlwr(str) = %s, strlwr(str)); printf(nstrupr(str) = %s, strupr(str)); printf(nstrlen(str) = %d, strlen(str)); return 0; }
Computer Concepts and Fundamentals of Programming 76 A sample output is shown below: #includestdio.h #includestring.h main() { char str1[] = Sky is the limit; char str2[] = Sky is Not the limit; char str3[80] = ; int result; printf(nnstr1 = %s, str1); printf(nnstr2 = %s, str2); printf(nnstr3 = %s, str3); strcpy(str3, str2); /*strcpy(destination, source)*/ printf(nnAfter copying str2 to str3, str3 = %s, str3); result = strcmp(str1, str2); /* strcmp(str1, str2) returns a value 0 if str1 alphabetically precedes str2, strcmp(str1, str2) returns a value 0 if str2 alphabetically precedes str1, strcmp(str1, str2) returns 0 if str1 is exactly the same as str2 */ printf(nnOn comparing str1 and str2, result = %d, result); return 0; }
Strings 77 A sample output is shown below: const char* strstr(const char *str1, const char *str2); The strstr() function returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not a subset of str1. A program illustrating the use of strstr() follows: #includestdio.h #includestring.h main() { char str1[] = Sky is the limit; char *result; printf(nnstr1 = %s, str1); result= strstr(str1, the); printf(nnresult = %s, result); result= strstr(str1, star); printf(nnresult = %s, result); return 0; } A sample output is shown below: str1 = Sky is the limit result = the limit result = (null)
Computer Concepts and Fundamentals of Programming 78 Sample program 8.1.Write a program to enter a paragraph and check number of alphabet, digit or special character /* C program to check alphabet, digit or special character */ #include stdio.h main() { char ch; /* Reads a character from user */ printf(Enter any character: ); scanf(%c, ch); /* Checks if it is an alphabet */ if((ch = 'a' ch = 'z') || (ch = 'A' ch = 'Z')) { printf(%c is ALPHABET.n, ch); } else if(ch = '0' ch = '9') { printf(%c is DIGIT.n, ch); } else { printf(%c is SPECIAL CHARACTER.n, ch); } } 8.3  Programs for practice 1. To accept a matrix of mXn order, n and m are user defined, from user. Calculate and print their row sum, column sum and diagonal sum. 2. To accept a matrix of mXn order, where n and m are user defined, from user. Print its transpose. 3. To accept any string from user and print its length. 4. To accept any string from user and print the string in reverse order. 5. To accept any string from user and insert any n characters from mth position from it. ( n and m should be less than length of the string ) 6. Read a set of 5 lines from user and print out the longest line.
CHAPTER – 9 USER DEFINED FUNCTIONS 9.1 Definition Self-contained block of statement used to perform a particular task is called as function. The biggest advantage of function is code reusability. It divides the large program into segments because of this it becomes easy for a programmer to debug the program. Functions are sometimes called as methods. Functions are divided into following category i. Call by value and ii. Call by reference/ call by address: i.	Call by value: In this category of the function the copy of variable value is being passed to the called function. This divided into following categories depending on the return type and parameter it carries. 1. Function with no return and parameter 2. Function with no return but carrying parameter 3. Function with return but carrying no parameter 4. Function with return as well as parameter ii. Call by reference / call by address: In this category of function the address of the variable is passed to the called function. Sometime address is also called as reference of variable. Program 9.1 Call by value: Function category 1: Write a program to perform addition of two numbers. #includestdio.h #includeconio.h void add(void); main() { add(); } void add() { int a,b,c; printf(enter the value of a,b); scanf(%d%d,a,b); c=a+b; printf(n addition is: =); printf(%d,c); }
Computer Concepts and Fundamentals of Programming 80 Note: Same program can be written by using fourth category 9.2 Call by value: Function category 4: Write a program to perform addition of two numbers. #include stdio.h #include conio.h int ganesh(int a,int b); main() { int x=4,y=8,z; z=ganesh(x,y); // here x and y are called as actual parameter ,ssss printf(%d,z); } int ganesh(a,b)// here a and b are called as formal parameters { int c=a+b; return c; } 9.3 Call by reference: Write a function program with call by reference to swap the values of two integer variable. In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters. #include stdio.h #include conio.h void swapnum ( int *var1, int *var2 ) { int tempnum ; tempnum = *var1 ; *var1 = *var2 ; *var2 = tempnum ; } int main( ) { int num1 = 35, num2 = 45 ; printf(Before swapping:); printf(nnum1 value is %d, num1); printf(nnum2 value is %d, num2); /*calling swap function*/ swapnum( num1, num2 ); printf(nAfter swapping:); printf(nnum1 value is %d, num1); printf(nnum2 value is %d, num2); getch(); return 0; }
User defined function 81 9.3  Parameter and its types Parameters are nothing but the variables. Depending upon the location of the declaration they are classified as: 1. Local parameter: Any variable declared within the function body is a local parameter. Its scope lies up to that function body only where it is declared. 2. Global parameter: Any viable declared outside the function body is called as global parameter. 3. Actual parameter: The parameter which are being passed to the called function are calle as actual parameter. 4. Formal parameter: The parameter which are accepting the value of actual parameter are called as formal parameter. Following example best illustrates the functioning of the different parameters #include stdio.h #include conio.h int pi;// This is a global variable int ganesh(int a,int b); main() { int x=4,y=8,z;// x,y,z atre called as local parameter z=ganesh(x,y); // here x and y are called as actual parameter, ssss printf(%d,z); } int ganesh(a,b)// here a and b are called as formal parameters { int c=a+b; return c; } 9.4 Recursion Recursion: Function which is called within its own body is called as recursion. Program 8.3.1 //This program is for the recusive function //function called within its own body #includestdio.h main() { printf(nThis is a recursive function will run infinitenn);	main(); } 9.3.2  Program Fibonacci series /*This program is showing the execution of recusive function*/ #includestdio.h
Computer Concepts and Fundamentals of Programming 82 #includeconio.h int Fibonacci(int); int main() { int n, i = 0, c; scanf(%d,n); printf(Fibonacci seriesn); for ( c = 1 ; c = n ; c++ ) { printf(%dn, Fibonacci(i)); i++; } return 0; } int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); } 9.4  Programs for practice WAP to check whether the given number is (Using all the four categories of function) 1. PRIME NUMBER 2. ARMSTRONG NUMBER 3. PALINDROME NUMBER 4. SPECIAL NUMBER 5. MAGIC NUMBER 6. PERFECT NUMBER 7. ADAM NUMBER
CHAPTER – 10 POINTERS 10.1 Introduction The computer’s memory is a collection of storage cell. Each cell or location has a unique address. The address is a consecutive numerical number often expressed in hexadecimal, which is difficult to use directly in the program. To ease the burden of programming using numerical address, the concept of variables is introduced. A variable is a named location that can store a value of a particular type. Instead of numerical addresses, names are attached to certain addresses. Also, data types such as int, double, char are related with the contents for the interpretation of data. Pointer is defined as address variable, a variable which holds the address of another variable. The following diagram illustrate the relationship between computers' memory address and content; and variable's name and value used by the programmers. Address Name Value /content 7000000 7000001 a 25 7000002 7000003 7000004 b 3 7000005 int a=25, b=3; 7000001 is the address of variable named “a” whose value is 25. If this address 7000001 is be stored in a variable, then the variable has to be a pointer or pointer variable. 10.2  Pointer declaration Like any other variable the pointer variable also should be declared before use. Syntax to declare a pointer data_type * pointer_var_name; Example int * p; The character asterisk (*) tells to the compiler that the identifier “p” should be declare as pointer. The data type tells to the compiler that pointer “p” will store memory address of an integer variable.
Computer Concepts and Fundamentals of Programming 84 10.3  Initializing Pointers When a pointer variable is declared, its content is not initialized. Like other variable pointers also need be initialized by assigning it a valid address. This is normally done via the address-of operator (). int a=25; int * p= a; /* pointer initialization */ p a 700045 600012 The pointer p is pointing to a 10.4  address () and dereference (*) operators C language provides two operators: address () and dereference (*) to manipulate data using pointers. The “address of ” is an operator which returns the address of a variable. for example int a=25; int * p= a; /* address of the a is assigned to pointer p */ printf(“%d”,a); /* output 25 */ The dereference operator or indirection operator * “ is an unary operator which operates on a pointer and returns the value at the location pointed to by that pointer. for example you can access the value of “a” using pointer use deference operator “*” printf(“%d”,*p);	/* output 25 */ Sample Program 10.1 /* To print value and address of a variable */ #include stdio.h int main() { int a=25; /* int variable */ int *p; /* int pointer declaration */ p=a; /* initializing pointer */ printf(The address of a: %un,p); printf(Value a: %dn,*p); return 0; } Output: The address of a: 65524 Value a: 25 10.5  Pointer’s data type A pointer to any variable type is an address in memory -- which is an integer. But a pointer is NOT an integer always. A pointer should take the type of the value it points to. A pointer can only hold an address of the declared type; it cannot hold an address of a different type. For example 600012 25
Pointers 85 int *p; p can hold the address of a int variable only. int a; p=a; 10.6  Benefits of pointers • Reduces the storage space • Execution using pointer is faster (i.e) Reduces the execution time of the program • Memory is dynamically allocated, allows us to resize the dynamically allocated memory block 10.7  Arrays and Pointers Array and pointers are closely related with each other. The name of an array without a subscript (index number) is a pointer constant. When the name is used without the subscript it references the address of element 0 of the array. int myarray[10]; /* Declare an array */ int *myptr; /* Declare a pointer (not initialized)*/ printf (“%dn”, myarray); /* print address of myarray[0] */ scanf (“%d”,myarray[0]); /* get value from keyboard and store in myarray[0] */ myptr = myarray[2]; /* Assign the address of the third element of myarray to myptr*/	printf(“%d”, *myptr); /* Print the value of what myptr is pointing to, i.e., the value of myarray[2] */ Note that the * in front of myptr de-references the pointer. That is, it says “use the value in the address that is pointed to.” Sample Program 10.2 /* Printing array values and addresses */ #include stdio.h int main ( ) { int k; float a[4] = {100, 200, 300, 400}; for (k=0; k4; k++) printf (%d %ld %ld %fn, k, a, a[k], a[k]); } 10.8  Pointer Arithmetic Arithmetic operations can be performed on pointers, but only limited operations can be performed on pointers. A pointer may be: • incremented ( ++ ) • decremented ( — ) • an integer may be added to a pointer ( + or += ) • an integer may be subtracted from a pointer ( – or -= ) • Pointer comparison ( , == , ) °° See which pointer points to the higher numbered array element °° Also, see if a pointer points to 0 • Pointers of the same type can be assigned to each other
Computer Concepts and Fundamentals of Programming 86 • Operations meaningless unless performed on an array • addition, multiplication and division operations on two pointer variables cannot be performed Data Type Initial Address Operation Address after Operations Required Bytes int 4000 ++ 4002 2 int 4000 -- 3998 2 char 4000 ++ 4001 1 char 4000 -- 3999 1 float 4000 ++ 4004 4 float 4000 -- 3996 4 long 4000 ++ 4004 4 long 4000 -- 3996 4 Expression Result Address + number Address Address - number Address Address - Address Number Address + Address Illegal Note: The value by which the address of the pointer variable will increment/ decrement is not fixed. It depends upon the data type of the pointer variable. Sample program 10.3 /*program to find sum of all elements stored in an array */ #includestdio.h #includeconio.h main () { int a [5] ={5,10,15,20,25}; int i, sum=0,*p; p = a; for (i = 0; i5; i++) { sum = sum+(*p); p++; } printf (the sum is % d, sum); getch (); } Output the sum is 75 Sample program 10.4 Palindrome string #includestdio.h #includestring.h int main()
Pointers 87 { char str[30]; char *p,*t; printf(Enter any string: ); gets(str); for(p=str ; *p!=NULL ; p++); for(t=str, p-- ; p=t; ) { if(*p==*t) { p--; t++; } else break; } if(tp) printf(nString is palindrome); else printf(nString is Not palindrome); } Sample program 10.5 Write a program to compare two string using pointers.(Note: Do not use strcmp function) #includestdio.h int compare_string(char*, char*); main() { char first[100], second[100]; int result; printf(Enter first stringn); gets(first); printf(Enter second stringn); gets(second); result = compare_string(first, second); if ( result == 0 ) printf(Both strings are same.n); else printf(Entered strings are not equal.n); } int compare_string(char *first, char *second) { while(*first==*second)
Computer Concepts and Fundamentals of Programming 88 { if ( *first == '0' || *second == '0' ) break; first++; second++; //1 mark } if( *first == '0' *second == '0' ) return 0; else return 1; } 10.9 Programs for practice 1. WAP to accept an integer value and display it's value and address using pointer 2. WAP to check whether the given string is palindrome or not using pointer. 3. WAP to find the length of the string entered by user and display the string in reverse order.4
CHAPTER – 11 STRUCTURES AND UNIONS 11.1 Introduction Structure is a user-defined datatype in C language. A structure is used to represent a group of data items of different datatype, whereas array is the group of similar data items i.e data items of same datatype. Structures are used to handle a group logically related data items. For example to keep track of student details, the following a set of attributes about a student may be used: name, roll_no, marks and gender. Structures can be used to organize these complex data in a useful way. Defining a Structure Unlike predefined datatypes, structures must be first defined for their format that may be later used for declaring the structure variables. The general format for defining a structure struct tag_name { datatype member 1; datatype member 2; ------------ datatype member m; }; In this definition, struct is a required keyword, tag is a name that identifies structures of this type. It should be terminated with a semicolon. Each member should be independently declared for its name and type. For example consider a student database consisting of name, roll_no, marks and gender, a structure can be defined as follows struct student { char name [30]; int roll_no; float marks; char gender; }; Student is a user-defined datatype and variables of this type can be declared and used in the program. Declaring a structure variable
Computer Concepts and Fundamentals of Programming 90 After defining a structure, we can declare variables of that type. The general format of declaring structure variable struct tag_name struct_variable; example struct student s1,s2,s3; this statement declares s1,s2 and s3 as structure variables of type student. Each one of these variable have four members name, roll_no, marks and gender. C language allows to combine both the structure definition and variables declaration in one statement as follows struct student { char name [30]; int roll_no; float marks; char gender; }s1,s2,s3; Structure initialization struct student s1 = {“John”,780123,67.5,’m’}; struct student s2 = {“Priya”,780122,85.5,’f’}; Note: the order of values enclosed in braces must match the order of members in the structure definition. It is allowed to initialize first few members and leave the remaining blank. The uninitialized members should be only at the end of the list. For example struct student s2 = {“Priya”,780122}; /* initializes name and roll_no leaving marks and gender blank */ Accessing members of the structure The members of a structure are usually processed individually. Therefore, we must be able to access the individual structure members. A structure member can be accessed by (.) period operator struct_variable.member_name. The (.) operator is a member of the highest precedence group, and its associativity is left-to-right. Sample Program 1 struct student { char name [30]; int roll_no; float marks; char gender; }; main() { struct student s1; printf(“ enter the name of the student “); scanf(“%s”, s1.name);
Structures and unions 91 printf(“ enter the roll_no of the student “); scanf(“%d”, s1.roll_no); printf(“ enter the gender of the student “); scanf(“%c”, s1.gender); s1.marks=75.5; /* the details of the student */ printf (“Name: %s”, s1.name); printf (“Roll no: %d”, s1.roll_no); printf (“ Gender: %c”, s1.gender); printf (“ Marks: %f”, s1.marks); } Arrays of structure If we have to maintain the details of more than one student then array of structures can be used. Array of structure may be declared as follows struct student s[50]; s is an array of 50 elements in which each element is of type struct student s[0].name /* refers to the name of the first student */ s[5].marks /* refers to the marks of the 6th student */ Sample Program 2 /* To read and print the details of 50 students and find if a student scored first class or not */ struct student { char name [30]; int roll_no; float marks; char gender; }; main() { struct student s[50]; int i; for(i=0;i50;i++) { printf(“ enter the name of the student “); scanf(“%s”, s[i].name); printf(“ enter the roll_no of the student “); scanf(“%d”, s[i].roll_no);
Computer Concepts and Fundamentals of Programming 92 printf(“ enter the gender of the student “); scanf(“%c”, s[i].gender); printf(“ enter the marks of the student “); scanf(“%f”, s[i].marks); } /* the details of the student */ for(i=0;i50;i++) { printf (“Name: %s”, s[i].name); printf (“Roll no: %d”, s[i].roll_no); printf (“ Gender: %c”, s[i].gender); if(s[i]=60) { printf (“First class”); } } } Structure within Structure (Nested Structure) A structure can be nested inside another structure. In other words, the members of a structure can be of any other type including structure. The general format for nested structures structure tagname_1 { member1; member2; member3; structure tagname_2 member4; ... membern; }; Example struct date { int day; int month; int year; }; struct student {
Structures and unions 93 char name [30]; int roll_no; struct date dob; }; struct student s; The structure student has a member dob which itself is a structure with three members. The members in the inner structure can be referred as s.dob.day=25; s.dob.month=11; union A union is a user data type like structure that is used to handle different data types in a unit. Union follows the format of structure for definition of union, declaration of union variable and accessing of members union union_name { datatype member 1; datatype member 2; ------------ datatype member m; } [one or more union variables]; At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Otherwise you can later declare variable as follows union union_name var1,var2; To access any member of a union, the period operator (.) is to be used Example union subject { char name[50]; int subject_code; }; union subject s1 ={“computer science”, 2205}; /*union initialization */ union subject s2; /*declare union variable */ strcpy(s2.name,”mathematics”); /* access union member */ 11.3  Difference between structure and union The difference between structure and union is, union use less memory than structures. Each member of a structure is allotted separate memory space (ie) the size of structure in equal to the sum of size of all its members, whereas in case of union, size is equal to size of largest member. For example struct student { char name [30];
Computer Concepts and Fundamentals of Programming 94 int roll_no; float marks; char gender; } s1; The structure variable s1 requires 37 bytes ( 30 for name, 2 for roll_no, 4 for marks and 1 for gender). Each member get separate memory location, so all can be used at a time. union student { char name [30]; int roll_no; float marks; char gender; } s2; The union variable s2 requires only 30 bytes, ie the size of largest member. But only one member can contain a value or used at any given time. Another example union subject { char name[50]; int subject_code; }; The union above could be used to either store name or subject_code at a particular time. Presumably there are times when you would want one or the other, but not both. #includestdio.h #includeconio.h union subject { char name[50]; int subject_code; }; void main() { union subject s; clrscr(); printf(Enter subject Name: ); scanf(%s,s.name); printf(The subject Name: %sn,s.name); printf(Enter subject code: ); scanf(%d,s.subject_code); printf(The subject code: %d,s.subject_code); }
Structures and unions 95 Output Enter subject Name: computer science The subject Name: computer science Enter subject code: 2205 The subject code: 2205 Appendix Opening a web browser via a ‘C’ program Is it possible to open a web page in a browser using a 'C' program? The program below provides an answer to the aforementioned question: Program listing one #includestdio.h main() { char url[25] = www.mail.yahoo.com; char launch[255]; system(clear); sprintf(launch, gnome-open %s, url); system(launch); return 0; } [NOTE: 1. The above code should be compiled on a Linux system. 2. Parallel methods for opening a web-browser are available for Windows/Mac OSs. For instance, on a Mac OS, system(“open http://url”); might be used.] An alternative method of opening a web page is given below: Program listing two #includestdio.h main() { char url[25] = www.iiml.ac.in; char launch[255]; system(clear); sprintf(launch, firefox %s, url); system(launch); return 0; } [Note: The code in Program listing two assumes that firefox is installed on the workstation and the appropriate PATH has been set.]
Computer Concepts and Fundamentals of Programming 96 The program below provides an illustration of another method of opening a web-browser via a 'C' program: Program listing three #includestdio.h #includeunistd.h main() { execl(/usr/bin/firefox, (char *)0); printf(execl() could not open the web-page); /* this line will be executed only if execl() above is not able to launch firefox*/ return 0; } The reader may interpret execl()as execute and leave. The execl() function replaces the current process by running the program specified as an argument to the execl()function. The process identifier (PID) of the new process will be the same as the PID of the old process (old process refers to the program in program listing three which is being compiled and executed and new process refers to firefox). The prototype of the execl()function is: int execl(const char *path, const char *arg1,...); execl() is a variadic function and the list of arguments to execl() should be terminated by a NULL pointer, therefore (char *)0 has been used to indicate the end of arguments to execl().
Structures and unions 97 INDIAN MARITIME UNIVERSITY (A Central University, Government of India) END SEMESTER EXAMINATION December 2017 Programme: B. Tech (Marine Engineering) Semester: II Subject Name: Computer Science Subject Code: UG11T2205/ UG11T1205 Date: 29.12.2017 Maximum Marks: 100 Time: 10AM – 1PM Pass Marks: 50 PART – A Marks: 10 X 3 = 30 (All Questions are compulsory) 1.  a) Differentiate between RAM and ROM Answer. RAM ROM Random Access Memory Read Only Memory Volatile memory: stores information as long as the computer is not switched off. Non-volatile memory: ROM retains information even when the computer is powered off. Types of RAM: SDRAM – Synchronous DRAM DDR – Double Data Rate SDRAM RDRAM – Rambus DRAM DIMM RIMM There are five basic types of ROM: ROM PROM EPROM EEPROM Flash memory b) What is the use of header files example any one Answer. A header file contains C declarations and macro functions. A few standard header files in C are: assert.h complex.h ctype.h Example: In order to pass variable number of arguments to a function the file stdarg.h should be included.
Computer Concepts and Fundamentals of Programming 98 header files in ‘C’ The preprocessing directive ‘#include’ can be written as	#includestdio.h or	#include”stdio.h” #includestdio.h searches for the file named stdio.h in the standard list of system directories. #include”stdio.h” searches for the file named stdio.h first in the directory containing the current file, thereafter in the quote directories and then in the standard list of system directories. Some of the header files used in ‘C’ are: assert.h complex.h ctype.h errno.h fenv.h limits.h locale.h math.h signal.h stdarg.h stdlib.h string.h time.h c) Explain ternary operator? Give example Answer.?: is known as ternary operator. The conditional operator (?:) takes three operands and has the following syntactic form: expr1 ? expr2: expr3; expr1 is always evaluated first and results in either true or false. If expr1 evaluates to true (1), expr2 is evaluated; otherwise expr3 is evaluated. Example: #includestdio.h main() { int isPremiumMember; float price; printf(nIs customer a Premium Member (Yes - 1, No - 0): ); scanf(%d, isPremiumMember);
Structures and unions 99 price= isPremiumMember? 100: 120; /*If the customer is a Premium Member then price = 100, if the customer is not a Premium Member then price = 120*/ printf(nPrice = %f, price); return 0; }
Computer Concepts and Fundamentals of Programming 100 d) find the output #includestdio.h int main() { int i=3; i=i++; printf(%dn,i); return 0; } Answer. Output is: 3 e) Explain do while loop with example Answer. The do . . . while() loop The general form of the while() loop is: do { code-block; }while (expr); If the expr after while evaluates to true then the body of the do . . . while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do . . . while(); loop will be necessarily executed at least once. The do . . . while() loop is an exit-controlled loop.
Structures and unions 101 #includestdio.h main() { /* printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++; }while(k=30); return 0; } NOTE: This section demystifies the fact that although two different nested loops are executed exactly the same number of times, even then the execution times are likely to be different. Which code segment (1 or 2) will execute faster? #includestdio.h main() { int i, j; system(clear); for(i=0;i10;i++) { for(j=0;j100;j++) code segment 1 { /* some code */ } }
Computer Concepts and Fundamentals of Programming 102 for(i=0;i100;i++) { for(j=0;j10;j++) code segment 2 { /* some code */ } } return 0; } Obviously /* some code */ will be executed equal number of times in both the code segments i.e. code segment 1 as well as code segment 2. Does that imply that the time taken for execution of the two code segments will be the same assuming that /* some code */ is exactly the same in both the code segments. The answer is that code segment 1 and code segment 2 will require different time periods for execution. A deeper examination proves the assertion: (i). In code segment 1, the initialization i = 0; j = 0; is carried out 1 + 10 = 11 times, whereas, in code segment 2, the initialization i = 0; j = 0 is carried out 1 + 100 = 101 times. (ii). In code segment 1, the comparison i 10; j 100; is carried out 11 + 101 x 10 i.e. 1021 times, whereas, in code segment 2 the comparison i 100; j 10; is carried out 101 + 100 x 11 i.e. 1201 times. (iii). In code segment 1, the increments i++; j++; are carried out 10 + 100 x 10 i.e. 1010 times, whereas, in code segment 2 the increments i++; j++; are carried out 100 + 100 x 10 i.e. 1100 times. The code produced below uses four counters ctr1, ctr2, ctr3 and ctr4 which will help in understanding the aforementioned explanation: #includestdio.h main() { int i, j; int ctr1=0, ctr2=0, ctr3=0, ctr4=0; system(clear); for(i=0;++ctr1 i10;i++,++ctr2) { for(j=0;++ctr1 j100;j++,++ctr2) { /* some code */ } } for(i=0;++ctr3 i 100;i++,++ctr4) { for(j=0;++ctr3 j 10;j++,++ctr4)
Structures and unions 103 { /* some code */ } } printf(nctr1 = %d, ctr2 = %d, ctr1, ctr2); printf(nctr3 = %d, ctr4 = %d, ctr3, ctr4); return 0; } A sample output of the above program is given below: ctr1 = 1021, ctr2 = 1010 ctr3 = 1201, ctr4 = 1100 The code presented below may be used for determining the exact execution time of the two code segments: #includestdio.h #includetime.h main() { int i, j; clock_t start = clock(); system(clear); for(i=0;i10;i++) { for(j=0;j100;j++) { /* some code */ } } printf(nTime required for executing segment 1 = %lf, ((double)clock() - start)/CLOCKS_PER_SEC); start = clock(); for(i=0;i100;i++) { for(j=0;j10;j++) { /* some code */ } }
Computer Concepts and Fundamentals of Programming 104 printf(nTime required for executing segment 2 = %lf, ((double)clock() - start)/CLOCKS_PER_SEC); return 0; } It is also important to bear in mind that the above is a mathematical evaluation of the two code segments. On using the concept of locality of reference (or principle of locality) the evaluation will be different. There are four special cases of locality of reference: temporal, spatial, equidistant and branch. f) Describe the difference between structure and union. Answer. A structure in ‘C’ language is a collection of related elements, possibly of the same or different types, identified by a name. Each element in the structure is known as a field. A union in ‘C’ language is a construct that allows memory to be shared by different types of data. In a union, each piece of data starts at the same memory location and partly or wholly occupies the same memory. #includestdio.h struct example1 { char ch; int i; float f; double d; }; union example2 { char ch; int i; float f; double d; };
Structures and unions 105 main() { printf(nsizeof(example1) = %d, sizeof(example1)); printf(nsizeof(example2) = %d, sizeof(example2)); return 0; } OUTPUT: g) Explain Flowchart with one example. Answer. A Flowchart is a diagrammatic representation of an algorithm, workflow or process. A structured method for documenting process flow was introduced by Frank and Lillian Gilbreth.
Computer Concepts and Fundamentals of Programming 106 Example: Flowchart for finding the GCD of two integers: h) Explain scanf statement and printf statement with example. scanf(): A function for accepting input; printf(): A function for displaying output;. Obtaining an integer as input from the user:
Structures and unions 107 #includestdio.h main() { int num; printf(Enter an integer: ); scanf(%d, num); printf(nThe integer you entered is: %d, num); return 0; } A sample output is shown below: Enter an integer: 786 The integer you entered is: 786 i) Define Function and its advantages. Answer. A function in ‘C’ is an independent module which can be invoked for performing a particular task. When a function is called, then the control is transferred from the calling function to the called function and once the execution of the called function is over, the control returns to the calling function. [The programs hereafter in this section have been executed using Dev-C++ Version 5.11] #includestdio.h float sumfunc(float x, float y); main() { float num1, num2, sum; printf(nEnter first number: ); scanf(%f, num1); printf(nEnter second number: ); scanf(%f, num2); sum = sumfunc(num1, num2); function invocation or function call printf(nSum of %f and %f = %f, num1, num2, sum); return 0; } function declaration or function prototyping
Computer Concepts and Fundamentals of Programming 108 float sumfunc(float x, float y)	function header { float temp; temp = x + y;	function body return temp; } OUTPUT: The function declaration: float sumfunc(float x, float y); contains three parts, namely, (i). type of return value from the function, (ii). name of the function, (iii). number and type of parameters being passed into the function. type of return value function name number and types of parameters being passed into the function float sumfunc(float x, float y); Advantages: (i) Programs can be divided into smaller, manageable segments. (ii) Functions help in reusing code which might be required more than once in a program. (iii) Functions can be used for protecting data. j) What is the Byte size of ‘char’ and ‘float’ in C. Answer. [The size of ‘char’ and ‘float’ is machine dependent and compiler dependent.] function definition
Structures and unions 109 #includestdio.h main() { printf(nsizeof(char) = %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(long) = %d, sizeof(long)); printf(nsizeof(long double) = %d, sizeof(long double)); return 0; } Sample output is shown below:	PART – B Marks: 5 X 14 = 70 (Answer any 5 of the following) 2. a) Write a C program to find the factorial of a number where number will be taken as fly (runtime) (7 marks) Answer. [N.B.: The phrase ‘on the fly’ implies something that is being changed while the process that is being affected by the change is being carried out/executed. Switching computer parts on the fly implies replacing parts of the computer while the computer is running.]
Computer Concepts and Fundamentals of Programming 110 #includestdio.h main() { int i, n; long int f=1; printf(nEnter integer whose factorial you want: ); scanf(%d, n); for(i=n;i1;i--) f=f*i; printf(nFactorial of %d = %ld, n, f); return 0; } Sample output is shown below: b) Write a C program to check whether a year is leap year or not year will be taken as fly (runtime). (7 marks) Answer. Every year that is exactly divisible by 4 is a leap year. But when a year is exactly divisible by 100, then it is considered as a leap year when it is exactly divisible by 400 also. If a year is exactly divisible by 1000, then it will be considered as a leap year only if it is not exactly divisible by 4000.
Structures and unions 111 #includestdio.h int isleap(int y) { if((y%1000)==0) { if((y%4000)!=0) return 1; else return 0; } else if((y%100)==0) { if((y%400)==0) return 1; else return 0; } else { if((y%4)==0) return 1; else return 0; } } main() { int year; int result; printf(Enter the year for checking: ); scanf(%d, year); result=isleap(year); if(result) /*if(result) is the same as writing if(result!=0) */ printf(n%d is a leap year, year); else printf(n%d is not a leap year, year); return 0; }
Computer Concepts and Fundamentals of Programming 112 3 b) Explain any three services provided by the internet? (7 marks) Answer. (i). World Wide Web: The World Wide Web is the part of Internet accessible to users. (ii). Electronic Mail
Structures and unions 113 (iii). E-Commerce (iv). File Transfer Protocol: for transferring large files between computers connected via Internet. (v). IRC: Internet Relay Chat (vi). Telnet (vii). Web-Hosting. 4. a) Explain Switch Case with Example	(10 marks) switch...case construct helps control conditional branching operations. The general format of the switch construct is: switch(expression) { case constant-expression1: statement(s); case constant-expression2: statement(s); default: statement; } The expression in switch(expression) should evaluate to an integral value. The control passes to the statement whose case constant- expression matches the value of the switch(expression). A few points have to be borne in mind (i) no two case constants within the same switch should have the same value, (ii) the break statement can be used to terminate the processing of a particular case and to branch to the end of the switch construct and without the break statement the next case(s) would also be executed, (iii) the default statement need not be placed at the end and there can be at the most one default statement. The program below explores an interesting fact related to switch...case Program listing #includestdio.h main() { int x = 9; system(clear); switch(x) { int y=9; case 8: printf(nx=%d,x); break; case 7: printf(nx=%d,x); break; default: printf(nDefault being executed: x=%d,x);	printf(ny=%d,y); }
Computer Concepts and Fundamentals of Programming 114 return 0; } A sample output of the program is: Default being executed: x=9 y=9360080 The most intriguing point is that although y is initialised with the value 9 even the the value of y in the output is an unpredictable value. Why? It is for the simple reason that although declarations can appear at the head of compound statement forming the switch construct, the initializations included in the declarations are not performed. b) Explain i) Multiuser Operating system ii) Multithreading operating system (4 marks) Answer. A Multiuser Operating System allows multiple users to access a computer system concurrently. For example, Windows XP. The major functions of an Operating System (OS) are i) resource management, ii) data management, iii) job management, iv) acting as a user interface. A thread is a basic unit of CPU utilization. Multi threading implies that a single process can have multiple code segments running concurrently. In multithreading there will be parent processes and child processes. 5. a) Explain Generations of Computer	(7 marks) First Generation Examples are UNIVAC and ENIAC 1940 – 1956 (approx.) Used vacuum tubes for circuitry and magnetic drums for memory. Relied on Machine Language. Input was based on punched cards and paper tapes. Very expensive to operate. Used great deal of electricity. Required large storage space. Second Generation 1956 – 1963 (approx.) Vacuum tubes were replaced by transistors. Second generation computers relied on assembly or symbolic languages. Smaller, faster, cheaper and more energy efficient than the first generation computers. Third Generation 1964 – 1971 (approx.) Used Integrated Circuits. Input was given by keyboard and output was displayed on monitors. Fourth Generation 1971 – present (approx.) Used microprocessors. Fourth Generation computers were accompanied with developments in the Internet, GUIs, mouse device and other handheld devices. Fifth Generation Present – beyond (approx.) Accompanied with development in Artificial Intelligence, parallel processing, quantum computation, nanotechnology. Fourth Generation (VLSI) 4-bit microcomputer Intel 4004, Intel 4040 8-bit microcomputer Intel 8008, Intel 8080, Motorola 6800, Motorola 6809, MOSTechnology 6502, Zilog Z80 16-bit microcomputer Intel 8008, Zilog Z8000, WDC 65816/65802 32-bit microcomputer Intel 80386, Pentium, Motorola 68000, ARM 64-bit microcomputer Alpha, MIPS, PA-RISC, PowerPC, SPARC, x86-64, ARMv8-A Theoretical/Experimental Optical computer, Quantum computer, Spintronics-based computer
Structures and unions 115 b) Write a Program in C to find the Transpose of a Matrix (7 marks) #includestdio.h main() { int nrows, ncols; /*nrows is for number of rows and ncols is for number of columns */ printf(nNumber of rows in the matrix: ); scanf(%d, nrows); printf(nNumber of cols in the matrix: ); scanf(%d, ncols); int mat[nrows][ncols]; int tranmat[ncols][nrows]; /*tranmat[][] is for holding the transpose */ int i, j; printf(nNow obtaining integers for the %d by %d matrixn, nrows, ncols); for(i=0;inrows;i++) { for(j=0;jncols;j++) { printf(Enter integer for %d row and %d col: ,i,j); scanf(%d, mat[i][j]); } } for(i=0;inrows;i++) {	for(j=0;jncols;j++) { tranmat[j][i] = mat[i][j]; } } printf(nOriginal matrix:n); for(i=0;inrows;i++) {	for(j=0;jncols;j++) { printf(%7d, mat[i][j]); }	printf(n); } printf(nTranspose matrix:n); for(i=0;incols;i++) {	for(j=0;jnrows;j++)
Computer Concepts and Fundamentals of Programming 116	{ printf(%7d, tranmat[i][j]);	}	printf(n); } return 0; } A sample output is shown below: 6. a) Explain i) Call by Value	ii) Call be reference with example. (10 marks) /* Call by value */ #includestdio.h void swap(int a, int b); main()
Structures and unions 117 { int var1, .var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } OUTPUT: /* Call by reference */ #includestdio.h void swap(int *a, int *b);
Computer Concepts and Fundamentals of Programming 118 main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } OUTPUT: In pass by value, the values are simply passed from the calling function to the called function. Any change in values in the called function will not be reflected in the calling function. In pass by reference any change in values in the called function will also be reflected in the calling function.
Structures and unions 119 [Important Note: There is no pass by reference in ‘C’. is also known as referencing operator in C++.] b) Explain gets() and puts(). (4 marks) Answer. The gets() function in ‘C’ reads a line from the input stream and terminates it by ‘0’. The puts() function is used for displaying a string on the standard output. The puts() function automatically inserts a newline character at the end of each string it displays. #includestdio.h main() { char str[80]; printf(nEnter any string: ); gets(str); puts(nThe string you entered is: ); puts(str); return 0; } OUTPUT:
Computer Concepts and Fundamentals of Programming 120 7. a) Explain the Types of Operators in C Answer. Arithmetic operators + Addition – Subtraction * Multiplication / Division % Modulus Increment and decrement operators ++ Increment by 1 Example a++; -- Decrement by 1 Example b--; Relational operators == Equality operator != Not equal to Less than Greater than = Less than or equal to = Greater than or equal to Logical operators And || Or ! Not It performs the logical negation of an expression Bitwise operators left shift operator right shift operator ~ One’s complement operator Bitwise AND operator | Bitwise OR operator ^ Bitwise XOR operator Assignment operator Operator= Performs the operation and then assigns Example: a += b; Would expand to a = a + b; Conditional operator ?: ternary operator expr1 ? expr2: expr3; expr1 is always evaluated first and results in either true or false. If expr1 evaluates to true (1), expr2 is evaluated; otherwise expr3 is evaluated Special operators sizeof() int a, b; b = sizeof(a); sizeof(a); returns the amount of memory in bytes required to hold a ‘address of’ operator * ‘value at address’ operator. The * (asterisk) is also known as the indirection operator.
Structures and unions 121 8. Write a C program to store information (name, roll and marks) of Student using Structure data where information will be taken as fly (runtime)	(10 marks) #includestdio.h struct student_data { char name[40]; char rollno[20]; int marks_sub_1; int marks_sub_2; int marks_sub_3; }; main() { struct student_data svar1; printf(nEnter name of student: ); scanf(%[^n], svar1.name); fflush(stdin); printf(nEnter roll number of student: ); scanf(%[^n], svar1.rollno); printf(nEnter subject1 marks: ); scanf(%d, svar1.marks_sub_1); printf(nEnter subject2 marks: ); scanf(%d, svar1.marks_sub_2); printf(nEnter subject3 marks: ); scanf(%d, svar1.marks_sub_3); printf(nName of student: %s, svar1.name); printf(nRoll number of student: %s, svar1.rollno); printf(nMarks in subject1: %d, svar1.marks_sub_1); printf(nMarks in subject2: %d, svar1.marks_sub_2); printf(nMarks in subject3: %d, svar1.marks_sub_3); return 0; }
Computer Concepts and Fundamentals of Programming 122 A sample interaction with the program is shown below: ***
Structures and unions 123 INDIAN MARITIME UNIVERSITY (Central University, Government of India) May/June 2016 End Semester Examinations B.Tech. (Marine Engineering) Second Semester – Computer Science – (UG11 T1205/T2205) Date: 17.06.2016 Maximum Marks: 100 Time: 3 Hrs Pass Marks: 50 PART – A Marks: 10 X 3 = 30 Compulsory Question 1) a) Can a calculator be considered as a computer? Answer. Calculator Computer Definition An electronic device used for mathematical calculations and has a small keyboard and display screen that shows the results. An electronic device which is capable of receiving information and performing a sequence of operations according to the instructions given (program). Development Wilhelm Schickard (according to two letters written by Schickard to Johannes Kepler in 1623 and 1624) invented the calculator. Blaise Pascal also developed a calculator. Gottfried Leibniz spent forty years designing a four-operation mechanical calculator. The Antikythera mechanism is believed to be the world’s first analog “computer” according to Derek J. de Solla Price. It was designed for calculating astronomical positions. Charles Babbage who is considered the “father of computer” developed the difference engine and thereafter the Analytical Engine. The principle of the modern computer was proposed by Alan Turing in the paper On Computable Numbers (1936). [N.B.: According to the Oxford English Dictionary, the first known use of the word “computer” was in 1613 in a book bearing the name The Yong Mans Gleanings authored by Richard Braithwait.] A programmable calculator can be considered as a computer. The idea of a universal computational device was described by Alan Turing in 1937. Alan Turing proposed that all computations could be performed by a special kind of a machine, now known as a Turing machine. Around 1944 – 45, John von Neumann proposed that along with the data, the programs should also be stored in the memory of a computer. b) Choose the correct one (i) A header file is: (A) A file that contains standard library functions
Computer Concepts and Fundamentals of Programming 124 (B) A file contains definitions and macros (C) A file that contains user defined functions (D) A file that is present in current working directory Answer. (A) A header file in ‘C’ is a file that contains prototype statements and other declarations. It is placed in a library for shared use. (ii) A character variable can at a time store (A) 1 character (B) 8 character (C) 254 characters (D) None of the above Answer. (A) The C standard provides two character types: char and wchar_t. The size of char in ‘C’ is machine dependent. Normally it is one byte or eight bits. [Note: The programs of this section have been executed on Dev C++ Version 5.11] c) Write a C program for adding two numbers. #includestdio.h main() { double num1, num2, result; printf(nEnter first number: ); scanf(%lf, num1); printf(nEnter second number: ); scanf(%lf, num2); result = num1 + num2; printf(n%lf + %lf = %lf, num1,num2, result); return 0; }
Structures and unions 125 A shorter method: #includestdio.h main() { double num1, num2; printf(nEnter two numbers: ); scanf(%lf %lf, num1, num2); printf(n%lf + %lf = %lf, num1,num2, num1 + num2); return 0; } d) Differentiate between data and information. Answer. Data refers to facts and figures. Data are unstructured facts and figures. Information is data that is contextualised, categorized, calculated and condensed. Information is data with relevance and purpose. e) What do you understand by secondary memory Answer. Auxiliary storage is also known as secondary storage. The programs and data are stored permanently in the secondary storage. The programs and data remain in the secondary storage, even when the computer is switched off. Auxiliary storage is used for both input and output. Secondary memory includes all permanent or persistent storage devices, such as flash drives, hard disk drives, magnetic tapes, ROM. Secondary memory is slower than primary memory. [N.B.: Primary storage is also known as main memory. The programs and data are stored temporarily in the main memory during processing. The data in primary storage are erased when the computer is switched off (or in case of logging off from a time- sharing computer). ]
Computer Concepts and Fundamentals of Programming 126 f) How is an array represented in memory? Answer. An array is a collection of elements of the same data type. The name of an array refers to the first byte of the array. The index represents an offset from the beginning of the array to the element being referenced. ‘C’ calculates the address of any element of the array using the formula given below: element address = array base address + (sizeof(element) * index) int num[5]; num[0] num[1] num[2] num[3] num[4] g) (i) What do you mean by Nested structure? Answer. #includestdio.h struct date_of_birth { int dd; int mm; int yy; }; struct personal_details { char name[40]; char addr1[80]; char addr2[80]; struct date_of_birth dob; }; main() { struct personal_details person1; printf(nEnter name: ); scanf(%[^n], person1.name); fflush(stdin); printf(nEnter first line of address: ); scanf(%[^n], person1.addr1); fflush(stdin); printf(nEnter second line of address: ); scanf(%[^n], person1.addr2); fflush(stdin); printf(nEnter date of birth: dd mm yyyy: ); scanf(%d %d %d, person1.dob.dd, person1.dob.mm, person1.dob.yy); printf(nName = %s, person1.name); printf(nFirst line of address = %s, person1.addr1);
Structures and unions 127 printf(nSecond line of address = %s, person1.addr2); printf(nDate of birth = %d/%d/%d, person1.dob.dd, person1.dob.mm, person1.dob.yy); return 0; } (ii) How many bits does a char type data has? Answer. Most of the personal computers use 1 byte to store the char datatype. A byte has 8 bits. [The unit symbol for byte is B and the unit symbol for bit is b. The term byte was coined by Werner Buchholz. The term “qubit” was coined by Benjamin Schumacher. 1 Kilobyte = 1024 bytes 1 Megabyte = 1024 Kilobytes 1 Gigabyte = 1024 Megabytes 1 Terabyte = 1024 Gigabytes 1 Petabyte = 1024 Terabytes 1 Exabyte = 1024 Petabytes 1 Zettabyte = 1024 Exabytes 1 Yottabyte = 1024 Zettabytes] h) Describe the similarities and dissimilarities between algorithm and flowchart. Answer. An algorithm is a logical step-by-step method for solving a problem. An algorithm details the procedure for solving a problem. Algorithm includes calculations, reasoning, and data processing. A flowchart is a pictorial depiction (using different shapes) of the logic used in solving a problem. A flowchart depicts the logic flow of a program. In other words, a flowchart depicts the design of an algorithm. A flowchart helps in pictorial thinking and visualization. A flowchart shows the order and sequence of the actions to be performed for solving a problem.
Computer Concepts and Fundamentals of Programming 128 A few of the symbols used in a flowchart are depicted below: Process Alternate Process Decision Input/Output statement Predefined process (Module Call) Internal storage Document Multidocument Terminator Preparation Manual Input
Structures and unions 129 Manual Operation Connector Off-page Connector Card Punched Tape Summing Junction Or Collate Sort Extract Merge Stored Data
Computer Concepts and Fundamentals of Programming 130 Delay Sequential Access Storage Magnetic Disk Direct Access Storage Display Flow Line An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition, all algorithms must satisfy the following criteria: 1. Input. Zero or more quantities are externally supplied. 2. Output. At least one quantity is produced. 3. Definiteness. Each instruction is clear and unambiguous. 4. Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps. 5. Effectiveness. Every instruction must be very basic so that it can be carried out, in principle, by a person using only pencil and paper. It is not enough that each operation be definite as in criterion 3; it also must be feasible. (Source for definition of algorithm: Ellis Horowitz, Sartaj Sahni, Sanguthevar Rajasekaran) [N.B.: Algorithmics is a term coined by Brassard and Bratley. Algorithmics is the systematic study of the fundamental techniques used to design and analyse efficient algorithms.] i) List out the various application of computer? Answer. Computers are used in Engineering Design, Defence, Health care, Education, Businesses, Weather forecasting, simulation, etc. j) List the advantage of Pseudo-code? Answer. Pseudocode depicts the logic of solving a problem in simple English and mathematics. It is a stepwise description of the logic used for solving a problem. A pseudocode uses structural conventions of a normal computer programming language. A pseudocode is normally to be read and understood by human beings rather than machines. The word pseudo means false and code means programs.
Structures and unions 131	PART-B (14 X 5 = 70 Marks)	Answer and Five Questions 2 a) Write a C program for printing Fibonacci series, taking how many numbers to be print as an input. Answer. The first few terms of the Fibonacci series are: 0, 1, 1, 2, 3, 5, 8, 13, 21, . . . Except for the first two terms, each term is the sum of the preceding two terms. #includestdio.h main() { int f1=0, f2=1, f3; int num, ctr=2; printf(nHow many terms of the Fibonacci series: ); scanf(%d, num); if(num==0) printf(nNo terms to be printed); else if(num==1) printf(n%d,f1); else if(num==2) printf(n%d %d ,f1,f2); else { printf(n%d %d ,f1,f2);	while(ctrnum)	{	f3=f1+f2;	printf(%d ,f3);	f1=f2;	f2=f3;	ctr++;	} } return 0; }
Computer Concepts and Fundamentals of Programming 132 Sample output is produced below: b) Write a C program for checking whether a number is a prime number or not? Answer. #includestdio.h main() { int num; int no_of_factors=0; int i; /* a prime number has exactly two factors 1 and itself */ printf(nEnter number to be checked: ); scanf(%d, num); for(i=1;i=num;i++) { if((num%i)==0) no_of_factors++; } if(no_of_factors==2) printf(n%d is a prime number, num); else { printf(n%d is not a prime number, num); printf(nIt is having %d factors, no_of_factors); } }
Structures and unions 133 [407 is divisible by 1, 11, 37, and 407] c) Differentiate between do-while and while loop with a suitable example. (7+4+3) Answer. The do . . . while() loop The general form of the while() loop is: do
Computer Concepts and Fundamentals of Programming 134 { code-block; }while (expr); If the expr after while evaluates to true then the body of the do . . . while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do . . . while(); loop will be necessarily executed at least once. The do . . . while() loop is an exit-controlled loop. #includestdio.h main() { /* printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++; }while(k=30); return 0; }
Structures and unions 135 The while() loop The general form of the while() loop is: while (expr) {	code-block; } If the expr after while evaluates to true then the body of the while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The while() loop is an entry-controlled loop, which implies that if the expr evaluates to false right at the beginning then the body of the while loop will not be executed even once. #includestdio.h main() { /* printing the integers from 11 to 20 using a while() loop */ int j=11; while(j21) { printf(nj = %d, j); j++; } return 0; }
Computer Concepts and Fundamentals of Programming 136 3) a) How application software differs from system software? Relationship between System and Application Software Example of System Software: Operating System. Examples of Application Software: word processors, spreadsheets, database management systems. System software provides a platform to application software. b) Differentiate between a MAN and a WAN.	(7 + 7) Answer. A LAN (Local Area Network) is usually privately owned and links the devices (Personal Computers, printers, audio and video peripherals) in a single office, building or campus. As at the time of writing this book, the size of LAN is limited to a few kilometers. LANs are designed so that resources (hardware/software) can be shared between personal computers/workstations. LANs can incorporate the concept of a server and clients. A WAN (Wide Area Network) provides long-distance transmission of data, images, etc. over large geographic areas spanning continents or countries.
Structures and unions 137 A MAN (Metropolitan Area Network) is a network with a size between a LAN and a WAN. Basis of comparison LAN MAN WAN Expansion Local Area Network Metropolitan Area Network Wide Area Network Geographical Area Small. For example School, College, Hospital, Office Larger region such as a city or a town Countries or even continents Ownership of network Usually private Private or public Private or public Devices used WiFi, Ethernet cables, Hub, Switch, Router Modem and Wire cable Optic fibres, Microwave, Satellites [Note: VLAN is for Virtual Local Area Network] 4) a) Define an algorithm. How is it useful in the context of software development? Answer. An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition, all algorithms must satisfy the following criteria: 1. Input. Zero or more quantities are externally supplied. 2. Output. At least one quantity is produced. 3. Definiteness. Each instruction is clear and unambiguous. 4. Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps. 5. Effectiveness. Every instruction must be very basic so that it can be carried out, in principle, by a person using only pencil and paper. It is not enough that each operation be definite as in criterion 3; it also must be feasible. (Ellis Horowitz, Sartaj Sahni, Sanguthevar Rajasekaran) Program: A program is the expression of an algorithm in a programming language. Algorithms help in developing code. b) Write a pseudo-code to count number of vowels in a text. (7 + 7) Answer. Obtain text as input from the user and assign it to a string variable Set up a counter for counting vowels and initialize it with 0 (zero) find the length of the string and store it in a variable (string_length, for instance) read the entire string from the first character to the last character (string_length) (using a loop) { read a character if the character read is a vowel (a, e, i, o, u, A, E, I, O, U), then increment counter by 1 } print the value of counter [Note: The examinee is required to write only the pseudocode but for the benefit of the reader a program in ‘C’ for counting the number of vowels in a string is produced below:
Computer Concepts and Fundamentals of Programming 138 #includestdio.h #includestring.h main() { char str[80]; char c; int i, len, ctr=0; printf(nEnter any string: ); scanf(%[^n], str); len=strlen(str); for(i=0;ilen;i++) { c=str[i]; if((c=='a') || (c=='A')) ctr++; else if((c=='e') || (c=='E')) ctr++; else if((c=='i') || (c=='I')) ctr++; else if((c=='o') || (c=='O')) ctr++; else if((c=='u') || (c=='U')) ctr++; } printf(nstr = %s, str); printf(nNumber of vowels = %d, ctr); return 0; } A sample output is shown below: Enter any string: Computer Science str = Computer Science Number of vowels = 6 The program for counting the number of vowels in a string can also be written as follows: #includestdio.h #includestring.h main() { char str[80]; char c; int i, len, ctr=0; printf(nEnter any string: ); scanf(%[^n], str); len=strlen(str);
Structures and unions 139 for(i=0;ilen;i++) { c=str[i]; switch(c) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': ctr++; } } printf(nstr = %s, str); printf(nNumber of vowels = %d, ctr); return 0; } A sample interaction with the program is shown below: Enter any string: Mouse was invented by D. Engelbart str = Mouse was invented by D. Engelbart Number of vowels = 10 ] 5) a) Write a program using pointers to insert a value in an array. Answer. #includestdio.h #define SIZE 10 void func(int *arrptr, int n, int loc); main() { int arr[SIZE]; int i; int num; int location; printf(nNow obtaining %d integers for the array: n, SIZE); for(i=0;iSIZE;i++) { printf(nEnter %dth integer: , i); scanf(%d, arr[i]); } printf(nEnter integer to be inserted: ); scanf(%d, num);
Computer Concepts and Fundamentals of Programming 140 printf(nEnter location at which integer is to be inserted: ); scanf(%d, location); printf(nThe original array elements:); for(i=0;iSIZE;i++) printf(narr[%d] = %d, i, arr[i]); func(arr, num, location); printf(nThe array elements after inserting %d at %d:, num, location); for(i=0;iSIZE;i++) printf(narr[%d] = %d, i, arr[i]); return 0; } void func(int *arrptr, int n, int loc) { if((loc0) || (loc =SIZE)) printf(nThe array subscripts are numbered from 0 to %d, SIZE-1); else arrptr[loc] = n; } A sample interaction with the program is produced below: Now obtaining 10 integers for the array: Enter 0th integer: 0 Enter 1th integer: 1 Enter 2th integer: 2 Enter 3th integer: 3 Enter 4th integer: 4 Enter 5th integer: 5 Enter 6th integer: 6 Enter 7th integer: 7 Enter 8th integer: 8 Enter 9th integer: 9 Enter integer to be inserted: -4521 Enter location at which integer is to be inserted: 3 The original array elements: arr[0] = 0 arr[1] = 1 arr[2] = 2 arr[3] = 3 arr[4] = 4 arr[5] = 5
Structures and unions 141 arr[6] = 6 arr[7] = 7 arr[8] = 8 arr[9] = 9 The array elements after inserting -4521 at 3: arr[0] = 0 arr[1] = 1 arr[2] = 2 arr[3] = -4521 arr[4] = 4 arr[5] = 5 arr[6] = 6 arr[7] = 7 arr[8] = 8 arr[9] = 9 b) What is a null pointer? Give one example. (10 + 4) Answer. A null pointer is a pointer of any type that is assigned the constant NULL (stdio.h). Examples: char *pChar = NULL; /* NULL pointer of type char */ int *pInt = NULL; /* NULL pointer of type int */ float *pFloat = NULL; /* NULL pointer of type float */ double *pDouble = NULL; /* NULL pointer of type double */ If a pointer variable is declared within the main() function or any other function and it has not been initialised or assigned a value, then it contains a garbage value as demonstrated below: #includestdio.h main() { int *iptr; float *fptr = NULL; printf(niptr = %u, iptr); /*iptr will contain a junk value since it is not initialized */ printf(nfptr = %u, fptr); return 0; } Sample output: iptr = 3 fptr = 0
Computer Concepts and Fundamentals of Programming 142 6) a) Explain different types of variable available in C programming language with their byte size in memory. Answer. The following program helps in determining how much memory (in bytes) is required for different data types. #includestdio.h main() { printf(nsizeof(bool) = %d, sizeof(bool)); printf(nsizeof(char) = %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(short int) = %d, sizeof(short int)); printf(nsizeof(long int) = %d, sizeof(long int)); printf(nsizeof(long double) = %d, sizeof(long double)); printf(nsizeof(long long int) = %d, sizeof(long long int)); return 0; } Output: sizeof(bool) = 1 sizeof(char) = 1 sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 sizeof(short int) = 2 sizeof(long int) = 4 sizeof(long double) = 12 sizeof(long long int) = 8
Structures and unions 143 b) Write a function in C program for finding power (a, b), to calculate the value of a raised to b. (4+10) Answer. #includestdio.h long int power(int x, int y); main() { int a, b; long int ans; printf(nEnter the value of base: ); scanf(%d, a); printf(nEnter the value of exponent: ); scanf(%d, b); ans=power(a,b); printf(n%d to the power of %d = %ld, a, b, ans); return 0; } long int power(int x, int y) { long int p=1; int i; for(i=1;i=y;i++) p=p*x; return p; }
Computer Concepts and Fundamentals of Programming 144 7) a) What is an operating system? List the typical functions of operating systems. Answer. An operating system acts as an interface between the hardware of a computer and the user. The two major design goals of an operating system are (i) efficient use of hardware, (ii) efficient use of resources. The Operating System manages: input devices such as keyboard and mouse output devices such as monitor, printer network devices storage devices	processor. The Operating System provides a consistent application interface. When a computer is switched on, the first set of instructions that are usually executed are from the computer’s ROM. This piece of code examines the computer hardware in order to ascertain that the hardware is functioning. This is known as POST (Power-On Self Test). After POST, the computer’s disk drives are activated, and the bootstrap loader is loaded. The bootstrap loader loads the Operating System into the computer’s memory. Examples of Operating Systems: UNIX, Linux, Windows NT, Windows IoT. The UNIX operating system consists of four major components: the kernel, the shell, a standard set of utilities, and application programs. b) What is multi tasking, multi programming, multi threading. (7 + 7) Answer. Multitasking is the concurrent execution of several processes (tasks). The processes share the CPU and main memory. Multitasking can be of several types, for instance, cooperative multitasking, preemptive multitasking, real time multitasking. In Multiprogramming, several different computer programs are loaded into the computer’s memory and execution of the first program loaded onto the memory begins. When the program reaches an instruction which requires it to wait for a peripheral, the context of the program is stored away and execution of the second program in memory begins. Multithreading is the ability of the CPU to execute multiple processes or threads concurrently. For example, three disjoint loops in a single program might be executed concurrently. 8) a) What are library functions? Explain call by value and call by reference with example. Answer. Library functions are in-built functions. The prototype of library functions in ‘C’ is contained in the header files. For example the prototype of printf() is in stdio.h, the prototype of sqrt() function is in math.h. The library functions are optimized for performance. /* Call by value */ #includestdio.h void swap(int a, int b); main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2);
Structures and unions 145 swap(var1, var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } OUTPUT: /* Call by reference */ #includestdio.h void swap(int *a, int *b); main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2);
Computer Concepts and Fundamentals of Programming 146 printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } OUTPUT: In pass by value, the main program [or function like main()] and the subprogram (or the called function) create two different variables or objects. Communication between the main program (or the calling function) and the subprogram (or the called function) is only one-way, i.e. from the main program to the subprogram. The variables or objects created in the main program belong to the main program and the variables or objects created in the sub-program belong to the sub-program. In pass by reference any change in values in the called function will also be reflected in the calling function. [Important Note: There is no pass by reference in ‘C’. is also known as referencing operator in C++.] b) What is the difference between gets() and scanf() function? Write the differences between structures and arrays.	(7 + 7) Answer. gets() is used to obtain a string value from the user. scanf() can be used to obtain a character, int, float, or double type value from the user.
Structures and unions 147 Conversion specifications are to be used with scanf()such as %c for character, %d or %i for integer, %f for float. For accepting a string containing spaces ^[n] is used in scanf(). The gets() function accepts a line terminated by the newline character and converts the newline character to ‘0’. A structure is a collection of related elements, possibly of different or same subtypes, identified by a single name. Each element in the structure is called a field. The difference between an array and a structure is that all elements in an array must be of the same type, while the elements in a structure can be of the same or different types. But an array of structures can be created and array(s) can be part of a structure. The fields (or structure elements) should all be related to one object (as a matter of good programming practice). For example: struct book { char book_name[80]; char author1[80]; char author2[80]; char author3[80]; char publisher[80]; char edition[80]; int no_of_pages; char isbn[14]; }; [The student is advised to read the chapters on arrays and structures carefully in order to gain an understanding for answering this question.] *****
CHAPTER – 12 ELECTRONIC COMMERCE 12.1 Introduction: E-commerce associated with the purchase and sale of goods and/or services via electronic channels such as the internet. E-commerce was first introduced in the 1960s via an electronic data interchange (EDI) on value-added networks (VANs). E-Commerce addresses the need of business organizations, vendors and customers to reduce cost and improve the quality of goods and services also increasing the speed of delivery. A key element of e-commerce is information processing. All steps of commerce, except for production, distribution, and delivery of physical goods, are forms of information gathering, processing, manipulation, and distribution, which computers and networks are perfectly suited to handle E-commerce refers to paperless exchange of business information using different ways: • Electronic Data Exchange (EDI) • Electronic Mail (e-mail) • Electronic Bulletin Boards • Electronic Fund Transfer (EFT) • Other Network-based technologies 12.1.1  Potential Benefits of Electronic Commerce The following are the potential benefits of E-commerce: 1. Internet and web-based electronic commerce is cheaper than traditional EDI. 2. Internet and web-based electronic commerce allows more business partners to be reached than with traditional EDI. 3. Internet arid web-based electronic commerce can reach a more geographically dispersed customer base. 4. Procurement processing costs can be reduced. 5. Cost of purchases can be reduced. 6. Reductions in maintaining records. 7. Lower cycle times. 8. Better customer service and 9. Lower marketing and sales costs. 12.2  Concepts of Electronic Communication Electronic communications the transmission of information using advanced techniques such as computer modems, facsimile machines, voice mail, electronic mail, teleconferencing, video-cassettes and private television network. In general the e-commerce applications will be built on the existing technology infrastructure such as: a set of computers, communications networks, and communications software forming the Information Superhighway.
Electronic Commerce 149 Media or Types of Electronic Communication 1. Telephone: The most commonly and widely used electronic device of communication is telephone. By telephone, people can transmit information orally within a minute. Recently-developed satellite telephoning system has added new dimension in telecommunication system. In most of the cases, it is the easiest and less expensive way of communicating distance people. 2. Telex: Telex is an important device of modern communication technology. Under this system, a tele-printer is used by which information can be communicated fm one place to another with the help of a machine. The tele-printer consists of two parts keyboard transmitter and receiver. When a message is to be sent, the typist presses a button, waits for the dial tone, dials the number desired and types the massage. The message is typed on a small strip of paper at the receiver’s end as it is typed in the originating office. This is one of the quickest and most accurate methods of exchanging written messages. 3. Facsimile or Fax: The use of fax a gradually increasing for transmitting visual materials such as picture, diagrams, illustrations etc. here, the fax machine is connected with a telephonic. The document to be transmitted is fed through the machine, then it is electronically scanned and signals are transmitted to the receiving end where an identical copy of the document is reproduced on a bland sheet of paper by the receiving machine. 4. Electronic Mail or E-Mail: E-mail is one of the most widely used and most popular methods of modern communication system. E-mail involves sending message via telecommunicating links. Here two computer terminals are connected together on network to transfer messages from one to another. The message is typed on a computer screen at one end and is conveyed to the other end through electric impulses. 5. Voice Mail or V-Mail: Voice mail is a form of e-mail. It is used to send the voice of the sender instead of sending written massage to the receiver. The mechanism of sending message here is almost same as in case of e-mail. It is useful to communicate with the original voice tone of the sender. 6. Videoconferencing: Videoconferencing is the latest version of teleconferencing system. Under this method people can meet and work together without being gathered in one room. They can hear and see each other over the television or video screen and can share information with one another. Now-a-days multinational companies use videoconferencing method as a widely used means of communication in order to keep touch with the executives staying miles away from the head office. It also saves money and time of high officials. 7. Internet: Internet is the latest and most amazing development that has changed the way of live regarding communication. It is the world’s largest computer network linked together by telephone lines, radio links or satellite links. Internet can be used for multipurpose functions. It can be used for sending e-mail, for advertisement, for teleconferencing, for telephoning and so on. 8. Multimedia: Multimedia is an excellent invention for upgrading the communication system. Multimedia is a combination of many media brought together to transfer messages. These media can include graphics, photo, music, voice, text and animation. When all of these elements are placed together or computer screen, they become multimedia. It can be effectively used for advertising and publicity campaigns. It is very powerful means of communication. 12.3  Internet and Intranet: Internet: The Internet is the global system of interconnected computer networks that use the Internet protocol suite (TCP/IP) to link devices worldwide. The dictionary definition of internet is that it is a large global system of connected computers that enables people to share information and communicate. Also known as the worldwide web. The internet is now for many of us an indispensable part of our daily lives. It enables us to connect and disseminate data with anyone, anytime and anywhere. It’s one common network, only sharing one common addressing scheme. And a lot of open-standard protocols. Formed by the many thousands of independent networks. It’s thousands of networks agreeing to talk to each other: being on one common network: The Internet.
Computer Concepts and Fundamentals of Programming 150 The Internet is a communal of computer network. It is a network of networks that consists of private, public, academic, business, and government networks of local to global scope, linked by extensive array of electronic, wireless, and optical networking technologies. Fig. Internet of things The internet is nothing more than the computer network which is used to transmit the data from one location to another. With the help of Internet user can search for required information as well as other features such as messaging programs, home shopping, file sharing and music or video downloading sites all operate on top of the basic network. The fact is the internet is little more than a collection of standalone computers, which are all linked together mainly using the telephone network. Computers can be connected with the help of old-fashioned copper cables as well as the newer fiber-optic cables along with wireless radio connections and satellite links. In short, the internet is the means by which we move computerized data from one location to another. Fig. Internet Vs Intranet Intranet An intranet is a private network that can only be accessed by authorized users. The prefix “intra” means “internal” and therefore implies an intranet is designed for internal communications. It is a private network based on TCP/IP protocols that belongs to an organization and is accessible to the organization’s employees or others who have authorization.
Electronic Commerce 151 There is certain internal information that organizations do not want to make public on the Internet. In such scenarios, intranet allows an organization to make wide range of internal information and services accessible only to its employees and authorized persons. A company-wide intranet establishes an important confluence point of internal communication and collaboration. It offers a common point to access internal and external resources. An intranet is built on the technologies for Local Area Networks (LANs) and Wide Area Networks (WANs). And just like the internet, an intranet offers its own powerful modules that sit on top of the basic platform. These features will vary from organization to organization and intranet to intranet. Companies are using intranets to: - share documents and circulate information - communicate company news and corporate messages - complete online tasks and workflow processes - Improve collaboration and joint working across teams and office locations - Encourage employee engagement with blogs, surveys and company forums. The cloud nature of the intranet whereby information is stored on remote servers means that everything on an intranet is accessible 24/7 using smartphone or internet connection. And in the modern digital workplace where more and more employees are telecommuting and working flexibly. The cloud intranet means that staff no longer need to be physically in the office to get things done. With a cloud intranet employees are still working for company whether on their way to office, attending an overseas conference or out on the road visiting clients. It can help to increase the efficiency and effectiveness of employees as well as overall productivity. 12.4  EDI to E Commerce EDI stands for Electronic Data Interchange. EDI is an electronic way of transferring business documents in an organization internally between its various departments or externally with suppliers, customers or any subsidiaries etc. In EDI, paper documents are replaced with electronic documents like word documents, spreadsheets etc. Following are few important documents used in EDI − • Invoices • Purchase orders • Shipping Requests • Acknowledgement • Business Correspondence letters • Financial information letters Steps in an EDI System • A program generates the file which contains the processed document. • The document is converted into an agreed standard format. • The file containing the document is send electronically on network. • The trading partner receives the file. • An acknowledgement document is generated and sent to the originating organization. Advantages of an EDI System Following are the advantages of an EDI System. • Reduction in data entry errors. − Chances of errors are much less being use of computer in data entry. • Shorter processing life cycle − As orders can be processed as soon as they are entered into the system. This reduced the processing time of the transfer documents. • Electronic form of data − It is quite easy to transfer or share data being in electronic format.
Computer Concepts and Fundamentals of Programming 152 • Reduction in paperwork − As lot of paper documents are replaced with electronic documents there is huge reduction in paperwork. • Cost Effective − As time is saved and orders are processed very effectively, EDI proves to be higly cost effective. • Standard Means of communication − EDI enforces standards on the content of data and its format which leads to clearer communication. Issues and challenges related to the growth of EDI? “Growth in EDI ability is becoming a requirement for effectively servicing many large business customers,” explains the researchers’ report. “Even then, implementation of EDI creates difficult and complex problems for organizations. Thus many companies have adopted EDI but have not received the expected results. Subsequently EDI benefits are not guaranteed.” Some common issues are: 1. Failure to include all business processes. With a data interchange platform in the mix, some enterprises continue their reliance on legacy applications which should be rendered outmoded. Additionally, during the platform selection process, decision makers may choose a system that doesn’t address the immediate needs of the organization. These gaps in utility can add more to employees’ plates, managing B2B communication inside and outside the EDI platform. 2. Inadequate budgetary and management support. Shoring up the support of employees at every level is critical to successful deployment. Those individuals may lean on legacy systems, not because of gaps in the framework, but because they’re prone to resisting the new platform. Working with a third-party solutions provider, decision makers should size up the budgetary costs up front so that point people at every level set reasonable expectations. 3. Insufficient staff training. Fault lines in your EDI platform may emerge because employees haven’t been properly oriented to how the systems work. Effective training reduces the time spent on individual tasks and gives your employees dexterity to move forward with a comprehensive understanding of the system. 4. Errors in data security. Companies with sensitive data to store, send and receive require EDI solutions built to protect and secure data. Choosing a system with insufficient data security can leave your organization susceptible to hackers and other outside parties. 5. Lack of flexibility. Another point is the failure for EDI systems to scale, adapt and update alongside the shifting demands of an industry. This is why maintenance and continuous review are essential. 12.5  Concerns for E-commerce Growth The consequences of some of the issues described below are bad publicity, loss of business, disgruntled customers, possible financial damages, unsecured sensitive customer information, and data corruption. 1. Lack of planning • Unrealistic goals • No business focus or site not integrated with your overall business. 2. No promotion or inappropriate promotion • Spending a lot of money just to develop a site without also investing in promotion is wasteful • Doing promotion and not following up. 3. Bad site design poor usability • Simplicity works. Sometimes, it is more important to have targeted content with an overall customer • focus than to have the latest whiz-bang gizmos and a flashy site. • Is content easily found and is the site easy to navigate? • Are fonts too small or set against the wrong background colour? • Is it intuitive to visitors to know the next steps? • Do you have a strong call to action?
Electronic Commerce 153 4. Slow performance • Potentially good sites fail because of performance when visitors wait for the site to load. A site that takes more than a couple of seconds to load will not be successful • Slow sites are usually the result of bad design, a poorly selected host, non-optimised images, or sites overloaded with widgets and gizmos. 5. Coding errors • The site may look and perform well on newer browsers but it can also crash on older browsers • “Page Not Found” and other coding errors. 6. Security hacking issues • Non-secure online payments • Spam attacks on a blog or user comments • Hacked or defaced site • Viruses on your site. 7. Going cheap - you get what you pay for • When outsourcing, if the price sounds too good to be true then it just might be • Free hosting in foreign countries are generally slower with more downtime than local hosting • Not relying on expert advice/help. 8.	Content • Spelling grammar issues • Incorrect or inaccurate content • No contact information! • Poorly written content that is difficult to read • Inappropriate content. 12.6  Technical issues 1. Interoperability: • The ability of systems running in different operating environments to communicate and work together. – E.g., clients running Windows XP can access Web pages from servers running Linux. • For the interoperability to work, the same set of rules (protocols) must be followed • Internetworking standard, i.e., TCP/IP 2.	Security: Three types of security threats – denial of service, – unauthorized access, and – theft and fraud • Denial of Service (DOS): Two primary types of DOS attacks: spamming and viruses a)	Spamming – Sending unsolicited commercial emails to individuals – E-mail bombing caused by a hacker targeting one computer or network, and sending thousands of email messages to it. b)	Viruses: self-replicating computer programs designed to perform unwanted events Worms: special viruses that spread using direct Internet connections Trojan Horses: disguised as legitimate software and trick users into running the program • Unauthorized access a) I Illegal access to systems, applications or data b)	Passive unauthorized access – listening to communications channel for finding secrets. – May use content for damaging purposes c) Active unauthorized access – Modifying system or data – Message stream modification • Fraud occurs when the stolen data is used or modified, Theft of software via illegal copying from company’s servers, Theft of hardware, specifically laptop.
Computer Concepts and Fundamentals of Programming 154 3.	Privacy: • Threats to data	Data collection – Faster and easier data collection through online technology – Cross-referencing real offline consumer data with online purchasing habits collected with or without their knowledge. Or cross-referencing online data with other online data between several Web entrepreneurs, for example – Hidden data collection without consumer consent, possibly through cookies.	Usage tracking – Patterns of online activity lead to inferences about the user’s product preferences for providing customized pop-up ads and referring sites. – May include spyware.	Spyware - A type of program that watches what users do with their computer and then sends that information over the Internet to the spyware’s author. 4.	Phishing: • Misspelled URLs or the use of subdomains • Use of JavaScript commands to alter the address bar by placing a picture of the legitimate URL over the fake one. 12.7  Essential security requirement for the e commerce Security is an essential part of any transaction that takes place over the internet. Customer will loose faith in e-business if its security is compromised. Following are the essential requirements for safe transactions − • Confidential − Information should not be accessible to unauthorized person. It should not be intercepted during transmission. • Integrity − Information should not be altered during its transmission over the network. • Availability − Information should be available wherever and whenever requirement within time limit specified. • Authenticity − There should be a mechanism to authenticate user before giving him/her access to required information. • Non-Repudiabiity − It is protection against denial of order or denial of payment. Once a sender sends a message, the sender should not able to deny sending the message. Similarly the recipient of message should not be able to deny receipt. • Encryption − Information should be encrypted and decrypted only by authorized user. • Auditability − Data should be recorded in such a way that it can be audited for integrity requirements. 12.8  Security Technologies: 12.8.1  What is Cryptography? Cryptography is one of the essential technologies used in building a secure virtual private network(VPN). It is the art and science of making a cryptosystem that is capable of providing information security. Cryptography deals with the actual securing of digital data. It refers to the design of mechanisms based on mathematical algorithms that provide fundamental information security services. It is the establishment of a large toolkit containing different techniques in security applications. 12.8.2  What is Cryptanalysis? The art and science of breaking the cipher text is known as cryptanalysis. Cryptanalysis is the branch of cryptography and they both co-exist. The cryptographic process results in the cipher text for transmission or storage. It involves the study of cryptographic mechanism with the intention to break them. Cryptanalysis is also used during the design of the new cryptographic techniques to test their security strengths. Data confidentiality may be provided by one of two categories of encryption algorithm, namely symmetric cryptography and asymmetric cryptography. Symmetric, or conventional, cryptography requires that the sender and receiver share a key, which is an item of secret information used to encrypt and decrypt data. The process by which two peers agree upon a key over an insecure medium can be problematic as, until the key is agreed, the peers have no way to communicate in secret.
Electronic Commerce 155 12.8.3 Cryptography Algorithms Cryptography primitives are nothing but the tools and techniques in Cryptography that can be selectively used to provide a set of desired security services − • Encryption • Hash functions • Message Authentication codes (MAC) • Digital Signatures A cryptosystem is an implementation of cryptographic techniques and their accompanying infrastructure to provide information security services. A cryptosystem is also referred to as a cipher system. Fig. Cryptosystem The objective of this simple cryptosystem is that at the end of the process, only the sender and the receiver on this communication channel will know the plaintext. Components of a Cryptosystem are: • Plaintext: It is the data to be protected during transmission. • Encryption Algorithm: It is a mathematical process that yields a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext. • Cipher text:  It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not secured. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel. • Decryption Algorithm: It is a mathematical process, that yields a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it. • Encryption Key: It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext. • Decryption Key: It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext. 12.8.4  Types of Cryptosystems There are two types of cryptosystems based on the manner in which encryption-decryption is carried out in the system − 1. Symmetric Key Encryption 2. Asymmetric Key Encryption (public key cryptography) Symmetric Key Encryption: Symmetric encryption is one of the best-known technique. A secret key, which can be a number, a word, or just a string of random letters, is applied to the text of a message to change the content in a particular way. This might be as simple as shifting each letter
Computer Concepts and Fundamentals of Programming 156 by a number of places in the alphabet. As long as both sender and recipient know the secret key, they can encrypt and decrypt all messages that use this key. Symmetric encryption uses a key, which is known as the Symmetric Key. In today’s computer-based system this Symmetric Key is a series of numbers and letters. This Symmetric Key is used to encrypt a message as well as the same key is also used to decrypt it. In Symmetric Encryption uses only one key. Fig. Symmetric key encryption The features of symmetric key encryption are • Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption. • Persons using symmetric key encryption must share a common key prior to exchange of information. • A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome. • In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n × (n – 1)/2. • Keys are recommended to be changed regularly to prevent any attack on the system. • Processing power of computer system required to run symmetric algorithm is less. Challenges of Symmetric Key Cryptosystem There are two restrictive challenges of employing symmetric key cryptography. • Key exchange − Before any communication, both the sender and the receiver need to agree on a secret symmetric key. The key exchange problem arises from the fact that communicating parties must somehow share a secret key before any secure communication can be initiated, and both parties must then ensure that the key remains secret. It requires a secure key establishment mechanism in place. • Trust Issue − Ensuring the integrity of received data and verifying the identity of the source of that data can be very important. Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver ‘trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed. Asymmetric Key Encryption The encryption process where different keys are used for encrypting and decrypting the information is known as Asymmetric Key Encryption. Though the keys are different, they are mathematically related and hence, retrieving the plaintext by decrypting ciphertext is feasible. The most commonly used implementations of public key cryptography (also known as public-key encryption) are based on algorithms presented by Rivest-Shamir-Adelman (RSA) Data Security.
Electronic Commerce 157 Public key cryptography involves a pair of keys known as a public key and a private key (a public key pair), which are associated with an entity that needs to authenticate its identity electronically or to sign or encrypt data. Each public key is published and the corresponding private key is kept secret. Data that is encrypted with the public key can be decrypted only with the corresponding private key. RSA public key pairs can be any size. Typical sizes today are 1024 and 2048 bits. Fig. Asymmetric key encryption The features of Asymmetric key encryption are • Encryption and decryption, which allow two communicating parties to disguise data that they send to each other. The sender encrypts, or scrambles, the data before sending it. The receiver decrypts, or unscrambles, the data after receiving it. While in transit, the encrypted data is not understood by an intruder. • Nonrepudiation, which prevents: The sender of the data from claiming, at a later date, that the data was never sent and the data from being altered. • Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related − when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext. • It requires to put the public key in public repository and the private key as a well-guarded secret.	Hence, this scheme of encryption is also called Public Key Encryption. • Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme. • When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits. • Host2 uses his private key to extract the plaintext. • Length of Keys (number of bits) in this encryption is large and hence, the process of encryption- decryption is slower than symmetric key encryption. • Processing power of computer system required to run asymmetric algorithm is higher. 12.8.5  Digital signatures A digital signature guarantees the authenticity of an electronic document or message in digital communication and uses encryption techniques to provide proof of original and unmodified documentation. Digital signatures are used in e-commerce, software distribution, financial transactions and other situations that rely on forgery or tampering detection techniques. A digital signature is also known as an electronic signature In asymmetric ciphers, one single individual holds the private key, while everyone can get the public key So if you encrypt with the private key, and send both cryptogram and message, anyone can check that “decryption” with the public key does indeed create
Computer Concepts and Fundamentals of Programming 158 the message. Note that some public key systems do not allow “encryption” with the private key. Most systems can be modified to generate and verify signatures. A digital signature can be created using asymmetric cryptography. Fig. Digital signature A digital signature is applied and verified, as follows: • The document or message sender (signer) or public/private key supplier shares the public key with the end user(s). • The sender, using private key, appends the encrypted signature to the message or document. • The end user decrypts the document and verifies the signature, which lets the end user know that the document is from the original sender. Review Questions Q.1 What are the advantages and disadvantages of e commerce? Q.2 What are the intranet features? Q.3 What are issues and challenges related to the growth of EDI? Q.4 What are Types of e commerce? Explain in details. Q.5 What are the Common issues with e-commerce and doing business online? Q.6 What is digital cash and what is the basic model of transaction system? Enlist different properties of digital cash. Q.7 What are the pros and cons of digital cash? Q.8 What are the essential security requirement for the e commerce? Q.9 What are the Measures to ensure Security for e commerce? Q.10 Symmetric vs asymmetric encryption ? Q.11 Explain types of Cryptosystems in detail.
Appendix Opening a web browser via a ‘C’ program Is it possible to open a web page in a browser using a ‘C’ program? The program below provides an answer to the aforementioned question: Program listing one #includestdio.h main() { char url[25] = “www.mail.yahoo.com”; char launch[255]; system(“clear”); sprintf(launch, “gnome-open %s”, url); system(launch); return 0; } [NOTE: 1. The above code should be compiled on a Linux system. 2. Parallel methods for opening a web-browser are available for Windows/Mac OSs. For instance, on a Mac OS, system(“open http://url”); might be used.] An alternative method of opening a web page is given below: Program listing two #includestdio.h main() { char url[25] = “www.iiml.ac.in”; char launch[255]; system(“clear”); sprintf(launch, “firefox %s”, url); system(launch); return 0; }
Computer Concepts and Fundamentals of Programming 160 [Note: The code in Program listing two assumes that firefox is installed on the workstation and the appropriate PATH has been set.] The program below provides an illustration of another method of opening a web-browser via a ‘C’ program: Program listing three #includestdio.h #includeunistd.h main() { execl(“/usr/bin/firefox”, (char *)0); printf(“execl() could not open the web-page”); /* this line will be executed only if execl() above is not able to launch firefox*/ return 0; } The reader may interpret execl()as execute and leave. The execl() function replaces the current process by running the program specified as an argument to the execl()function. The process identifier (PID) of the new process will be the same as the PID of the old process (old process refers to the program in program listing three which is being compiled and executed and new process refers to firefox). The prototype of the execl()function is: int execl(const char *path, const char *arg1,...); execl() is a variadic function and the list of arguments to execl() should be terminated by a NULL pointer, therefore (char *)0 has been used to indicate the end of arguments to execl().
Appendix 161 INDIAN MARITIME UNIVERSITY (A Central University, Government of India) June 2017 End Semester Examinations B. SC (Nautical Science – First Semester (Computer Science – UG21T 3104) (AY 2016 - 17 batch onwards) Date: 08.06.2017 Maximum Marks: 70 Time: 3 Hrs Pass Marks: 35 Answer any SEVEN of the following. (7X10=70) 1. What is mail merge? Write the procedure to use mail merge for inviting your friends for your birthday party. (10 Marks) 2. How are charts useful in Excel? Compare any three chart types available in Excel. (10 Marks) 3.	a)  What is the difference between Animation and Transition? (5 Marks) b)  Write the procedure to insert a chart in a slide (5 Marks) 4. Carry out the following conversions: (10 Marks) i. (101011)2=(?)10 ii. (247.6875)10=(?)8 iii.	(3A.2F)16=(?)10 iv. (5647.45)8=(?)16 v. (35.625)10=(?)2 5. Write short notes on (10 Marks) a. EDI (Electronic data interchange) b. Encryption c. Digicash d. SSL (Secure Socket Layer) e. Hashing 6.	a)  Write about character input and output in details (5 Marks) b)  Write a program to accept a number from keyboard and find whether it odd or even (5 Marks) 7. Explain switch-case statement with example (10 Marks) 8. Define function. Explain how a user defined function can be created and used. (10 Marks) 9. a)  Define pointer. Explain how is it declared and used. (5 Marks) b)  Define structure. Explain declaring and accessing of structure members with example. (5 Marks) *****
Computer Concepts and Fundamentals of Programming 162 INDIAN MARITIME UNIVERSITY (A Central University, Government of India) MAY/JUNE 2018 END SEMESTER EXAMINATION BSc (Nautical Science) Semester: III Computer Science Paper I (UG21T2301) Date:02-07-2018 Max Marks: 70 Time: 3Hours Pass Marks: 35 Answer any seven of the following. (7X10=70) 1.	a)	Represent the decimal 12345.54321 into its equivalent binary number. (10) b)	Convert (100001100)2 into Hexadecimal c)	Convert decimal 465 to its octal equivalent d)	Convert (1001.01)2 to its equivalent decimal e)	Convert hexadecimal (2 4 3 F)16 to octal 2.	a)	Find 2’s complement of 6910 (2) b)	Subtract 15 from 87 using two’s complement (4) c)	Do as directed (4) i. add (10111)2 and (110101)2 ii.	add (1011001 )2 by (111010 )2 3. Write short notes on (a)	excess 3 code (5) (b)	ASCII code (5) 4.	a)	Explain the difference between volatile and non-volatile memory give example (5) b)	What is the use of virtual memory? (5) 5. Write short note on different computer environments (10) 6.	a)	Describe Satellite Communication system (5) b)	What is E-commerce and Give some applications of E-commerce? (5) 7.	a)	Distinguish between symmetric and asymmetric cryptography. (5) b)	Define digital cash (2) c)	Write notes on SET (3) 8.	a)	Define Electronic Data Interchange (EDI). Explain the process of EDI (5) b)	Differentiate between Internet and intranet (5) 9. Explain how SSL protocol is used for secure transaction (10) *****
Question Bank For Practice 163 QUESTION BANK FOR PRACTICE 1. The numbers 1, 8, 17, 18, 26, and 27 are very special numbers, because the sum of the digits of the cubes of these numbers is equal to the number itself: Num Cube Sum of the digits of the cube 1 1 1 8 512 5 + 1 + 2 = 8 17 4913 4 + 9 + 1 + 3 = 17 18 5832 5 + 8 + 3 + 2 = 18 26 17576 1 + 7 + 5 + 7 + 6 = 26 27 19683 1 + 9 + 6 + 8 + 3 = 27 Write a program to print all such numbers in the range 1 to 2000. 2. The number 153 is an amazing number, because, 153 is divisible by the sum of its digits: 153/(1 + 5 + 3) = 17 (such integers which are divisible by the sum of their digits are known as Harshad numbers or Niven numbers) Write a program to print all such numbers in the range 1 to 2000. This question is not related to Armstrong Numbers in any way. 3. An emirp is 'prime' spelt backwards and refers to a prime number which will yield a different prime number when written backwards. For instance 13 and 31, 17 and 71, 37 and 73. Write a program to print all such numbers in the range 1 to 2000. 4. The number 1547 is interesting, because 1547 = (1 + 5 + 4 + 7)(12 + 52 + 42 + 72 ) i.e. it is equal to the product of the sum of their digits and sum of the squares of their digits. Write a program to print all such numbers in the range 1 to 4000. 5. The number 301 is a very interesting number because 3012 = 90601 and 1032 = 10609 i.e. 301 and 103 are the reverse of each other and their squares are also the reverse of each other. Write a program to print all such numbers in the range 1 to 4000. 6. Write a program in 'C' to interchange the value of two integer variables. temp=var1; var1=var2; var2=temp; 7. Write a program in 'C' to interchange the value of two integer variables without using a third variable. METHOD 1: var1=var1-var2; var2=var2+var1; var1=var2-var1;
Computer Concepts and Fundamentals of Programming 164 METHOD 2: var1=var1+var2; var2=var1-var2; var1=var1-var2;	(i) Write a program to input three sides and determine whether they form a triangle or not?	(ii) Write a program to input any string and convert the uppercase letters in the string to lowercase 8. Write a program in ‘C’ to illustrate matrix operations such as addition and multiplication of two matrices. The order of the matrix should be decide at run time. 9. A number of nine (9) digits has the following properties: The first two digits (from the left) are divisible by 2; The first three digits (from the left) are divisible by 3; The first four digits (from the left) are divisible by 4; The first five digits (from the left) are divisible by 5; The first six digits (from the left) are divisible by 6; The first seven digits (from the left) are divisible by 7; The first eight digits (from the left) are divisible by 8; The first nine digits (from the left) are divisible by 9; It contains all the digits from 1 to 9 exactly once. Write a program in ‘C’ to find the number. 10. Write a program to print the sum of the digits of the first 11 prime numbers. Each prime number should be printed on a new line and the sum of the digits of the prime number should appear next to the prime number. For example: PRIME NUMBER SUM OF DIGITS OF THE PRIME NUMBER 2 2 3 3 5 5 7 7 11 2 13 4 17 8 19 10 23 5 29 11 31 4
Question Bank For Practice 165 11. Write a program to print the gap between two consecutive prime numbers for the first 20 prime numbers. For example: PRIME NUMBER GAP BETWEEN TWO CONSECUTIVE PRIME NUMBERS 2 3 Gap between 3 and 2 = 1 5 Gap between 5 and 3 = 2 7 Gap between 7 and 5 = 2 11 Gap between 11 and 7 = 4 13 Gap between 13 and 11 = 2 17 Gap between 17 and 13 = 4 19 Gap between 19 and 17 = 2 23 Gap between 23 and 19 = 4 29 Gap between 29 and 23 = 6 31 Gap between 31 and 29 = 2 12. For natural numbers in the range of 1 to 1000,: There are x no of prime numbers: Total no. of prime numbers which end in 1: Total no. of prime numbers which end in 3: Total no. of prime numbers which end in 7: Total no. of prime numbers which end in 9: 13. Write a program to find the sum of the following series: 1 – 2 + 3 – 4 + 5 – 6 + . . . + 99 – 100 Method 1: 1 – 2 = –1 3 – 4 = –1 5 – 6 = –1 … 99 – 100 = –1 Thus, we need to add –1 fifty times. Method 2: s = s + i * (–1)(i+1) Method 3: s=0; for(k=1;k100;k+=2) s= s + k – (k+1);
Computer Concepts and Fundamentals of Programming 166 Method 4: s1=s2=0; for(i=1;i100;i+=2) s1=s1 + i; for(j=2;j=100;j+=2) s2=s2 – j; s3=s1 + s2; Method 5: s1=s2=0; for(i=1;i100;i+=2) s1=s1 + i; for(j=2;j=100;j+=2) s2=s2 + j; s3=s1 – s2; 14. Write a program in ‘C’ to display the first seven lines of the following pattern: 0 1 1 2 2 2 3 4 4 3 4 7 8 7 4 5 11 15 15 11 5 6 16 26 30 26 16 6 15. Write a program in ‘C’ to input any integer and print it in words. For example, if the input is 213, then the output should be Two Hundred Thirteen (range: 1 – 9999). 16. Write a program in ‘C’ to input any integer and print its Roman Equivalent (range: 1 – 2999). 17. Write a program in ‘C’ to input any integer and count the number of digits in it. 18. Write a program in ‘C’ to input any integer and print it in reverse order. 19. Write a program in ‘C’ to input any string and print its words in reverse order. For instance, if the input is LION IS A PET ANIMAL, then the output should be ANIMAL PET A IS LION. 20. Write a program in ‘C’ to input any string and print its words in the same order but internally reversed. For instance, if the input is LION IS A PET ANIMAL, then the output should be NOIL SI A TEP LAMINA 21. Write a program in ‘C’ to input any word and print all its permutations. 22. Write a program in ‘C’ to input two integers and print the greater without using less than and greater than operators. Do NOT use the IF construct. 23. Write a program in ‘C’ to determine the angle (reflex-angle) between the hour hand and minute hand.
Question Bank For Practice 167 A book that might help in building basic logic. It dwells on emirp, primorial, Father prime, Sophie-Germain Prime, Wilson prime, Cullen prime, Prime Quadruplet, Prime Quintuplet, Prime Sextuplet, Weifrich prime, Woodall prime, Fermat primes, Mersenne primes, Pi-prime, Circular prime numbers, interprime, twin primes, Left-truncatable prime, Right-truncatable primes, Two-sided primes, Permutable primes, Titancic primes,... Many corporations have lost several billions of opportunities only because of sophistry in the analyses of data available to them. This book is a must-read as it dwells on fundamental mathematical reasoning, fallacies, howlers, and number- tricks.
COMPUTER CONCEPTS AND FUNDAMENTALS OF PROGRAMMING

COMPUTER CONCEPTS AND FUNDAMENTALS OF PROGRAMMING

  • 1.
    COMPUTER CONCEPTS AND FUNDAMENTALS OF PROGRAMMING GaneshB. Ingle, Vishwanath Mishra, Ms. G. Sridevi Devasena, Smt. Unnati Nitin Chaudhari, Wallace Jacob M A L AY S I AS I N G A P O R EI N D I A
  • 2.
    Notion Press Old No.38, New No. 6 McNichols Road, Chetpet Chennai - 600 031 First Published by Notion Press 2018 Copyright © Ganesh B. Ingle, Vishwanath Mishra, G. Sridevi Devasena, Unnati Nitin Chaudhari, Wallace Jacob 2018 All Rights Reserved. ISBN 978-1-644291-23-8 This book has been published with all efforts taken to make the material error-free after the consent of the author. However, the author and the publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause. No part of this book may be used, reproduced in any manner whatsoever without written permission from the author, except in the case of brief quotations embodied in critical articles and reviews.
  • 3.
    Preface We will remainindebted to the luminaries of the ilk of Wilhelm Schickard, Blaise Pascal, Guglielmo Marconi, Samuel F. B. Morse, Nikola Tesla, Charles Babbage, Lady Ada Lovelace, John von Neumann, Alan Turing, Grace Hopper, Edsger W. Dijkstra, Claude Shannon, Edgar F. Codd, Dennis Ritchie, Bjarne Stroustrup, Vint Cerf, Tim Berners-Lee, Sergey Brin, Larry Page, Steven Paul Jobs, and their like, who framed and changed the landscape of electronics, telecommunications and computing forever. We are also thankful to Vijay Mukhi (and his team), Yashvant Kanetkar whose books on BASIC, C, C++, UNIX, and JAVA, explored acres and acres of uncharted territory. We feel that their contribution cannot be measured. We have drawn inspiration from them and hence written this book. This book is a humble endeavor on our part to help the IMU Marine Engineering and Nautical Science students appreciate and comprehend the very important subject: Computer Science. Indubitably ‘computer science and technology’ has invaded and pervaded our lives and the best course of action would be to understand it and use it for the benefit of every living and non-living being. As frail human beings, we might be lacking in many spheres. However, we are open to constructive criticism and humbly solicit suggestions for improvement of the text from the esteemed readers of our book.
  • 5.
    CONTENT Chapter –1 1 INTRODUCTION TO COMPUTER Chapter – 2 11 COMPUTER SOFTWARE Chapter – 3 18 INTRODUCTION Chapter – 4 24 DATA TYPES AND OPERATORS Chapter – 5 35 DECISION CONTROL INSTRUCTIONS Chapter – 6 46 DECISION MAKING AND LOOPING Chapter – 7 59 ARRAYS Chapter – 8 75 STRINGS Chapter – 9 79 USER DEFINED FUNCTIONS Chapter – 10 83 POINTERS Chapter – 11 89 STRUCTURES AND UNIONS Chapter – 12 148 ELECTRONIC COMMERCE
  • 7.
    Chapter – 1 INTRODUCTIONTO COMPUTER 1.1  Computer Introduction It is an electronic device capable of performing complex arithmetical and logical operations to give desired output. 1.1.1  Characteristics of Computer are as follows: • Speed • Arithmetical and Logical Operations • Accuracy • Reliability • Storage • Retrieving Data and Program • Automation • Versatility (Flexible) • Consistency • Communications 1.1.2 Hardware/Software Computer Hardware Parts of computer, which can be touch is called hardware.(Physical Parts) • Monitor • CPU • Key Board • Mouse • Speaker Computer Software Parts of computer, which cannot be touch is called software. These are set of instructions or programs written in any computer programming language. Operating System Software: Windows, MAC, Linux Application Software: MS Office, Photoshop, Media Player Internet Browser Software: Internet Explorer, Google Chrome, Mozilla Firefox, etc.
  • 8.
    Computer Concepts andFundamentals of Programming 2 1.1.3  Generations of computer i. First(1945-1955): Used vacuum tubes. Were very large. Generated immense heat. Very expensive. ii. Second(1955-1965):Used transistors. Continued to be large andexpensive. iii. Third(1965-1975):Used integrated circuits. Significant reduction in size and cost iv. Fourth(1975-1995): Uses Very Large Scale Integration. Desktop computers would not have been possible without VLSI. It used Microprocessor minimizing the size of P.C. v. Fifth: Will provide us with Artificial intelligence. Also called knowledge information processing system Fig: Generations of computer 1.2  Classification of Computers Computers are classified depending upon the types of electronics/hardware and processing power Depending on hardware they are classified in to • Analog, • Digital and • Hybrid Depending on processing power and speed they are classified in to Personal computer • A single-user computer • Can be useful at School, Home, etc. • Known as Micro Computer • Laptop, Desktop Workstation • A powerful, single-user computer. • A workstation is like a personal computer, but it has a more powerful microprocessor • higher-quality monitor. • Can be found in companies etc. Minicomputer • A multi-user computer • Capable of supporting from 10 to hundreds of users simultaneously. • Can be found in banks, government departments etc.
  • 9.
    Introduction to computer 3 Mainframe •A powerful multi-user computer • Capable of supporting hundreds or thousands of users simultaneously. Supercomputer • An extremely fast computer • Can perform hundreds of millions of instructions per second • Weather, scientific research can be done by these types of computer 1.3  Basic internet terminology Host A computer that is used to transfer data on the Internet. Web Hosting To store and make web pages available and ready for inquiries, or a computer that has a consistent connection to the Internet. Domain A domain name is a description or representation of a computer's location on the Internet. It is usually separated by a dot. For example: http://www.imu.edu.in DNS DNS (Domain Name System) is a large database of domain names and their correspondent Internet (IP Addresses). IP address This 32 bit address mechanism for addressing the devices on the network. Different classes of IP address as per the IPV4 standard are as follows: i. Class A –(0-126) ii. Class B-(128-191) iii. Class C-(192-223) iv. Class D-(224-239) v. Class E-(240-255) The 127 is used by the local host as loop back adapter and for the inter processes communication. In the above list class D and E are used for the experimental purpose. HTML Hypertext Markup Language is a coding language used to tell a browser how to place pictures, text, multimedia and links to create a web page. FTP File Transfer Protocal is a method of transferring files between two computers on the Internet InterNic InterNic is governs and maintains the name and host registration on the Internet.
  • 10.
    Computer Concepts andFundamentals of Programming 4 URL Uniform Resource Locator is a web address used to connect website on the World Wide Web. For example: http://www.imu.edu.in Port The total nober of ports are 0-65535.A a Port is a channel that a server software would listen to, for any inquiries. Bit Bit is a single digit base 2. For example: 1 is a bit or 0 is a bit. Byte A Byte generally consists of eight bits. Server The server computer coupled with server software, listens for inquiries from a client computer. Upload To upload is to transfer data from your computer to another computer. Download To download is to transfer data from another computer to your computer. sss 1.4  Basic computer organization Following points are important points as far as computer organization is concern Fig: CPU and main memory • Processor system and its operations: Data Movement Operations. It is moving data from memory to the CPU It is moving data from memory to memory. It performs all input and output. Arithmetic and Logical Operations. It performs all integer arithmetic. It compares two quantities shifting, rotating bits in a quantity, testing, comparing, and converting bits • CPU: manages the instruction-execution cycle. FETCH – DECODE – EXECUTE. Coordinates the activities of other devices. Different types of CPU operations are, starting a program Halting a program, skipping to other instructions, testing data to decide whether to skip over some instructions.
  • 11.
    Introduction to computer 5 Fig:inside CPU • Memory: (fast access) storage device for preserving binary data and instructions. Memory is divided into units or words. Each is usually a standard size or fixed-length. Each memory word has a unique address for random access. It has two types RAM and ROM. Random Access Memory (RAM). It is readable, writeable, usually volatile (e.g., Dynamic RAM or DRAM) used as general storage. ROM is Read Only Memory (ROM).It is readable, permanent, nonvolatile,Special-purpose storage for data and instructions. • Input/output system • Input/output devices • Secondary storage i. Main memory is organization ii. Types of instructions for a typical processor iii. Scale and performance factors 1.5  Number systems The “base” or a “radix” is the number of different digits or combination of digits and letters that a system of counting uses to represent numbers. There are different types of number systems depending upon the base or radix. There are different types of number systems are as follows: • Binary (radix=2): 1000111101 (radix = 2) • Ternary (radix=3): 0 to 3 • Octal (radix=8): 0 to 7 • Decimal (radix=10): 0 to 9 • Hexadecimal (radix=16): 0 to 9 and A, B, C, D, E, F • BCD, EBCD, Excess3, BCO(Binary Coded Octal), BCH(Binary Coded Hexadecimal) • Binary, octal, decimal and hexadecimal are called positional number system
  • 12.
    Computer Concepts andFundamentals of Programming 6 1.5.1  Decimal to binary conversion: 1) (37)10 = (100101)2 q r 2 37 1 2 18 0 2 9 1 2 4 0 2 2 0 2 1 1 2 0 2) (41.68755)10 = (101001.1011)2 q r 2 41 1 2 20 0 2 10 0 2 5 1 2 2 0 2 1 1 2 0 Note: conversion from radix 10 to any base –r system similar to the above example only 2 will replaced by r 1.5.2  Decimal to Octal Conversion (153.153)10 = (231.406517)8 q r 8 19 1 8 2 3 8 0 2 1.5.3  Decimal to Hexadecimal Conversion (253)10 = (FD)16 q r 16 253 13(D) 16 15 15(F) 100101 101001 0.68755 × 2 = 1.3750 0.3750 × 2 = 0.7500 0.7500 × 2 = 1.5000 101 231 0.153 × 8 = 4.104 0.104 × 8 = 0.832 0.832 × 8 = 6.656 0.656 × 8 = 5.248 0.248 × 8 = 1.984 0.984 × 8 = 7.872 0.406517 FD
  • 13.
    Introduction to computer 7 1.5.4 Binary to Decimal Conversion (101101)2 = 25 × 1+24 × 0 +23 × 1 + 22 × 1 + 21 × 1 + 20 × 1 (101101)2 = 32 + 8 + 4 + 1 = (45)10 1.5.5  Binary to Hexadecimal conversion (1100101001010010)2 = (CA52)16 i. First, split the binary number into groups of four digits, starting with the least significant digit. ii. Next, convert each group of four binary digits to a single hex digit. iii. Put the single hex digits together in the order in which they were found, and you’re done! 1100 1010 0101 00102 C A 5 2 1.5.6  Hexadecimal to Decimal Conversion A hexadecimal number can be converted into its equivalent number in decimal system by calculating the sum of the products of each symbol multiplied by its corresponding place value. Examples (6B39)16 = (27449)10 (6 × 163 ) + (11 × 162 ) + (3 × 161 ) + (9 × 160 ) = 24567 + 2816 +48 + 9 = 27449 1.5.7  Octal to Decimal conversion An octal number can be converted into its equivalent number in decimal system by calculating the sum of the products of each digit multiplied by its corresponding place value. (13256)8 = (5806)10 into its equivalent in decimal systems (1 × 84 ) + (3 × 83 )+(2 × 82 ) + (5 × 81 )+(6 × 80 ) = 4096 + 1536 + 128 + 40 + 6 = 5806 1.5.8  Octal to Hexadecimal conversion The given octal number can be converted into its equivalent hexadecimal number in two different steps: i. Convert the given octal number into its binary equivalent by representing each digit in the octal number to its equivalent 3-bit binary number. ii. Divide the binary number into 4-bit sections starting from the least significant bit Example: (365)8 = (F5)16 3 6 5 011 110 101 0000 1111 0101 0 F 5 } } } }
  • 14.
    Computer Concepts andFundamentals of Programming 8 1.5.9  Binary coded decimal The BCD system is employed by computer systems to encode the decimal number into its equivalent binary number. This is generally accomplished by encoding each digit of the decimal number into its equivalent binary sequence. The main advantage of BCD system is that it is a fast and efficient system to convert the decimal numbers into binary numbers as compared to the pure binary system. The 4-bit BCD system is usually employed by the computer systems to represent and process numerical data only. In the 4-bit BCD system, each digit of the decimal number is encoded to its corresponding 4-bit binary sequence. The two most popular 4-bit BCD systems are: • Weighted 4-bit BCD code • Excess-3 (XS-3) BCD code 1.5.10 EBCDIC The EBCDIC code is an 8-bit alphanumeric code that was developed by IBM to represent alphabets, decimal digits and special characters, including control characters. The EBCDIC codes are generally the decimal and the hexadecimal representation of different characters. This code is rarely used by non IBM-compatible computer systems. 1.5.11  ASCII code The ASCII code is pronounced as ASKEE and is used for the same purpose for which the EBCDIC code is used. However, this code is more popular than EBCDIC code as unlike the EBCDIC code this code can be implemented by most of the non-IBM computer systems. Initially, this code was developed as a 7-bit BCD code to handle 128 characters but later it was modified to an 8-bit code. 1.5.12  Gray Code Gray code is another important code that is also used to convert the decimal number into 8-bit binary sequence. However, this conversion is carried in a manner that the contiguous digits of the decimal number differ from each other by one bit only. Decimal Number 8-Bit Gray Code 0 00000000 1 00000001 2 00000011 3 00000010 4 00000110 5 00000111 6 00001111 7 00001011 8 00001001 9 00001101 We can convert the Gray coded number to its binary equivalent by remembering the following two major rules: • The Most Significant Bit (MSB) of the Gray coded number and the equivalent binary number is always the same. • The next-to-most significant bit of the binary number can be determined by adding the MSB of the binary number to the next-to-most significant bit of the gray coded number.
  • 15.
    Introduction to computer 9 1.5.12 1! and 2 ! Complement Fixed point representation and floating point representation +ve numbers are stored in register of digital computer in sign magnitude form Negative numbers are stored in three different way a. Signed magnitude representation b. Signed 1s complement representation c. Signed 2s complement representation Why do we require 1! and 2! Complement? One’s complement and two’s complement are two important binary concepts. Two’s complement is especially important because it allows us to represent signed numbers in binary, and one’s complement is the interim step to finding the two’s complement.Two’s complement also provides an easier way to subtract numbers. Example (9)10 to binary is (0 0001001)2 Note: here MSB 0 indicate + sign (-9)10 to binary is a. 1 0001001 signed magnitude b. 1 1110110 signed 1s complement c. 1 1110111 signed 2s complement Note: 2s complement can be formed by leaving LSB unchanged and remaining taking 1s complement 1.5.13  Rules for binary addition and subtraction a. Addition b. Subtraction 0 + 0 = 0 0 - 0 = 0 0 + 1 = 1 0 - 1 = 1 borrow 1 1 + 0 = 1 1 - 0 = 1 1 + 1 = 1 carry 0 1 - 1 = 0 Example 1. Addition 2. Subtraction 1 0 1 1 0 1 (Augend) 1 0 1 1 0 1 (Minuend) 1 0 0 1 1 1 (Addend) 1 0 0 1 1 1 (Subtracted) 1 1 1 1 1 0 1 0 1 0 0 0 0 0 1 1 0 Sum = 1010100 Difference=1010100 1.5.14  Binary Multiplication The multiplication of two binary numbers can be carried out in the same manner as the decimal multiplication. Unlike decimal multiplication, only two values are generated as the outcome of multiplying the multiplication bit by 0 or 1 in the binary multiplication. These values are either 0 or 1.
  • 16.
    Computer Concepts andFundamentals of Programming 10 The binary multiplication can also be considered as repeated binary addition. Therefore, the binary multiplication is performed in conjunction with the binary addition operation. A B A×B 0 0 0 0 1 0 1 0 0 1 1 1 1 1 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 1.5.15  Binary Division Binary division is also performed in the same way as we perform decimal division. Like decimal division, we also need to follow the binary subtraction rules while performing the binary division. The dividend involved in binary division should be greater than the divisor. The following are the two important points, which need to be remembered while performing the binary division. If the remainder obtained by the division process is greater than or equal to the divisor, put 1 in the quotient and perform the binary subtraction. If the remainder obtained by the division process is less than the divisor, put 0 in the quotient and append the next most significant digit from the dividend to the remainder. Example Perform the binary division of the decimal numbers 18 and 8. The equivalent binary representation of the decimal number 18 is 10010. The equivalent binary representation of the decimal number 8 is 1000. 1.2.16  Floating point representation 1 0 0 0 ) 1 0 0 1 0 ( 1 0 → Quotient 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 → Remainder Floating-point numbers are the numbers containing two different parts, integer part and fractional part. The floating-point numbers are also referred as real numbers. A notation known as scientific notation is used to represent the real numbers in the computer system. The scientific notation, also called exponential notation, represents the real numbers in the following form: 325.123 → 3.25123 × 102 0.000000245 → 2.45 × 10-7 1000.0101 → 1.0000101 × 23 4333.123 4.333123 × 103 43.33123 × 102 433.3123 × 101
  • 17.
    CHAPTER – 2 COMPUTERSOFTWARE 2.1  Computer software Computer software is software programs, applications, scripts, code written in any computer language which can be executed and instruction. In order to access hardware directly it requires software. In other word various kinds of programs used to operate computers and related devices can be also termed as software. 2.2  Types of software i. System software a. Operating system Operating system is an interface between the hardware and the user. b. System utility ii. Application software a. Word processing b. Spread sheets c. Database d. Web browser 2.3  Compter networking 2.3.1  Types of computer networks i. LAN • This is a local area network up to 100 meters with speed of 100 Mbps to 1000 Mbps • Any computer network for business, school, and college is termed as local area network. • LAN can bet connected to other LAN by means of bridges • Multiple LAN connected forms a WAN • On LAN users can share expensive devices, such as laser printers, as well as data.  • It works much faster as compared to traditional telephone network • Topology, Protocol and media distinguishes one LAN from another • Number of devices are connected by means of switch, or stack of switches, using a private addressing scheme. • The media generally used for LAN is twisted pair cables or coaxial cables • Less congestion in the network
  • 18.
    Computer Concepts andFundamentals of Programming 12 ii. MAN • This A metropolitan area network. It is larger than LAN or group of LAN • A network up to a city, big university, telephone company network is termed as MAN • It interconnect several local area networks by bridging them with backbone lines • Less fault tolerance and more congestion in the network • It is costlier than Lan for implementation • Devices used are Modem ,Wire/Cable, repeaters • It’s hard to design and maintain a Metropolitan Area Network. • Data transfer rate and the propagation delay is moderate iii. WAN • This a wide area network • Data speed is lower 1/10 th of LAN • Propagation delay is one of the biggest problems • It has two types asynchronous transfer mode (ATM) network and Point-to-Point WAN • Devices used in WAN are Optic wires, Microwaves and Satellites.  • Communication medium used is PSTN or Satellite Link. • More noise and error in data transmission There are other types of networks other than this are as follows i. PAN (Personal Area Network) ii. SAN (Storage Area Network) iii. EPN (Enterprise Private Network) iv. VPN (Virtual Private Network) 2.3.2 Topology Method of arranging and connecting different computer on the network with different way is termed as topology. There are different topologies as follows: Fig: 5.1
  • 19.
    Computer software 13 i. BUStopology • All computers are connected by means of single backbone cable • Terminators are used to avoid the bouncing of the signals • There is no dedicated client server architecture existing in this topology • All computers are connected by means of T connectors to the backbone cable • Failure of backbone cable bring down the complete network ii. STAR topology • All computers are connected in star fashion by means of switch • Message is being broadcasted • Wastage of bandwidth • Failure of centralize switch bring down the complete network • Switch/hub can act as repeater or signal booster. • Unshielded Twisted Pair (UTP) Ethernet cable is used to connect computers. • Failure of one node does not affect the network • Performance such topology is depended on capacity of central device iii. RING topology • All the devices are connected to each other in the shape of a ring or a loop. • It connects all nodes and forms a closed loop. • Here new term token is used • Computer wants to pass a message, then it catches the token, attaches a message, and then transmits around the network. When its transmission is complete, the device passes the token to the next. • It much secure way of communication • Moving, adding and changing devices may affect the network • No need for network server to control the connectivity • A dual ring topology can be used as a backup if the first ring fails. • Slower than a star topology. iv. MESH topology • It has two types full mesh and partial mesh topology • In full mesh topology every node is connected with rest of the node • It is very expensive topology.it will need a lot of capital to invest • A broken node won’t distract the transmission of data in a mesh network. • It has huge bandwidth • It makes large data center • Maintaining mesh networks can be very hard to manage. • Network redundancy problem v. TREE topology • Its combination of BUS and Star topology • It is highly scalable topology • Identifying the faulty is easy • Best for implementation of temporary networks.
  • 20.
    Computer Concepts andFundamentals of Programming 14 • Point to point connection for every devices • If one device is damaged it doesn’t affect the network • Failure of backbone cable bring down the complete network • This network is insecure, anybody can see transmitted data. • As more and more nodes maintenance becomes difficult vi. CELLULAR topology • This topology is mainly used for mobile communication. • It forms cellular structure and any authentic mobile device comes in vicinity of the network gets connected with the network. • Every cell represents cell represents a portion of the total network area. • In this topology every node transmits in a certain area called a cell. • Data transmission is in the form of cellular digital packet data. 2.3.3  Computer network devices i. HUB • Hub is generally used in LAN. • There are two types of hub active (with external power supply) and passive(without external power supply). • It handles a data types like frames then transmits to the destination port • Hub broadcasts the data • Hubs are stupid devices as they cannot distinguish between data ,which port a frame should be sent to • Passive hub don’t amplify the signals • Hubs works in data link layer of OSI reference model. ii. Switch • Switches is generally used in LAN. • Switches works in data link layer of OSI reference model. • It handles a data types like frames then transmits to the destination port • It filters the packets and regenerating forwarded packets. • It reduces the collision rate. • Many switches are self-learning. • Switches may have different port with different speed of transmission. • Almost one-half of the nodes connected to a switch can send data at the simultaneously. iii. Router • It works in the network layer of OSI reference model • It filter out network traffic • It dividing networks logically instead of physically. • Ip router divides network into many segments • It routs the packet to the particular network • There are two types of router static and dynamic • For every packet it calculate checksum, and rewrite the MAC header
  • 21.
    Computer software 15 iv. Bridge •It connects two or more LAN networks • It works in data link layer of OSI reference model • It segment’s the larger network • It has the capacity to block the incoming flow of data. • It can build a list of the MAC addresses • The types of bridges are Transparent Bridge, Source Route Bridge, Translational Bridge v. Gateway • It is a stopping point for data from other networks • This is a specialized computer.It also operates as a firewall and a proxy server. • It controls all of the data traffic your Internet Service Provider (ISP) • It keeps out unwanted traffic to get in private network. • Network interface cards (NIC/LAN card) • This is also called as LAN card, Ethernet card ,interface controller card, expansion card, network card, network adapter or network adapter card (NAC) • This is working in the physical layer of OSI reference model • It has RJ45 port through which it gets connected to network 2.3.4  OSI reference model Fig: OSI reference model
  • 22.
    Computer Concepts andFundamentals of Programming 16 2.3.5 TCP/IP TCP/IP is normally considered to be a 4 layer system. The 4 layers are as follows: i. Application layer ii. Transport layer iii. Network layer iv. Data link layer Application layer This layer includes applications or processes that use transport layer protocols to deliver the data to destination computers. The list of application layer protocols are: i. HTTP (Hypertext transfer protocol) ii. FTP (File transfer protocol) iii. SMTP (Simple mail transfer protocol) iv. SNMP (Simple network management protocol) etc. Transport layer: This is a backbone to data flow between two hosts. This layer receives data from the application layer above it. There are many protocols that work at this layer but the two most commonly used protocols at transport layer are TCP and UDP. Network layer: The main purpose of this layer is to organize or handle the movement of data on network. The main protocol used at this layer is IP. While ICMP (used by popular ‘ping’ command) and IGMP are also used at this layer. Data link layer: This layer mainly consists of device drivers in the OS and the network interface card attached to the system. Both the device drivers and the network interface card take care of the communication details with the media being used to transfer the data over the network. Fig: TCP/IP layered model 2.3.6 Firewall A firewall is a protective barrier between your PC and internet. When you are connected to the Internet, you are a potential target to of cyber threats, such as hackers that attack through security loopholes. Types of firewall are as follows Hardware: A hardware firewall can be a router or any other security product that is placed between your PC and the outside world. More than one PC can be connected with that security device or router, and each will be protected by the firewall.
  • 23.
    Computer software 17 Software: Asoftware firewall is installed on your PC, it will deflect incoming attacks and hide open ports. It will warn you about suspicious outgoing traffic. You can have a software firewall on each computer for strong protection. By installing software firewall, an attacker will have to cross two level security to access your PC. Fig: Firewall 2.3.7  IP and classes of IP(IPV4) This 32 bit address mechanism for addressing the devices on the network. Different classes of IP address as per the IPV4 standard are as follows: v. Class A –(0-126) vi. Class B-(128-191) vii. Class C-(192-223) viii. Class D-(224-239) ix. Class E-(240-255) The 127 is used by the local host as loop back adapter and for the inter processes communication. In the above list class D and E are used for the experimental purpose.
  • 24.
    CHAPTER – 3 INTRODUCTION 3.1 Origin of C language ‘C’ is a multi-purpose language (including system programming) whose development is linked to UNIX operating system. Many of the features of ‘C’ language stem from BCPL (developed by Martin Richards) and B (developed by Ken Thompson). Both BCPL and B are “type less” languages while C provides a variety of data types. It may not be an exaggeration to say that 'C' programming language, developed by Dennis Ritchie, circa 1969-1973 (although quite a few book quote the year as 1972), is one of the most powerful, general-purpose programming languages which has also inspired many other languages. In 1978, Dennis Ritchie and Brian W. Kernighan published the seminal book The C Programming Language (the version of the language described in the book is known as KR C) which served as a language definition and a formal reference that helped in vast popularization of the 'C' language. In 1983, ANSI instituted the X3J11 committee which was assigned a goal of developing a 'C' standard. The X3J11 committee produced its report by the end of 1989 – ANSI X3.159- 1989 “Programming Language C”. This version of 'C' is known as C89. This standard was ratified by ISO as ISO/IEC 9899-1990 (sometimes referred to as C90). In fact, C89 and C90 refer to the same language. In 1995, ISO released an extension to the internationalization support to the standard. This version is known as C95. A revised standard was again released in 1999 (now known as C99). In 2007, work began on yet another revision of the C standard resulting in the development of the C11 standard which was approved in December 2011. C89 contains 32 keywords which are given below: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C99 has 37 keywords. The five new keywords which were added are: _Bool, _Complex, _Imaginary, inline, restrict C11 has 44 keywords. The seven new keywords which have been added are: _Alignas, _Alignof, _Atomic, _Generic, _Noreturn, _Thread_local, _Static_assert Interestingly, 'C' language used to include a reserved keyword called entry, which in fact was never implemented and now has been removed as a reserved word.
  • 25.
    Introduction 19 3.2  Why C? 3.3 Structure of C program 3.3.1  Performing addition of two numbers with following constraint a) do not use –(-) operation b) do not use *(-1) operation c) do not use (a2-b2)/a-b operation #includestdio.h main() { int add ,diff, a,b; printf(nEnter the value of two numbersn ); scanf(%d%d,a,b); add = 2*a; diff = a - b; add=add-diff; printf(nThe addition of 2 nos without using + is:==%d ,add); } 3.3.2  The first function to be executed in a ‘C’ program: All 'C' programmers know that the main() function is the entry point for a 'C' program. Can a user-defined function be executed before the main() function in a 'C' program? Can a user-defined function be executed after the last statement in main() function in a 'C' program? Can the main() function be called explicitly from within another function? Can the return value from the main() function be utilised in a program? These questions often pose a serious challenge to a 'C' programmer. The program below (compiled using gcc) answers the aforementioned questions: /*The code below is explained in greater detail in Chapter 2*/ #includestdio.h void func1(void) __attribute__((constructor)); void func2(void) __attribute__((destructor)); main() { printf(nWithin main()); return -8; } void func1() { system(clear); printf(nWithin func1()); }
  • 26.
    Computer Concepts andFundamentals of Programming 20 void func2() { int k = main(); printf(nWithin func2(), k = %d, k); } A sample output of the program is given below: Within func1() Within main() Within main() Within func2(), k = -8 The output of the above code testifies that func1() is called first, after which main() function is executed, after which func2() function is called, which in turn explicitly calls main() function which in turn returns -8 which is stored in integer variable k. [N.B. Two underscores precede the word attribute and two underscores follows the word attribute in the statements: void func1(void) __attribute__((constructor)); and void func2(void) __attribute__((destructor));] For those working on the TurboC compiler, the following program can be used: #includestdio.h void func1(); void func2(); #pragma startup func1 #pragma exit func2 main() { printf(nWithin main()); return -8; } void func1() { system(clear); printf(nWithin func1()); } void func2() { int k = main(); printf(nWithin func2(), k = %d, k); }
  • 27.
    Introduction 21 3.4.2  Executing a‘C’ program using gcc Open an editor like gedit, kwrite Type the c program and save it with the extension .c if no error(s) then type the command: ./a.out Open terminal and type command gcc filename.c Compiling a 'C' program using gcc: exploring a few switches The gnu C compiler is widely used because of its versatility (it can carry out preprocessing, compilation, assembly and linking) and also it has set unmatched standards in terms of reliability. The gnu C compiler actually works in stages. The stages are as follows: the Source Code is converted into Translation Unit the Translation Unit is converted into Assembly Code the Assembly Code is converted into Object Code the Object Code is converted into an Executable File. As an instance, if a program is saved by the name test57.c, then on issuing the command: gcc test57.c the intermediate stages might be visualized as follows: test57.c → test57.i → test57.s → test57.o → a.out The following switches can be used with the gcc command line in order to examine the intermediate stages: gcc –E test57.c (in order to obtain the Translation Unit equivalent. In short the –E option tells gcc to stop compilation after preprocessing) gcc –S test57.c (in order to obtain the Assembly Code) gcc –c test57.c (in order to obtain the Object Code). gcc test57.c (in order to obtain the executable file a.out) [NOTE: The options –E and –S are in uppercase] Let us consider the code snippet (saved in a file test57.c, for instance) shown below: #includestdio.h main() { printf(Computer Science); return 0; }
  • 28.
    Computer Concepts andFundamentals of Programming 22 In order to examine the intermediate assembly language file, the following commands can be used. $ gcc -S test57.c $ cat test57.s will produce the intermediate assembly language listing of the above code snippet. The command $ gcc -o test test57.c makes an executable file by the name of test. In order to look at the output now, the user can type the following command at the command line: $./test instead of typing./a.out. The GNU Compiler Collection (gcc) can compile programs written in several high level languages such as FORTRAN, C, C++, Java, Objective-C, etc. In order to determine languages whose programs can be compiled using gcc, the Package Manager rpm* can be used as illustrated below: $ rpm -qa | grep gcc A sample interaction with rpm (using it as suggested above) might appear as follows: compat-gcc-34-g77-3.4.6-4 gcc-4.1.2-14.el5 gcc-gfortran-4.1.1-52.el5 compat-gcc-34-c++-3.4.6-4 gcc-java-4.1.1-52.el5 compat-gcc-34-3.4.6-4 gcc-c++-4.1.1-52.el5 compat-libgcc-296-2.96-138 libgcc-4.1.2-14.el5 gcc-objc-4.1.1-52.el5 *rpm is a package manager which can be used to build, install, update, query and erase individual software packages. [N.B. gcc used to be the GNU 'C' Compiler, but is now used for GNU Compiler Collection.] In order to compile the program, the following instruction needs to be typed: gcc program-name.c -trigraphs To find out the version of gcc, one can use gcc -v The gdb utility in Linux gdb (GNU debugger) is an efficient utility for debugging a program that has been compiled by gcc (GNU compiler collection). In order to start gdb the user is only required to type gdb and press ENTER at the command line (although there are many alternatives of starting gdb). Let us understand using gdb through a sample program (Program listing one) Program listing one
  • 29.
    Introduction 23 #includestdio.h main() { double num1,num2, quot; printf(Enter the numerator: ); scanf(%lf, num1); printf(Enter the denominator: ); scanf(%lf, num2); quot=num1/num2; printf(n%lf/%lf=%lf, num1, num2, quot); return 0; } Suppose the above program is stored in a file by the name of test.c. In order to compile the program, the user may type: $ gcc -g test.c -o test It may not be meaningful to use gdb by compiling the program without the -g switch, since gdb will not have information related to variable names, function names, line numbers, etc. Once the program is compiled, the user can type $ gdb test Now, in order to run the program, the user can type run (or r) at the gdb prompt and press ENTER. [NOTE: The user can also type gdb -quiet test or gdb -q test in order to suppress the introductory and copyright messages which are displayed when gdb is invoked.] In order to list the program, the user can type list (or l) at the gdb prompt and press ENTER. In order to set a breakpoint at line number 10, the user can type b 10 at the gdb prompt and press ENTER. Function name can also be used for setting a breakpoint at the first executable statement within the function. After pausing at the indicated line, the user can type continue (or c) in order to continue executing the program. The breakpoint(s) can be deleted through the delete command. Once a breakpoint has been set, then the commands n (for next) and s (for step) can also be used to execute the next line of the program. The commands n and s work differently if the next line happens to be a function call. If n is used then the next pause will be at the statement following the function call, whereas, if s is used then the next pause will be at the first line of the function which is invoked. The bt command can be used for printing the current location within the program and the stack trace showing how the current location was reached if a function calls another function or itself i.e. there has been a series of function calls. The kill command can be used in order to terminate the program being executed in gdb. The help command can be typed at the gdb prompt if the user feels stuck anywhere. If the user wants to quit the gdb utility then the user should type q and press ENTER.
  • 30.
    CHAPTER – 4 DATATYPES AND OPERATORS 4.1  Data Types Data (singular: datum, plural: data) are a collections of facts and figures. Data will be of particular type. For instance, 786 is an integer, 0.23 is a fractional value and ‘x’ is a letter of the English alphabet. The built-in data types in ‘C’ are as follows: Type Example Format specifier char char c = ‘a’; %c int int num = 786; %d, %i float float f = 0.3f %f, %e, %E, %g, %G double double d = 0.9876 %lf void Used with functions and pointers. It is wrong to write void a. Format specifiers are also known as conversion characters/format code. In ‘C’, a string is an array of characters terminated by the NULL character ‘0’ – backslash zero. The format specifier for string is %s. Use of Format specifiers %o and %x
  • 31.
    Data types andoperators 25 Sample Program 4.1 /* for printing octal and hexadecimal equivalents of an integer */ #includestdio.h main() { int num = 9123; printf(nIn base 10, num = %d, num); printf(nIn base 8, num = %o, num); printf(nIn base 16, num = %x, num); return 0; } A sample output is shown below: In base 10, num = 9123 In base 8, num = 21643 In base 16, num = 23a3 Sample Program 4.2 /*When 0 (zero) and 0x precede an integer*/ #includestdio.h main() { int num1 = 03672; /* when an integer begins with 0, then it implies that it is an octal integer*/ int num2 = 0x3672; /* when an integer begins with 0x, then it implies that it is an hexadecimal integer*/ int num3 = 3672; printf(nnum1 = %d, num1); printf(nnum2 = %d, num2); printf(nnum3 = %d, num3); return 0; } A sample output is shown below: num1 = 1978 num2 = 13938 num3 = 3672 In C99, _Bool is also a data type. _Bool is a datatype for Boolean (true/false). The stdbool.h header files defines an alias bool for _Bool. Arrays, structures, enumerations are derived data types in ‘C’. ‘C’ language supports user-defined datatypes also. A variable declaration statement such as int n = 953; means four bytes will be given the name n and the integer 953 will be stored in these four bytes.
  • 32.
    Computer Concepts andFundamentals of Programming 26 Escape sequences in ‘C’ An escape sequence in ‘C’ usually begins with the backslash () and is a sequence of two or more characters which when used inside a character or string literal is translated into another character or sequence of characters. Escape sequence Character represented a alarm i.e. a beep sound or a bell sound b backspace f formfeed n linefeed i.e. new line r carriage return t horizontal tab v vertical tab backslash ’ single quotation mark ” double quotation mark ? question mark printf(): A function for displaying output; scanf(): A function for accepting input. Obtaining an integer as input from the user: Sample Program 4.3 #includestdio.h main() { int num; printf(Enter an integer: ); scanf(%d, num); printf(nThe integer you entered is: %d, num); return 0; }
  • 33.
    Data types andoperators 27 A sample output is shown below: Enter an integer: 786 The integer you entered is: 786 Sample Program 4.4 Obtaining a fractional number as input from the user: #includestdio.h main() { float num; printf(Enter a fractional value: ); scanf(%f, num); printf(nThe fractional value you entered is: %f, num); return 0; } A sample output is shown below: Enter a fractional value: 0.34 The fractional value you entered is: 0.340000 The sizeof() operator [sizeof() is an unary operator] in C can be used to determine the size (in bytes) of a variable, constant or datatype. Sample Program 4.5 #includestdio.h main() { printf(nsizeof(0.93) = %d, sizeof(0.93)); printf(nsizeof(0.93f) = %d, sizeof(0.93f)); printf(nsizeof(71) = %d, sizeof(71)); printf(nsizeof(71L) = %d, sizeof(71L)); /*lowercase L can also be used*/ return 0; } Obtaining a string as input from the user: Sample Program 4.6 #includestdio.h main() { char name[80]; printf(Enter your name: ); scanf(%s, name); printf(nThe name you entered is: %s, name); return 0; }
  • 34.
    Computer Concepts andFundamentals of Programming 28 Enter your name: Ganesh Ingle The name you entered is: Ganesh When reading a string through scanf(%s, name); The scanf() stops reading after the first whitespace (tab, space or Enter). Therefore Ingle was not stored in name. In order to read blank spaces into a string variable, the scanf() function can be used as illustrated below: Sample Program 4.7 #includestdio.h main() { char name[81]; printf(nEnter your name: ); scanf(%[^n]s, name); /* whatever you type before pressing the ENTER key will be stored in name*/ printf(nYou entered: %s, name); return 0; } Enter your name:Ganesh Ingle You entered: Ganesh Ingle Sample program 4.8 /* Program illustrating the use of sizeof() operator */ #includestdio.h main() { printf(nsizeof(char) = %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(long int) = %d, sizeof(long int)); return 0; } sizeof(char) = 1 sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 sizeof(long int) = 4 sample program 4.9: The program below exemplifies the use of long long in 'C' langauage. Program listing #includestdio.h main() { long long n=1; /* The range of long long is from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 */ int i;
  • 35.
    Data types andoperators 29 system(clear); for(i=1;i11;i++) { printf(n%lld,n*n); n=n*10+1; } return 0; } Sample program 4.10. To print the message I am the one without using any semicolon through out the program #includestdio.h main() { if(printf(I am the one)) { } } 4.11 The program to print message without using {,} in the program using di graph. #includestdio.h main() % printf(nhello welcome to TMIn); printf(nGMn); printf(nnCompletedn); % Sample program 4.12The program to print message without using {,} in the program using tri-graph characters. #includestdio.h main() ?? printf(nhello welcome to TMIn); printf(nGMn); printf(nnCompletedn); ?? 4.2  Data models The choices made by each implementation about the sizes of the fundamental types are collectively known as data model. Four data models found wide acceptance: 32 bit systems: • LP32 or 2/4/4 (int is 16-bit, long and pointer are 32-bit) • Win16 API
  • 36.
    Computer Concepts andFundamentals of Programming 30 • ILP32 or 4/4/4 (int, long, and pointer are 32-bit); • Win32 API • Unix and Unix-like systems (Linux, Mac OS X) 64 bit systems: • LLP64 or 4/4/8 (int and long are 32-bit, pointer is 64-bit) • Win64 API • LP64 or 4/8/8 (int is 32-bit, long and pointer are 64-bit) • Unix and Unix-like systems (Linux, Mac OS X) Other models are very rare. For example, ILP64 (8/8/8: int, long, and pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. Unicos on Cray). 4.3 Constants Constants are of two types a. Numeric Constants • Integer Constants (eg. 1,-15, 045, 0X6) • Real Constants (eg.3.14) b. Character Constants • Single Character Constants(eg. ‘5’ ,’z’) • String Constants (eg. “IMU” • Backslash Character Constants Eg: Constants Meaning a beep sound b backspace f form feed n new line r carriage return t horizontal tab v vertical tab ' single quote double quote backslash 0 null
  • 37.
    Data types andoperators 31 4.4 Operators 4.4.1  Arithmetic Operators Operator Description Example + Adds two operands. A + B = 30 − Subtracts second operand from the first. A − B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 -- Decrement operator decreases the integer value by one. A-- = 9 4.4.2  Relational Operators Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A B) is not true. Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A B) is true. = Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A = B) is not true. = Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A = B) is true. 4.4.3  Logical Operators Operator Description Example Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A B) is true. Sample Program 4.13 /*illustration of postfix and prefix */ #includestdio.h main() { int num1 = 7; int num2, num3; num2 = num1++; /*first assign the value of num1 (7 in this case) to num2 and thereafter increment the value of num1*/ printf(nnum1 = %d, num1); printf(nnum2 = %d, num2); num3 = ++num1; /*first increment the value of num1, and then assign the value of num1 to num3*/ printf(nnum1 = %d, num1);
  • 38.
    Computer Concepts andFundamentals of Programming 32 printf(nnum3 = %d, num3); return 0; } A sample output is shown below: num1 = 8 num2 = 7 num1 = 9 num3 = 9 Sample program 4.14 /* to find the angle between the hour hand and the minute hand*/ #includemath.h #includestdio.h main() { int h, m; double a1, a2; system(clear); printf(nthis code determines the angle between the hour hand and the minute hand); printf(Enter time (h m): ); scanf(%d %d, h, m); a1 = fabs(((h * 30) + (m * 1/2.0)) - (m * 6)); a2 = 360 - a1; printf(nTime = %d:%d, h,m); printf(nAngle between the hour hand and minute hand: %lf %lf, a1,a2); printf(nnCompletedn); return 0; } 4.4.4  Ternary operator Conditional operators return one value if condition is true and returns another value is condition is false.This operator is also called as ternary operator. Syntax: (Condition? true_value: false_value); Example: (A 100? 0: 1); 4.4.5  Bitwise Operator p q p q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
  • 39.
    Data types andoperators 33 Operator Description Example Binary AND Operator copies a bit to the result if it exists in both operands. (A B) = 12, i.e., 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -61, i.e,. 1100 0011 in 2's complement form. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A 2 = 240 i.e., 1111 0000 Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A 2 = 15 i.e., 0000 1111 4.4.6  Assignment operator Operator Description Example Binary AND Operator copies a bit to the result if it exists in both operands. (A B) = 12, i.e., 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -61, i.e,. 1100 0011 in 2's complement form. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A 2 = 240 i.e., 1111 0000 Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A 2 = 15 i.e., 0000 1111 4.4.7  Programs for practice Write a C program to solve following problems 1. To find the square of the number given by user. 2. To perform addition of two numbers entered by user. 3. To perform addition of two numbers without using + operator. 4. To calculate average of three real numbers entered by user. 5. To input a single character and display it with proper message. 6. To show the effect of various escape sequences. 7. To swap the values of two variables without using third variable. 8. To input the rainfall of three consecutive days in cms and find its a average. Print the output with proper messages. 9. Find the simple interest. Inputs are principal amount, period in year and rate of interest. 10. To enter a integer number and carry out modular division operation by 2,3 and 6 and display the result. 11. To find the average temperature of five sunny days. Assume the temperature in Celsius. 12. Find the area and perimeter of a) Square b) Rectangle c) triangle Accept the sides as input from user. 13. The speed of a van is 75 km/hr. Write a program to find the number of hours required for covering a distance of 500 km. 14. Write a program to evaluate the following expressions and display their results. 15. x2 + 2x3*(2*x) 16. (x+y+z)2 17. Write a program to read three integers from the keyboard using one scanf statement and output them on one line using: 18. Three printf statements, 19. Only one printf with conversion specifiers.
  • 40.
    Computer Concepts andFundamentals of Programming 34 20. Calculate the volume and area of a sphere using the formulas: 21. V = 4µr3/3 22. A = 4µr2 23. test the program using the values for the radius. 24. WAP to Calculate the mass of air in an automobile tire, using the formula PV = 0.37m(T + 460)where P = pressure in pounds per square inch, V= volume in cubic feet, m=mass of air in pounds, T=temp. In Fahrenheit. The tire contains two cubic feet of air. Assume that the pressure is 32psi at room temperature.
  • 41.
    CHAPTER – 5 DECISIONCONTROL INSTRUCTIONS The decision control instructions are broadly classified as: 1. if statement 2. if else statement 3. switch case statement 5.1  if statement if (test condition) { Statement 1; Statement 2; Statement 3; …………. …………. Statement n; } 5.2  if else statement if (test condition) { Statement 1; Statement 2; …………. …………. Statement n; } else { Statement 1; Statement 2; …………. …………. Statement n; }
  • 42.
    Computer Concepts andFundamentals of Programming 36 5.3  nested if else statement if(condition) { //Nested if else inside the body of if if(condition2) { //Statements inside the body of nested if } else { //Statements inside the body of nested else } } else { //Statements inside the body of else } 5.4  if elseif else statement if (test condition) { Statement 1; Statement 2; …………. …………. Statement n; } else if { Statement 1; Statement 2; …………. …………. Statement n; } else { Statement 1; Statement 2; …………. …………. Statement n; }
  • 43.
    Decision control instructions 37 5.5 switch case statement The syntax of switch case construct is as follows Switch ( expression ) // this expression can int or char it should not be float or string { case value-1: block-1; break; case value-2: block-2; break; case value-3: block-3; break; case value-4: block-4; break; default: default-block; break; } 5.6  goto statement Generally goto is a unconditional jumping statement. It can be used as a loop statement as well. Beacusae of unconditional jumping it is not advised to use goto statement. Sample code that illustrates goto statement as follows #includestdio.h #includeconio.h void main() { int number; clrscr(); printf(“Mango”); goto x; // here x is a label not a variable of any type ,program jumps to the label x abruptly. y: printf(“Orange”); goto z; // here z is a label not a variable of any type ,program jumps to the label z abruptly. x: printf(“Banana”); goto y; // here y is a label not a variable of any type ,program jumps to the label z abruptly. z: printf(“Apple”); getch(); }
  • 44.
    Computer Concepts andFundamentals of Programming 38 Sample Program 5.1 Write a program to check whether the entered year is a leap year or not considering century year condition (IMU question paper May June 2016) #include stdio.h #include conio.h int main() { int year; printf(Enter a year: ); scanf(%d,year); if(year%4 == 0) { if( year%100 == 0) { // year is divisible by 400, hence the year is a leap year if ( year%400 == 0) printf(%d is a leap year., year); else printf(%d is not a leap year., year); } else printf(%d is a leap year., year ); } else printf(%d is not a leap year., year); getch(); return 0; } Or Other logic #include stdio.h #include conio.h int main() { int year; printf(Enter a year: ); scanf(%d,year); if(year=1752) { if(year%4 == 0) printf(%d is a leap year., year ); else printf(%d is not a leap year., year ); } else {
  • 45.
    Decision control instructions 39 if(year%100 == 0 year%400 != 0) printf(%d is not a leap year., year); else if( year%100 == 0 year%400 != 0) printf(%d is a leap year., year); else if(year%4 == 0) printf(%d is a leap year., year ); else printf(%d is not a leap year., year ); } getch(); return 0; } Or other logic /** * C program to check Leap Year */ #include stdio.h main() { int year; /* Read year from user */ printf(Enter year: ); scanf(%d, year); /* * Check for leap year */ if(((year%4 == 0) (year%100 !=0)) || (year%400==0)) { printf(LEAP YEAR); } else { printf(COMMON YEAR); } } Sample Program 5.2 Write program to device a calculator with menu driven program # include stdio.h # include conio.h int main() { char operator; double firstNumber,secondNumber; printf(Enter an operator (+, -, *, /): );
  • 46.
    Computer Concepts andFundamentals of Programming 40 scanf(%c, operator); printf(Enter two operands: ); scanf(%lf %lf,firstNumber, secondNumber); switch(operator) { case '+': printf(%.1lf + %.1lf = %.1lf,firstNumber, secondNumber, firstNumber+secondNumber); break; case '-': printf(%.1lf - %.1lf = %.1lf,firstNumber, secondNumber, firstNumber-secondNumber); break; case '*': printf(%.1lf * %.1lf = %.1lf,firstNumber, secondNumber, firstNumber*secondNumber); break; case '/': printf(%.1lf / %.1lf = %.1lf,firstNumber, secondNumber, firstNumber/firstNumber); break; // operator is doesn't match any case constant (+, -, *, /) default: printf(Error! operator is not correct); } getch(); return 0; } Sample program 5.3 Program to print three digit number in words #includestdio.h main() { int num, t, d1, d2, d3; system(clear); printf(This program is for printing a three digit integer in words: n); printf(Enter an integer: ); scanf(%d, num); if(num0) { t=-num; printf(minus ); } else if(num==0) { printf(zero); t=num; } else
  • 47.
    Decision control instructions 41 t=num; d1=t/100; d2=(t%100)/10; d3=t%10; if(d1==1) printf(Onehundred ); else if(d1==2) printf(Two hundred ); else if(d1==3) printf(Three hundred ); else if(d1==4) printf(Four hundred ); else if(d1==5) printf(Five hundred ); else if(d1==6) printf(Six hundred ); else if(d1==7) printf(Seven hundred ); else if(d1==8) printf(Eight hundred ); else if(d1==9) printf(Nine hundred ); if(d2==1) { if(d3==1) printf(Eleven); else if(d3==2) printf(Twelve); else if(d3==3) printf(Thirteen); else if(d3==4) printf(Fourteen); else if(d3==5) printf(Fifteen); else if(d3==6) printf(Sixteen); else if(d3==7) printf(Seventeen); else if(d3==8) printf(Eighteen); else if(d3==9) printf(Nineteen); } else { if(d2==2) printf(Twenty );
  • 48.
    Computer Concepts andFundamentals of Programming 42 else if(d2==3) printf(Thirty ); else if(d2==4) printf(Forty ); else if(d2==5) printf(Fifty ); else if(d2==6) printf(Sixty ); else if(d2==7) printf(Seventy ); else if(d2==8) printf(Eighty ); else if(d2==9) printf(Ninty ); } if(d2!=1) { if(d3==1) printf(One); else if(d3==2) printf(Two); else if(d3==3) printf(Three); else if(d3==4) printf(Four); else if(d3==5) printf(Five); else if(d3==6) printf(Six); else if(d3==7) printf(Seven); else if(d3==8) printf(Eight); else if(d3==9) printf(Nine); } printf(nnCompletedn); } Sample program 5.4 Write a program to Find the roots of quadratic equation using switch case construct /** * C program to find all roots of a quadratic equation using switch case */ #include stdio.h #include math.h //Used for sqrt() main() {
  • 49.
    Decision control instructions 43 floata, b, c; float root1, root2, imaginary; float discriminant; printf(Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ); scanf(%f%f%f, a, b, c); discriminant = (b*b) - (4*a*c); /* * Computes roots of quadratic equation based on the nature of discriminant */ switch(discriminant 0) { case 1: //If discriminant is positive root1 = (-b + sqrt(discriminant)) / (2*a); root2 = (-b - sqrt(discriminant)) / (2*a); printf(Two distinct and real roots exists: %.2f and %.2fn, root1, root2); break; case 0: //If discriminant is not positive switch(discriminant 0) { case 1: //If discriminant is negative root1 = root2 = -b / (2*a); imaginary = sqrt(-discriminant) / (2*a); printf(Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2fn, root1, imaginary, root2, imaginary); break; case 0: //If discriminant is zero root1 = root2 = -b / (2*a); printf(Two equal and real roots exists: %.2f and %.2fn, root1, root2); break; } } } Sample program 5.5 Write a program to count minimum number of notes in an amount /** * C program to count minimum number of notes in an amount */ #include stdio.h main() { int amount;
  • 50.
    Computer Concepts andFundamentals of Programming 44 int note500, note100, note50, note20, note10, note5, note2, note1; note500 = note100 = note50 = note20 = note10 = note5 = note2 = note1 = 0 ; /* Reads amount from user */ printf(Enter amount: ); scanf(%d, amount); if(amount = 500) { note500 = amount/500; amount -= note500 * 500; } if(amount = 100) { note100 = amount/100; amount -= note100 * 100; } if(amount = 50) { note50 = amount/50; amount -= note50 * 50; } if(amount = 20) { note20 = amount/20; amount -= note20 * 20; } if(amount = 10) { note10 = amount/10; amount -= note10 * 10; } if(amount = 5) { note5 = amount/5; amount -= note5 * 5; } if(amount = 2) { note2 = amount /2; amount -= note2 * 2; } if(amount = 1) { note1 = amount; } printf(Total number of notes = n); printf(500 = %dn, note500); printf(100 = %dn, note100); printf(50 = %dn, note50);
  • 51.
    Decision control instructions 45 printf(20= %dn, note20); printf(10 = %dn, note10); printf(5 = %dn, note5); printf(2 = %dn, note2); printf(1 = %dn, note1); } Sample program 5.6 Write a program to check given number is even or odd using switch case /** * C program to check Even or Odd number using switch case */ #include stdio.h main() { int num; /* * Reads a number from user */ printf(Enter any number to check even or odd: ); scanf(%d, num); switch(num % 2) { //If n%2 == 0 case 0: printf(Number is Even); break; //Else if n%2 != 0 case 1: printf(Number is Odd); break; } } 5.7  Programs for practice 1. WAP to find the roots of a quadratic equation by using if...else condition. 2. WAP to read six numbers and find the largest one by using ladder of if...else. 3. WAP to find the average of six subjects and display the results. 4. WAP to check whether the entered year is a leap year or not with all check points 5. WAP (a menu driven)to display the names of the days of a week. 6. WAP Read the values of a,b,c through keyboard. Add them and after addition check if it is in the range of 100 200 or not. Print separate message of each. 7. WAP to convert integer to character using if condition. 8. WAP to calculate the sum of the remainders obtained by dividing with modular division operations by 2 on 1 to 9 numbers.
  • 52.
    CHAPTER – 6 DECISIONMAKING AND LOOPING 6.1  The for() loop The for() loop can be used for executing a statement/statements a specific (or infinite) number of times. The general form of the for() loop is as follows: for(expr1; expr2; expr3) { code block; } expr1 is executed only once when the for() loop is executed for the first time. expr2 is evaluated every time before entry into the loop till the time it does not evaluate to false. expr3 is evaluated every time except for the first time. The for() loop is an entry-controlled loop. Different constructs of for loop (these syntax are correct syntax) • for( ;condition;) { Increment / decrement; } • for(i=0,j=0,k=100; i=200;i++,j++,k++) { } • for(;i10;i++ ) { } • for(;i10;i++ ); { } [N.B.: These programs have been executed using Dev-C++ Version 5.11] #includestdio.h main() {
  • 53.
    Decision making andlooping 47 /* printing the integers from 1 to 10 using a for() loop */ int i; for(i=1;i11;i++) { printf(ni = %d, i); } return 0; } 6.2  The while () loop: The general form of the while() loop is: while (expr) { code-block; } If the expr after while evaluates to true then the body of the while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The while() loop is an entry-controlled loop, which implies that if the expr evaluates to false right at the beginning then the body of the while loop will not be executed even once. #includestdio.h main() { /* printing the integers from 11 to 20 using a while() loop */ int j=11; while(j21)
  • 54.
    Computer Concepts andFundamentals of Programming 48 { printf(nj = %d, j); j++; } return 0; } 6.3  The do... while() loop The general form of the while() loop is: do { code-block; }while (expr); If the expr after while evaluates to true then the body of the do... while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do... while(); loop will be necessarily executed at least once. The do... while() loop is an exit-controlled loop. #includestdio.h main() { /* printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++;
  • 55.
    Decision making andlooping 49 }while(k=30); return 0; } 6.4  Difference between while and do while loop while do while It is entry controlled loop It is exit controlled loop The may not be executed if the condition is false to start with The loop will executed at least once while(condition) { Statement 1; Statement 2 ; Statement 3; } do { Statement 1; Statement 2 ; Statement 3; } while(condition); Sample program 6.1 Program to illustrate tribonacci series #includestdio.h int main() {int num,a=0,b=1,c=2,d=0,i; printf(nEnter the number:); scanf(%d,num); printf(%dt%dt%d,a,b,c); for(i=3;inum;i++) {
  • 56.
    Computer Concepts andFundamentals of Programming 50 d=a+b+c; printf(t%d ,d); a=b; b=c; c=d; } } Sample program 6.2 Tetranacci series #includestdio.h int main() {int num,a=0,b=1,c=2,d=3,e=0,i; printf(nEnter the number:); scanf(%d,num); printf(%dt%dt%d,a,b,c); for(i=3;inum;i++) { e=a+b+c+d; printf(t%d ,e); a=b; b=c; c=d; d=e; } } Sample program 6.3 Lucas series #includestdio.h main() {  int x,y,z,num;  printf(Enter the limit of Lucas number: );  scanf(%d,num);  x=2;  y=1;  while(num=x)  {    printf( %d,x);    z=x+y;    x=y;    y=z;  }
  • 57.
    Decision making andlooping 51 } Sample program 6.4 Palindrome number #includestdio.h void pal(); main() { pal(); } void pal() { int n,x,mod,rev=0; printf(nEnter No.); scanf(%d,n); x=n; while(n) { mod=n%10; rev=rev*10+mod; n=n/10; } if(rev==x) printf(n PAL n); else printf(n NOT PAL n); } Sample program 6.5 Special number #includestdio.h void sp(); main() { sp(); } void sp() { int n,x,mod,sum=0,f; printf(n Enter no.); scanf(%d,n); x=n; int i; while(n) { mod=n%10; f=1;
  • 58.
    Computer Concepts andFundamentals of Programming 52 for(i=1;i=mod;i++) f=f*i; sum=sum+f; n=n/10; } if(sum==x) printf(n SPL); else printf(n NOT SPL); } Sample program 6.6 Write a program to check whether the number is n- Narcissistic number #includestdio.h main() { long int cube,n,mod,sum=0,temp; printf(Enter the any number: ); scanf(%d,n); cube=n*n*n; temp=cube; digit=0; while(cube) { mod=cube%10; digit++; cube=cube/10; } cube=x; while(cube) { mod=cube%10; sum=sum+pow(mod,digit); cube=cube/10; } if(sum==n) printf(“The given number: = %d is a n- Narcissistic number”,sum); else printf(“The given number: = %d is a n- Narcissistic not number”,sum); } Sample program 6.7 Armstrong number is also n- Narcissistic page #includestdio.h main() { int mod,n,x,arm1=0; printf(enter the val of n);
  • 59.
    Decision making andlooping 53 scanf(%d,n); x=n; while(n) { mod=n%10; arm1=arm1+mod*mod*mod; n=n/10; } if(arm1==x) printf(nnyes armstrong hai!!!!!nn); else printf(nnyes armstrong nahi hai!!!!!nn); } Sample program 6.8 Write a program to check whether the number is Prime number or not #includestdio.h main() { int n, i = 3, count, c; printf(Enter the number of prime numbers requiredn); scanf(%d,n); if ( n = 1 ) { printf(First %d prime numbers are:n,n); printf(2n); } for ( count = 2 ; count = n ; ) { for ( c = 2 ; c = i - 1 ; c++ ) { if ( i%c == 0 ) break; } if ( c == i ) { printf(%dn,i); count++; } i++; } } Sample program 6.9 Write a program to check whether the entered number is a.Magic number or not //magic number 82=8+2=10=1+0=1
  • 60.
    Computer Concepts andFundamentals of Programming 54 #includestdio.h main() { int n,x,mod,rev=0; printf(nEnter the limitn); scanf(%d,n); TMI: for(x=n;n;n=n/10) {mod=n%10;rev+=mod;} if(rev=10) {n=rev;rev=0; goto TMI; } else if(rev==1) printf(Entered number is a magic no ); else printf(Entered number is not a magic no ); } Sample program 6.10 Write a program to print the following Pattern /* * * * * * * * * * * * * * * * */ #includestdio.h main() { int n,i,j,k,l; printf(nEnter the limitn); scanf(%d,n); // work for the rows for(i=1;i=n;i++) { for(k=1;k=10000000;k++); for(l=40;l=i;l--)// work for the spaces {printf( );} for(j=1;j=i;j++) {printf( *);} printf(n); } }
  • 61.
    Decision making andlooping 55 6.5  Programs for practice 1. WAP to find and print the sum of digits of a number entered by user. 2. WAP to find and print the greatest digit of a number entered by user. 3. WAP to find and print the smallest digit of a number entered by user. 4. WAP to find and print all even digits of a number entered by user. 5. WAP to Print the square root of each digit of any number. Consider each digit as perfect square. For example 494 the square roots to be printed should be 232. 6. WAP to enter two integer values through keyboard. Using while loop, perform the product of the two integers. In case product is zero, loop should be terminated otherwise loop will continue. 7. To enter integer number and find the largest and smallest digit of that number based on user choice. 8. To find and print the Fibonacci series till n where n is user defined. 9. To condense the number to a single digit. 10. To check whether the number entered by user is Arm-strong number or not. 11. To check whether the number entered by user is perfect number or not. 12. To check whether the number entered by user is magic number or not. 13. To check whether the number entered by user is palindrome number or not. 14. To check whether the number entered by user is special number or not. 15. To find and print the Factorial of a number entered by user. 16. Write a program in ‘C’ to generate the following output: (a). 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 (b). 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 (c). 5 4 3 2 1 5 4 3 2 5 4 3 5 4 (d). * ** ***
  • 62.
    Computer Concepts andFundamentals of Programming 56 **** ***** **** *** ** * (e). C CO COM COMP COMPU COMPUT COMPUTE (f). C COO COOMMM COOMMMPPPP COOMMMPPPPUUUUU COOMMMPPPPUUUUUTTTTTT COOMMMPPPPUUUUUTTTTTTEEEEEEE (g). C CCO CCCOOM CCCCOOOMMP CCCCCOOOOMMMPPU CCCCCCOOOOOMMMMPPPUUT CCCCCCCOOOOOOMMMMMPPPPUUUTTE (h). C CCOO CCCOOOMMM CCCCOOOOMMMMPPPP CCCCCOOOOOMMMMMPPPPPUUUUU CCCCCCOOOOOOMMMMMMPPPPPPUUUUUUTTTTTT CCCCCCCOOOOOOOMMMMMMMPPPPPPPUUUUUUUTTTTTTTEEEEEEE
  • 63.
    Decision making andlooping 57 (i). 1 121 12321 1234321 123454321 12345654321 1234567654321 (j). 9 989 98789 9876789 987656789 98765456789 9876543456789 987654323456789 98765432123456789 (k) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 (l). 1 23 456 78910 (m). ( )( )() ()() ()()( (n). 1
  • 64.
    Computer Concepts andFundamentals of Programming 58 232 34543 4567654 567898765 (o). 1 232 34543 4567654 567898765 67890109876 7890123210987 890123454321098
  • 65.
    CHAPTER – 7 ARRAYS 7.1 Arrays Supposewe want to obtain 10 integer values, perform mathematical or other operations on them and then print the results, then we might require ten integer variables: var1, var2, var3,... , var10, for instance. Several programming languages provide the concept of arrays which help in reducing the number of variables because of a common name and indices for referencing individual elements. Let us consider an example: #includestdio.h main() { int num[10]; int i; printf(nNow obtaining 10 integer values: n); for(i=0;i10;i++) { printf(Enter %dth integer: , i); scanf(%d, num[i]); } printf(nThe 10 integer values which you entered are as follows:); for(i=0;i10;i++) printf(nnum[%d] = %d, i, num[i]); return 0; }
  • 66.
    Computer Concepts andFundamentals of Programming 60 A sample interaction with the program might appear as follows: How arrays are stored in memory? The declaration int num[10]; indicates to the ‘C’ compiler that memory is to be reserved (continuous locations) for storing 10 integer values. The locations are individually identified as num[0], num[1], num[2],... , num[9]. If an integer requires 4 bytes for storage, and if the first integer is being stored in locations identified as 2358932, 2358933, 2358934, 2358935; then the second integer would be stored in the locations: 2358936, 2358937, 2358938 and 2358939. In the diagram below, the numbers on the right indicate the address of the individual array elements. num[0] 2358932 num[1] 2358936 num[2] 2358940 num[3] 2358944 num[4] 2358948 num[5] 2358952 num[6] 2358956 num[7] 2358960 num[8] 2358964 num[9] 2358968 A few important points pertaining to arrays: If an array is declared as:
  • 67.
    Arrays 61 int num[10]; (i) then the first element of the array will be referred to as num[0] and the last element of the array will be referred to as num[9]; (ii) If an array is declared as a global array [above main() ], then (a) It will be initialized with NULL values in case it is a char type array (b) It will be initialized with 0 (zero) in case it is a numeric array (iii) If an array is declared as a static array, then (a) It will be initialized with NULL values in case it is a char type array (b) It will be initialized with 0 (zero) in case it is a numeric array (iv) If a numeric type array is partially initialized at the place where it is declared, then the rest of the elements are automatically set to zero. (v) An array name is a pointer to itself. Thus num[0] and num would be the same. Two-dimensional arrays A declaration such as: int num[4][5]; creates an array of 4 rows and 5 columns and might be visualized as follows: Col 0 Col 1 Col 2 Col 3 Col 4 Row 0 Row 1 Row 2 Row 3 The individual elements might be accessed as follows: num[0][0] num[0][1] num[0][2] num[0][3] num[0][4] num[1][0] num[1][1] num[1][2] num[1][3] num[1][4] num[2][0] num[2][1] num[2][2] num[2][3] num[2][4] num[3][0] num[3][1] num[3][2] num[3][3] num[3][4] The program below demonstrates how to enter values into a two-dimensional array and then print the values. #includestdio.h #define ROWS 3 #define COLS 4 main() { int mat[ROWS][COLS]; int i, j; printf(nNow obtaining integers for %d X %d matrix:n, ROWS, COLS); for(i=0;iROWS;i++)
  • 68.
    Computer Concepts andFundamentals of Programming 62 { for(j=0;jCOLS;j++) { printf(Enter integer for %dth row and %dth column: ,i,j); scanf(%d, mat[i][j]); } } printf(nThe matrix is as follows:n); for(i=0;iROWS;i++) { for(j=0;jCOLS;j++) { printf(%8d, mat[i][j]); } printf(n); } printf(nThe addresses of the matrix elements are as follows:n); printf(nAddress (matrix element)n); for(i=0;iROWS;i++) { for(j=0;jCOLS;j++) { printf(%u (%d) , mat[i][j], mat[i][j]); } printf(n); } return 0; }
  • 69.
    Arrays 63 A sample outputis shown below: Sample program 7.1 Program to illustrate matrix multiplication of two matrices of same order Matrix multiplication #include stdio.h main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10]; printf(Enter the number of rows and columns of first matrixn); scanf(%d%d, m, n); printf(Enter the elements of first matrixn); for ( c = 0 ; c m ; c++ ) for ( d = 0 ; d n ; d++ ) scanf(%d, first[c][d]); printf(Enter the number of rows and columns of second matrixn); scanf(%d%d, p, q); if ( n != p ) printf(Matrices with entered orders can't be multiplied with each other.n); else { printf(Enter the elements of second matrixn); for ( c = 0 ; c p ; c++ )
  • 70.
    Computer Concepts andFundamentals of Programming 64 for ( d = 0 ; d q ; d++ ) scanf(%d, second[c][d]); for ( c = 0 ; c m ; c++ ) { for ( d = 0 ; d q ; d++ ) { for ( k = 0 ; k p ; k++ ) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf(Product of entered matrices:-n); for ( c = 0 ; c m ; c++ ) { for ( d = 0 ; d q ; d++ ) printf(%dt, multiply[c][d]); printf(n); } } } Sample program 7.2 Write a first category function program to read a two matrices A and B of order 9x9 and print the following. a)A+B and b)A-B #includestdio.h main() { int a[3][3],b[3][3],c[3][3],i,j; printf(Enter the First 3x3 Matrix: ); for(i=0;i3;i++) { for(j=0;j3;j++) scanf(%d,a[i][j]); } printf(Enter the Second 3x3 Matrix: ); for(i=0;i3;i++) { for(j=0;j3;j++) scanf(%d,b[i][j]); } printf(nThe Sum of Matrices is: ); for(i=0;i3;i++)
  • 71.
    Arrays 65 { printf(n); for(j=0;j3;j++) { c[i][j]=a[i][j]+b[i][j]; printf(%d ,c[i][j]); } } printf(nnThe Differenceof Matrices is: ); for(i=0;i3;i++) { printf(n); for(j=0;j3;j++) { c[i][j]=a[i][j]b[ i][j]; //2 mark printf(%d ,c[i][j]); } } } Sample program 7.3 Write a program that will put 8 queens on a Chessboard so that no queen can capture another. The size of the board is 8 x 8. One queen can capture another if it is standing in the same row (horizontal), or in the same column (vertical), or on the same diagonal as the other queen. #includestdio.h #includemath.h int a[30],count=0; int place(int pos) { int i; for(i=1;ipos;i++) { if((a[i]==a[pos])||((abs(a[i]a[pos])==abs(ipos)))) return 0; } return 1; } void print_sol(int n) { int i,j; count++; printf(nnSolution #%d:n,count);
  • 72.
    Computer Concepts andFundamentals of Programming 66 for(i=1;i=n;i++) { for(j=1;j=n;j++) { if(a[i]==j) printf(Qt); else printf(*t); } printf(n); } } void queen(int n) //1 mark { int k=1; a[k]=0; while(k!=0) { a[k]=a[k]+1; while((a[k]=n)!place(k)) //1 mark a[k]++; if(a[k]=n) //1 mark { if(k==n) print_sol(n); else { k++; a[k]=0; //1 mark } } else k; } } main() //1 mark { int i,n; printf(Enter the number of Queensn); scanf(%d,n);
  • 73.
    Arrays 67 queen(n); printf(nTotal solutions=%d,count); } Selection Sort InSelection Sort, the element at the zeroth position is compared with all the elements below it and an interchange performed as and when required (depending on whether the elements have to be arranged in ascending or descending order). Thereafter, the element at the first position is compared with all the elements below it and an interchange performed as and when required. Similarly, the elements at the second, third,... position are compared with all the elements below them and an interchange performed as and when required. The program below is an implementation of Selection Sort: #includestdio.h #define SIZE 10 main() { int array[SIZE]; int i, j, t; printf(nNow obtaining %d integers: n, SIZE); for(i=0;iSIZE;i++) { printf(Enter %dth integer: , i); scanf(%d, array[i]); } printf(nnBefore sorting:); for(i=0;iSIZE;i++) printf(n%d, array[i]); for(i=0;iSIZE-1;i++) { for(j=i+1;jSIZE;j++) { if(array[i]array[j]) { t=array[i]; array[i]=array[j]; array[j]=t; } } } printf(nnAfter sorting:); for(i=0;iSIZE;i++) printf(n%d, array[i]); return 0; }
  • 74.
    Computer Concepts andFundamentals of Programming 68 A sample output is shown below: Bubble sort In Bubble sort two successive elements are compared with each other and an interchange performed as and when required (depending on whether sorting is required in ascending or descending order). #includestdio.h #define SIZE 10 main() { int num[SIZE]; int i, j; int t; for(i=0;iSIZE;i++) {
  • 75.
    Arrays 69 printf(Enter %dthinteger: , i); scanf(%d, num[i]); } printf(nBefore sorting: ); for(i=0;iSIZE;i++) printf(n%d, num[i]); for(i=0;iSIZE-1;i++) { for(j=0;jSIZE-1;j++) { if(num[j]num[j+1]) { t = num[j]; num[j]=num[j+1]; num[j+1]=t; } } } printf(nAfter sorting: ); for(i=0;iSIZE;i++) printf(n%d, num[i]); return 0; }
  • 76.
    Computer Concepts andFundamentals of Programming 70 A sample output is shown below: Suppose the integers are entered in the following order: 9012 481 916 -9129 0 -873 3782 6712 -865 -2 After 0th run of the outer for(i...) loop 481 916 -9129
  • 77.
    Arrays 71 0 -873 3782 6712 -865 -2 9012 (The largestinteger in the array is at the bottom of the array) After 1th run of the outer for(i...) loop 481 -9129 0 -873 916 3782 -865 -2 6712 (The second highest integer in the array is in the second last position in the array) 9012 After 2th run of the outer for(i...) loop -9129 0 -873 481 916 -865 -2 3782 (The third highest integer in the array is in the third last position in the array) 6712 9012 After 3th run of the outer for(i...) loop -9129 -873 0 481 -865 -2 916
  • 78.
    Computer Concepts andFundamentals of Programming 72 3782 6712 9012 After 4th run of the outer for(i...) loop -9129 -873 0 -865 -2 481 916 3782 6712 9012 After 5th run of the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 6th run of the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 7th run of the outer for(i...) loop
  • 79.
    Arrays 73 -9129 -873 -865 -2 0 481 916 3782 6712 9012 After 8th runof the outer for(i...) loop -9129 -873 -865 -2 0 481 916 3782 6712 9012 After sorting: -9129 -873 -865 -2 0 481 916 3782 6712 9012 7.3  Programs for practice 1. To read 10 integers in an array and print all the values stored in the array. 2. To read 10 integers in an array and print all the values in reverse order stored in the array. 3. To read 10 integers in an array and Find the largest and smallest number from the array. 4. To read 10 fractions in an array and print alternate array elements.
  • 80.
    Computer Concepts andFundamentals of Programming 74 5. To print all even numbers stored in an array of size n, where n is user defined. 6. To accept an array of n elements, n user defined. Increase each value by 100 and print the new array. 7. To read 10 integers in an array. Find and print the largest and smallest number. 8. To accept an array of n numbers. Check value, if an even number is found, increase its value by 10, if odd decrease its value by 5and print both odd as well as new array. 9. To find and print all arm-strong numbers stored in an array of size n, where n is user defined. 10. To find and print all prime numbers stored in an array of size n, where n is user defined. 11. To find sum and average of any n values stored in an array. 12. To accept any n value,store them in the array and check the presence of any number entered by user in the array. If present, print the number, its first location and how many times it occurs in the array. 13. To read a number containing five digits. Perform square of each digit. 14. To read a number of any length. Perform the addition and subtraction on largest and smallest digits of it
  • 81.
    CHAPTER – 8 STRINGS Stringfunctions in ‘C’ In ‘C’ language a string is an array of characters terminated by ‘0’ (the null character). Some of the most commonly used string functions in ‘C’ are: strcat(): for concatenating two strings, strchr(): used for locating the first occurrence of the character (second argument) in the string (first argument), strcmp(): used for comparing two strings, strcpy(): used for copying the string contained as the second argument to the function, in the first argument to the function, strncpy(): used for avoiding buffer overflow when copying, strlen(): for computing the length of the string, strncat(): for appending n bytes, strlwr(): for converting a string to lowercase strupr(): for converting a string to uppercase The programs below demonstrate the use of a few string functions. #includestdio.h #includestring.h main() { char str[80]; printf(nEnter any string:); scanf(%[^n], str); printf(nstr = %s, str); printf(nstrlwr(str) = %s, strlwr(str)); printf(nstrupr(str) = %s, strupr(str)); printf(nstrlen(str) = %d, strlen(str)); return 0; }
  • 82.
    Computer Concepts andFundamentals of Programming 76 A sample output is shown below: #includestdio.h #includestring.h main() { char str1[] = Sky is the limit; char str2[] = Sky is Not the limit; char str3[80] = ; int result; printf(nnstr1 = %s, str1); printf(nnstr2 = %s, str2); printf(nnstr3 = %s, str3); strcpy(str3, str2); /*strcpy(destination, source)*/ printf(nnAfter copying str2 to str3, str3 = %s, str3); result = strcmp(str1, str2); /* strcmp(str1, str2) returns a value 0 if str1 alphabetically precedes str2, strcmp(str1, str2) returns a value 0 if str2 alphabetically precedes str1, strcmp(str1, str2) returns 0 if str1 is exactly the same as str2 */ printf(nnOn comparing str1 and str2, result = %d, result); return 0; }
  • 83.
    Strings 77 A sample outputis shown below: const char* strstr(const char *str1, const char *str2); The strstr() function returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not a subset of str1. A program illustrating the use of strstr() follows: #includestdio.h #includestring.h main() { char str1[] = Sky is the limit; char *result; printf(nnstr1 = %s, str1); result= strstr(str1, the); printf(nnresult = %s, result); result= strstr(str1, star); printf(nnresult = %s, result); return 0; } A sample output is shown below: str1 = Sky is the limit result = the limit result = (null)
  • 84.
    Computer Concepts andFundamentals of Programming 78 Sample program 8.1.Write a program to enter a paragraph and check number of alphabet, digit or special character /* C program to check alphabet, digit or special character */ #include stdio.h main() { char ch; /* Reads a character from user */ printf(Enter any character: ); scanf(%c, ch); /* Checks if it is an alphabet */ if((ch = 'a' ch = 'z') || (ch = 'A' ch = 'Z')) { printf(%c is ALPHABET.n, ch); } else if(ch = '0' ch = '9') { printf(%c is DIGIT.n, ch); } else { printf(%c is SPECIAL CHARACTER.n, ch); } } 8.3  Programs for practice 1. To accept a matrix of mXn order, n and m are user defined, from user. Calculate and print their row sum, column sum and diagonal sum. 2. To accept a matrix of mXn order, where n and m are user defined, from user. Print its transpose. 3. To accept any string from user and print its length. 4. To accept any string from user and print the string in reverse order. 5. To accept any string from user and insert any n characters from mth position from it. ( n and m should be less than length of the string ) 6. Read a set of 5 lines from user and print out the longest line.
  • 85.
    CHAPTER – 9 USERDEFINED FUNCTIONS 9.1 Definition Self-contained block of statement used to perform a particular task is called as function. The biggest advantage of function is code reusability. It divides the large program into segments because of this it becomes easy for a programmer to debug the program. Functions are sometimes called as methods. Functions are divided into following category i. Call by value and ii. Call by reference/ call by address: i. Call by value: In this category of the function the copy of variable value is being passed to the called function. This divided into following categories depending on the return type and parameter it carries. 1. Function with no return and parameter 2. Function with no return but carrying parameter 3. Function with return but carrying no parameter 4. Function with return as well as parameter ii. Call by reference / call by address: In this category of function the address of the variable is passed to the called function. Sometime address is also called as reference of variable. Program 9.1 Call by value: Function category 1: Write a program to perform addition of two numbers. #includestdio.h #includeconio.h void add(void); main() { add(); } void add() { int a,b,c; printf(enter the value of a,b); scanf(%d%d,a,b); c=a+b; printf(n addition is: =); printf(%d,c); }
  • 86.
    Computer Concepts andFundamentals of Programming 80 Note: Same program can be written by using fourth category 9.2 Call by value: Function category 4: Write a program to perform addition of two numbers. #include stdio.h #include conio.h int ganesh(int a,int b); main() { int x=4,y=8,z; z=ganesh(x,y); // here x and y are called as actual parameter ,ssss printf(%d,z); } int ganesh(a,b)// here a and b are called as formal parameters { int c=a+b; return c; } 9.3 Call by reference: Write a function program with call by reference to swap the values of two integer variable. In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters. #include stdio.h #include conio.h void swapnum ( int *var1, int *var2 ) { int tempnum ; tempnum = *var1 ; *var1 = *var2 ; *var2 = tempnum ; } int main( ) { int num1 = 35, num2 = 45 ; printf(Before swapping:); printf(nnum1 value is %d, num1); printf(nnum2 value is %d, num2); /*calling swap function*/ swapnum( num1, num2 ); printf(nAfter swapping:); printf(nnum1 value is %d, num1); printf(nnum2 value is %d, num2); getch(); return 0; }
  • 87.
    User defined function 81 9.3 Parameter and its types Parameters are nothing but the variables. Depending upon the location of the declaration they are classified as: 1. Local parameter: Any variable declared within the function body is a local parameter. Its scope lies up to that function body only where it is declared. 2. Global parameter: Any viable declared outside the function body is called as global parameter. 3. Actual parameter: The parameter which are being passed to the called function are calle as actual parameter. 4. Formal parameter: The parameter which are accepting the value of actual parameter are called as formal parameter. Following example best illustrates the functioning of the different parameters #include stdio.h #include conio.h int pi;// This is a global variable int ganesh(int a,int b); main() { int x=4,y=8,z;// x,y,z atre called as local parameter z=ganesh(x,y); // here x and y are called as actual parameter, ssss printf(%d,z); } int ganesh(a,b)// here a and b are called as formal parameters { int c=a+b; return c; } 9.4 Recursion Recursion: Function which is called within its own body is called as recursion. Program 8.3.1 //This program is for the recusive function //function called within its own body #includestdio.h main() { printf(nThis is a recursive function will run infinitenn); main(); } 9.3.2  Program Fibonacci series /*This program is showing the execution of recusive function*/ #includestdio.h
  • 88.
    Computer Concepts andFundamentals of Programming 82 #includeconio.h int Fibonacci(int); int main() { int n, i = 0, c; scanf(%d,n); printf(Fibonacci seriesn); for ( c = 1 ; c = n ; c++ ) { printf(%dn, Fibonacci(i)); i++; } return 0; } int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); } 9.4  Programs for practice WAP to check whether the given number is (Using all the four categories of function) 1. PRIME NUMBER 2. ARMSTRONG NUMBER 3. PALINDROME NUMBER 4. SPECIAL NUMBER 5. MAGIC NUMBER 6. PERFECT NUMBER 7. ADAM NUMBER
  • 89.
    CHAPTER – 10 POINTERS 10.1 Introduction Thecomputer’s memory is a collection of storage cell. Each cell or location has a unique address. The address is a consecutive numerical number often expressed in hexadecimal, which is difficult to use directly in the program. To ease the burden of programming using numerical address, the concept of variables is introduced. A variable is a named location that can store a value of a particular type. Instead of numerical addresses, names are attached to certain addresses. Also, data types such as int, double, char are related with the contents for the interpretation of data. Pointer is defined as address variable, a variable which holds the address of another variable. The following diagram illustrate the relationship between computers' memory address and content; and variable's name and value used by the programmers. Address Name Value /content 7000000 7000001 a 25 7000002 7000003 7000004 b 3 7000005 int a=25, b=3; 7000001 is the address of variable named “a” whose value is 25. If this address 7000001 is be stored in a variable, then the variable has to be a pointer or pointer variable. 10.2  Pointer declaration Like any other variable the pointer variable also should be declared before use. Syntax to declare a pointer data_type * pointer_var_name; Example int * p; The character asterisk (*) tells to the compiler that the identifier “p” should be declare as pointer. The data type tells to the compiler that pointer “p” will store memory address of an integer variable.
  • 90.
    Computer Concepts andFundamentals of Programming 84 10.3  Initializing Pointers When a pointer variable is declared, its content is not initialized. Like other variable pointers also need be initialized by assigning it a valid address. This is normally done via the address-of operator (). int a=25; int * p= a; /* pointer initialization */ p a 700045 600012 The pointer p is pointing to a 10.4  address () and dereference (*) operators C language provides two operators: address () and dereference (*) to manipulate data using pointers. The “address of ” is an operator which returns the address of a variable. for example int a=25; int * p= a; /* address of the a is assigned to pointer p */ printf(“%d”,a); /* output 25 */ The dereference operator or indirection operator * “ is an unary operator which operates on a pointer and returns the value at the location pointed to by that pointer. for example you can access the value of “a” using pointer use deference operator “*” printf(“%d”,*p); /* output 25 */ Sample Program 10.1 /* To print value and address of a variable */ #include stdio.h int main() { int a=25; /* int variable */ int *p; /* int pointer declaration */ p=a; /* initializing pointer */ printf(The address of a: %un,p); printf(Value a: %dn,*p); return 0; } Output: The address of a: 65524 Value a: 25 10.5  Pointer’s data type A pointer to any variable type is an address in memory -- which is an integer. But a pointer is NOT an integer always. A pointer should take the type of the value it points to. A pointer can only hold an address of the declared type; it cannot hold an address of a different type. For example 600012 25
  • 91.
    Pointers 85 int *p; p can hold the address of a int variable only. int a; p=a; 10.6  Benefits of pointers • Reduces the storage space • Execution using pointer is faster (i.e) Reduces the execution time of the program • Memory is dynamically allocated, allows us to resize the dynamically allocated memory block 10.7  Arrays and Pointers Array and pointers are closely related with each other. The name of an array without a subscript (index number) is a pointer constant. When the name is used without the subscript it references the address of element 0 of the array. int myarray[10]; /* Declare an array */ int *myptr; /* Declare a pointer (not initialized)*/ printf (“%dn”, myarray); /* print address of myarray[0] */ scanf (“%d”,myarray[0]); /* get value from keyboard and store in myarray[0] */ myptr = myarray[2]; /* Assign the address of the third element of myarray to myptr*/ printf(“%d”, *myptr); /* Print the value of what myptr is pointing to, i.e., the value of myarray[2] */ Note that the * in front of myptr de-references the pointer. That is, it says “use the value in the address that is pointed to.” Sample Program 10.2 /* Printing array values and addresses */ #include stdio.h int main ( ) { int k; float a[4] = {100, 200, 300, 400}; for (k=0; k4; k++) printf (%d %ld %ld %fn, k, a, a[k], a[k]); } 10.8  Pointer Arithmetic Arithmetic operations can be performed on pointers, but only limited operations can be performed on pointers. A pointer may be: • incremented ( ++ ) • decremented ( — ) • an integer may be added to a pointer ( + or += ) • an integer may be subtracted from a pointer ( – or -= ) • Pointer comparison ( , == , ) °° See which pointer points to the higher numbered array element °° Also, see if a pointer points to 0 • Pointers of the same type can be assigned to each other
  • 92.
    Computer Concepts andFundamentals of Programming 86 • Operations meaningless unless performed on an array • addition, multiplication and division operations on two pointer variables cannot be performed Data Type Initial Address Operation Address after Operations Required Bytes int 4000 ++ 4002 2 int 4000 -- 3998 2 char 4000 ++ 4001 1 char 4000 -- 3999 1 float 4000 ++ 4004 4 float 4000 -- 3996 4 long 4000 ++ 4004 4 long 4000 -- 3996 4 Expression Result Address + number Address Address - number Address Address - Address Number Address + Address Illegal Note: The value by which the address of the pointer variable will increment/ decrement is not fixed. It depends upon the data type of the pointer variable. Sample program 10.3 /*program to find sum of all elements stored in an array */ #includestdio.h #includeconio.h main () { int a [5] ={5,10,15,20,25}; int i, sum=0,*p; p = a; for (i = 0; i5; i++) { sum = sum+(*p); p++; } printf (the sum is % d, sum); getch (); } Output the sum is 75 Sample program 10.4 Palindrome string #includestdio.h #includestring.h int main()
  • 93.
    Pointers 87 { char str[30]; char *p,*t; printf(Enterany string: ); gets(str); for(p=str ; *p!=NULL ; p++); for(t=str, p-- ; p=t; ) { if(*p==*t) { p--; t++; } else break; } if(tp) printf(nString is palindrome); else printf(nString is Not palindrome); } Sample program 10.5 Write a program to compare two string using pointers.(Note: Do not use strcmp function) #includestdio.h int compare_string(char*, char*); main() { char first[100], second[100]; int result; printf(Enter first stringn); gets(first); printf(Enter second stringn); gets(second); result = compare_string(first, second); if ( result == 0 ) printf(Both strings are same.n); else printf(Entered strings are not equal.n); } int compare_string(char *first, char *second) { while(*first==*second)
  • 94.
    Computer Concepts andFundamentals of Programming 88 { if ( *first == '0' || *second == '0' ) break; first++; second++; //1 mark } if( *first == '0' *second == '0' ) return 0; else return 1; } 10.9 Programs for practice 1. WAP to accept an integer value and display it's value and address using pointer 2. WAP to check whether the given string is palindrome or not using pointer. 3. WAP to find the length of the string entered by user and display the string in reverse order.4
  • 95.
    CHAPTER – 11 STRUCTURESAND UNIONS 11.1 Introduction Structure is a user-defined datatype in C language. A structure is used to represent a group of data items of different datatype, whereas array is the group of similar data items i.e data items of same datatype. Structures are used to handle a group logically related data items. For example to keep track of student details, the following a set of attributes about a student may be used: name, roll_no, marks and gender. Structures can be used to organize these complex data in a useful way. Defining a Structure Unlike predefined datatypes, structures must be first defined for their format that may be later used for declaring the structure variables. The general format for defining a structure struct tag_name { datatype member 1; datatype member 2; ------------ datatype member m; }; In this definition, struct is a required keyword, tag is a name that identifies structures of this type. It should be terminated with a semicolon. Each member should be independently declared for its name and type. For example consider a student database consisting of name, roll_no, marks and gender, a structure can be defined as follows struct student { char name [30]; int roll_no; float marks; char gender; }; Student is a user-defined datatype and variables of this type can be declared and used in the program. Declaring a structure variable
  • 96.
    Computer Concepts andFundamentals of Programming 90 After defining a structure, we can declare variables of that type. The general format of declaring structure variable struct tag_name struct_variable; example struct student s1,s2,s3; this statement declares s1,s2 and s3 as structure variables of type student. Each one of these variable have four members name, roll_no, marks and gender. C language allows to combine both the structure definition and variables declaration in one statement as follows struct student { char name [30]; int roll_no; float marks; char gender; }s1,s2,s3; Structure initialization struct student s1 = {“John”,780123,67.5,’m’}; struct student s2 = {“Priya”,780122,85.5,’f’}; Note: the order of values enclosed in braces must match the order of members in the structure definition. It is allowed to initialize first few members and leave the remaining blank. The uninitialized members should be only at the end of the list. For example struct student s2 = {“Priya”,780122}; /* initializes name and roll_no leaving marks and gender blank */ Accessing members of the structure The members of a structure are usually processed individually. Therefore, we must be able to access the individual structure members. A structure member can be accessed by (.) period operator struct_variable.member_name. The (.) operator is a member of the highest precedence group, and its associativity is left-to-right. Sample Program 1 struct student { char name [30]; int roll_no; float marks; char gender; }; main() { struct student s1; printf(“ enter the name of the student “); scanf(“%s”, s1.name);
  • 97.
    Structures and unions 91 printf(“enter the roll_no of the student “); scanf(“%d”, s1.roll_no); printf(“ enter the gender of the student “); scanf(“%c”, s1.gender); s1.marks=75.5; /* the details of the student */ printf (“Name: %s”, s1.name); printf (“Roll no: %d”, s1.roll_no); printf (“ Gender: %c”, s1.gender); printf (“ Marks: %f”, s1.marks); } Arrays of structure If we have to maintain the details of more than one student then array of structures can be used. Array of structure may be declared as follows struct student s[50]; s is an array of 50 elements in which each element is of type struct student s[0].name /* refers to the name of the first student */ s[5].marks /* refers to the marks of the 6th student */ Sample Program 2 /* To read and print the details of 50 students and find if a student scored first class or not */ struct student { char name [30]; int roll_no; float marks; char gender; }; main() { struct student s[50]; int i; for(i=0;i50;i++) { printf(“ enter the name of the student “); scanf(“%s”, s[i].name); printf(“ enter the roll_no of the student “); scanf(“%d”, s[i].roll_no);
  • 98.
    Computer Concepts andFundamentals of Programming 92 printf(“ enter the gender of the student “); scanf(“%c”, s[i].gender); printf(“ enter the marks of the student “); scanf(“%f”, s[i].marks); } /* the details of the student */ for(i=0;i50;i++) { printf (“Name: %s”, s[i].name); printf (“Roll no: %d”, s[i].roll_no); printf (“ Gender: %c”, s[i].gender); if(s[i]=60) { printf (“First class”); } } } Structure within Structure (Nested Structure) A structure can be nested inside another structure. In other words, the members of a structure can be of any other type including structure. The general format for nested structures structure tagname_1 { member1; member2; member3; structure tagname_2 member4; ... membern; }; Example struct date { int day; int month; int year; }; struct student {
  • 99.
    Structures and unions 93 charname [30]; int roll_no; struct date dob; }; struct student s; The structure student has a member dob which itself is a structure with three members. The members in the inner structure can be referred as s.dob.day=25; s.dob.month=11; union A union is a user data type like structure that is used to handle different data types in a unit. Union follows the format of structure for definition of union, declaration of union variable and accessing of members union union_name { datatype member 1; datatype member 2; ------------ datatype member m; } [one or more union variables]; At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Otherwise you can later declare variable as follows union union_name var1,var2; To access any member of a union, the period operator (.) is to be used Example union subject { char name[50]; int subject_code; }; union subject s1 ={“computer science”, 2205}; /*union initialization */ union subject s2; /*declare union variable */ strcpy(s2.name,”mathematics”); /* access union member */ 11.3  Difference between structure and union The difference between structure and union is, union use less memory than structures. Each member of a structure is allotted separate memory space (ie) the size of structure in equal to the sum of size of all its members, whereas in case of union, size is equal to size of largest member. For example struct student { char name [30];
  • 100.
    Computer Concepts andFundamentals of Programming 94 int roll_no; float marks; char gender; } s1; The structure variable s1 requires 37 bytes ( 30 for name, 2 for roll_no, 4 for marks and 1 for gender). Each member get separate memory location, so all can be used at a time. union student { char name [30]; int roll_no; float marks; char gender; } s2; The union variable s2 requires only 30 bytes, ie the size of largest member. But only one member can contain a value or used at any given time. Another example union subject { char name[50]; int subject_code; }; The union above could be used to either store name or subject_code at a particular time. Presumably there are times when you would want one or the other, but not both. #includestdio.h #includeconio.h union subject { char name[50]; int subject_code; }; void main() { union subject s; clrscr(); printf(Enter subject Name: ); scanf(%s,s.name); printf(The subject Name: %sn,s.name); printf(Enter subject code: ); scanf(%d,s.subject_code); printf(The subject code: %d,s.subject_code); }
  • 101.
    Structures and unions 95 Output Entersubject Name: computer science The subject Name: computer science Enter subject code: 2205 The subject code: 2205 Appendix Opening a web browser via a ‘C’ program Is it possible to open a web page in a browser using a 'C' program? The program below provides an answer to the aforementioned question: Program listing one #includestdio.h main() { char url[25] = www.mail.yahoo.com; char launch[255]; system(clear); sprintf(launch, gnome-open %s, url); system(launch); return 0; } [NOTE: 1. The above code should be compiled on a Linux system. 2. Parallel methods for opening a web-browser are available for Windows/Mac OSs. For instance, on a Mac OS, system(“open http://url”); might be used.] An alternative method of opening a web page is given below: Program listing two #includestdio.h main() { char url[25] = www.iiml.ac.in; char launch[255]; system(clear); sprintf(launch, firefox %s, url); system(launch); return 0; } [Note: The code in Program listing two assumes that firefox is installed on the workstation and the appropriate PATH has been set.]
  • 102.
    Computer Concepts andFundamentals of Programming 96 The program below provides an illustration of another method of opening a web-browser via a 'C' program: Program listing three #includestdio.h #includeunistd.h main() { execl(/usr/bin/firefox, (char *)0); printf(execl() could not open the web-page); /* this line will be executed only if execl() above is not able to launch firefox*/ return 0; } The reader may interpret execl()as execute and leave. The execl() function replaces the current process by running the program specified as an argument to the execl()function. The process identifier (PID) of the new process will be the same as the PID of the old process (old process refers to the program in program listing three which is being compiled and executed and new process refers to firefox). The prototype of the execl()function is: int execl(const char *path, const char *arg1,...); execl() is a variadic function and the list of arguments to execl() should be terminated by a NULL pointer, therefore (char *)0 has been used to indicate the end of arguments to execl().
  • 103.
    Structures and unions 97 INDIANMARITIME UNIVERSITY (A Central University, Government of India) END SEMESTER EXAMINATION December 2017 Programme: B. Tech (Marine Engineering) Semester: II Subject Name: Computer Science Subject Code: UG11T2205/ UG11T1205 Date: 29.12.2017 Maximum Marks: 100 Time: 10AM – 1PM Pass Marks: 50 PART – A Marks: 10 X 3 = 30 (All Questions are compulsory) 1.  a) Differentiate between RAM and ROM Answer. RAM ROM Random Access Memory Read Only Memory Volatile memory: stores information as long as the computer is not switched off. Non-volatile memory: ROM retains information even when the computer is powered off. Types of RAM: SDRAM – Synchronous DRAM DDR – Double Data Rate SDRAM RDRAM – Rambus DRAM DIMM RIMM There are five basic types of ROM: ROM PROM EPROM EEPROM Flash memory b) What is the use of header files example any one Answer. A header file contains C declarations and macro functions. A few standard header files in C are: assert.h complex.h ctype.h Example: In order to pass variable number of arguments to a function the file stdarg.h should be included.
  • 104.
    Computer Concepts andFundamentals of Programming 98 header files in ‘C’ The preprocessing directive ‘#include’ can be written as #includestdio.h or #include”stdio.h” #includestdio.h searches for the file named stdio.h in the standard list of system directories. #include”stdio.h” searches for the file named stdio.h first in the directory containing the current file, thereafter in the quote directories and then in the standard list of system directories. Some of the header files used in ‘C’ are: assert.h complex.h ctype.h errno.h fenv.h limits.h locale.h math.h signal.h stdarg.h stdlib.h string.h time.h c) Explain ternary operator? Give example Answer.?: is known as ternary operator. The conditional operator (?:) takes three operands and has the following syntactic form: expr1 ? expr2: expr3; expr1 is always evaluated first and results in either true or false. If expr1 evaluates to true (1), expr2 is evaluated; otherwise expr3 is evaluated. Example: #includestdio.h main() { int isPremiumMember; float price; printf(nIs customer a Premium Member (Yes - 1, No - 0): ); scanf(%d, isPremiumMember);
  • 105.
    Structures and unions 99 price=isPremiumMember? 100: 120; /*If the customer is a Premium Member then price = 100, if the customer is not a Premium Member then price = 120*/ printf(nPrice = %f, price); return 0; }
  • 106.
    Computer Concepts andFundamentals of Programming 100 d) find the output #includestdio.h int main() { int i=3; i=i++; printf(%dn,i); return 0; } Answer. Output is: 3 e) Explain do while loop with example Answer. The do . . . while() loop The general form of the while() loop is: do { code-block; }while (expr); If the expr after while evaluates to true then the body of the do . . . while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do . . . while(); loop will be necessarily executed at least once. The do . . . while() loop is an exit-controlled loop.
  • 107.
    Structures and unions 101 #includestdio.h main() { /*printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++; }while(k=30); return 0; } NOTE: This section demystifies the fact that although two different nested loops are executed exactly the same number of times, even then the execution times are likely to be different. Which code segment (1 or 2) will execute faster? #includestdio.h main() { int i, j; system(clear); for(i=0;i10;i++) { for(j=0;j100;j++) code segment 1 { /* some code */ } }
  • 108.
    Computer Concepts andFundamentals of Programming 102 for(i=0;i100;i++) { for(j=0;j10;j++) code segment 2 { /* some code */ } } return 0; } Obviously /* some code */ will be executed equal number of times in both the code segments i.e. code segment 1 as well as code segment 2. Does that imply that the time taken for execution of the two code segments will be the same assuming that /* some code */ is exactly the same in both the code segments. The answer is that code segment 1 and code segment 2 will require different time periods for execution. A deeper examination proves the assertion: (i). In code segment 1, the initialization i = 0; j = 0; is carried out 1 + 10 = 11 times, whereas, in code segment 2, the initialization i = 0; j = 0 is carried out 1 + 100 = 101 times. (ii). In code segment 1, the comparison i 10; j 100; is carried out 11 + 101 x 10 i.e. 1021 times, whereas, in code segment 2 the comparison i 100; j 10; is carried out 101 + 100 x 11 i.e. 1201 times. (iii). In code segment 1, the increments i++; j++; are carried out 10 + 100 x 10 i.e. 1010 times, whereas, in code segment 2 the increments i++; j++; are carried out 100 + 100 x 10 i.e. 1100 times. The code produced below uses four counters ctr1, ctr2, ctr3 and ctr4 which will help in understanding the aforementioned explanation: #includestdio.h main() { int i, j; int ctr1=0, ctr2=0, ctr3=0, ctr4=0; system(clear); for(i=0;++ctr1 i10;i++,++ctr2) { for(j=0;++ctr1 j100;j++,++ctr2) { /* some code */ } } for(i=0;++ctr3 i 100;i++,++ctr4) { for(j=0;++ctr3 j 10;j++,++ctr4)
  • 109.
    Structures and unions 103 { /*some code */ } } printf(nctr1 = %d, ctr2 = %d, ctr1, ctr2); printf(nctr3 = %d, ctr4 = %d, ctr3, ctr4); return 0; } A sample output of the above program is given below: ctr1 = 1021, ctr2 = 1010 ctr3 = 1201, ctr4 = 1100 The code presented below may be used for determining the exact execution time of the two code segments: #includestdio.h #includetime.h main() { int i, j; clock_t start = clock(); system(clear); for(i=0;i10;i++) { for(j=0;j100;j++) { /* some code */ } } printf(nTime required for executing segment 1 = %lf, ((double)clock() - start)/CLOCKS_PER_SEC); start = clock(); for(i=0;i100;i++) { for(j=0;j10;j++) { /* some code */ } }
  • 110.
    Computer Concepts andFundamentals of Programming 104 printf(nTime required for executing segment 2 = %lf, ((double)clock() - start)/CLOCKS_PER_SEC); return 0; } It is also important to bear in mind that the above is a mathematical evaluation of the two code segments. On using the concept of locality of reference (or principle of locality) the evaluation will be different. There are four special cases of locality of reference: temporal, spatial, equidistant and branch. f) Describe the difference between structure and union. Answer. A structure in ‘C’ language is a collection of related elements, possibly of the same or different types, identified by a name. Each element in the structure is known as a field. A union in ‘C’ language is a construct that allows memory to be shared by different types of data. In a union, each piece of data starts at the same memory location and partly or wholly occupies the same memory. #includestdio.h struct example1 { char ch; int i; float f; double d; }; union example2 { char ch; int i; float f; double d; };
  • 111.
    Structures and unions 105 main() { printf(nsizeof(example1)= %d, sizeof(example1)); printf(nsizeof(example2) = %d, sizeof(example2)); return 0; } OUTPUT: g) Explain Flowchart with one example. Answer. A Flowchart is a diagrammatic representation of an algorithm, workflow or process. A structured method for documenting process flow was introduced by Frank and Lillian Gilbreth.
  • 112.
    Computer Concepts andFundamentals of Programming 106 Example: Flowchart for finding the GCD of two integers: h) Explain scanf statement and printf statement with example. scanf(): A function for accepting input; printf(): A function for displaying output;. Obtaining an integer as input from the user:
  • 113.
    Structures and unions 107 #includestdio.h main() { intnum; printf(Enter an integer: ); scanf(%d, num); printf(nThe integer you entered is: %d, num); return 0; } A sample output is shown below: Enter an integer: 786 The integer you entered is: 786 i) Define Function and its advantages. Answer. A function in ‘C’ is an independent module which can be invoked for performing a particular task. When a function is called, then the control is transferred from the calling function to the called function and once the execution of the called function is over, the control returns to the calling function. [The programs hereafter in this section have been executed using Dev-C++ Version 5.11] #includestdio.h float sumfunc(float x, float y); main() { float num1, num2, sum; printf(nEnter first number: ); scanf(%f, num1); printf(nEnter second number: ); scanf(%f, num2); sum = sumfunc(num1, num2); function invocation or function call printf(nSum of %f and %f = %f, num1, num2, sum); return 0; } function declaration or function prototyping
  • 114.
    Computer Concepts andFundamentals of Programming 108 float sumfunc(float x, float y) function header { float temp; temp = x + y; function body return temp; } OUTPUT: The function declaration: float sumfunc(float x, float y); contains three parts, namely, (i). type of return value from the function, (ii). name of the function, (iii). number and type of parameters being passed into the function. type of return value function name number and types of parameters being passed into the function float sumfunc(float x, float y); Advantages: (i) Programs can be divided into smaller, manageable segments. (ii) Functions help in reusing code which might be required more than once in a program. (iii) Functions can be used for protecting data. j) What is the Byte size of ‘char’ and ‘float’ in C. Answer. [The size of ‘char’ and ‘float’ is machine dependent and compiler dependent.] function definition
  • 115.
    Structures and unions 109 #includestdio.h main() { printf(nsizeof(char)= %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(long) = %d, sizeof(long)); printf(nsizeof(long double) = %d, sizeof(long double)); return 0; } Sample output is shown below: PART – B Marks: 5 X 14 = 70 (Answer any 5 of the following) 2. a) Write a C program to find the factorial of a number where number will be taken as fly (runtime) (7 marks) Answer. [N.B.: The phrase ‘on the fly’ implies something that is being changed while the process that is being affected by the change is being carried out/executed. Switching computer parts on the fly implies replacing parts of the computer while the computer is running.]
  • 116.
    Computer Concepts andFundamentals of Programming 110 #includestdio.h main() { int i, n; long int f=1; printf(nEnter integer whose factorial you want: ); scanf(%d, n); for(i=n;i1;i--) f=f*i; printf(nFactorial of %d = %ld, n, f); return 0; } Sample output is shown below: b) Write a C program to check whether a year is leap year or not year will be taken as fly (runtime). (7 marks) Answer. Every year that is exactly divisible by 4 is a leap year. But when a year is exactly divisible by 100, then it is considered as a leap year when it is exactly divisible by 400 also. If a year is exactly divisible by 1000, then it will be considered as a leap year only if it is not exactly divisible by 4000.
  • 117.
    Structures and unions 111 #includestdio.h intisleap(int y) { if((y%1000)==0) { if((y%4000)!=0) return 1; else return 0; } else if((y%100)==0) { if((y%400)==0) return 1; else return 0; } else { if((y%4)==0) return 1; else return 0; } } main() { int year; int result; printf(Enter the year for checking: ); scanf(%d, year); result=isleap(year); if(result) /*if(result) is the same as writing if(result!=0) */ printf(n%d is a leap year, year); else printf(n%d is not a leap year, year); return 0; }
  • 118.
    Computer Concepts andFundamentals of Programming 112 3 b) Explain any three services provided by the internet? (7 marks) Answer. (i). World Wide Web: The World Wide Web is the part of Internet accessible to users. (ii). Electronic Mail
  • 119.
    Structures and unions 113 (iii).E-Commerce (iv). File Transfer Protocol: for transferring large files between computers connected via Internet. (v). IRC: Internet Relay Chat (vi). Telnet (vii). Web-Hosting. 4. a) Explain Switch Case with Example (10 marks) switch...case construct helps control conditional branching operations. The general format of the switch construct is: switch(expression) { case constant-expression1: statement(s); case constant-expression2: statement(s); default: statement; } The expression in switch(expression) should evaluate to an integral value. The control passes to the statement whose case constant- expression matches the value of the switch(expression). A few points have to be borne in mind (i) no two case constants within the same switch should have the same value, (ii) the break statement can be used to terminate the processing of a particular case and to branch to the end of the switch construct and without the break statement the next case(s) would also be executed, (iii) the default statement need not be placed at the end and there can be at the most one default statement. The program below explores an interesting fact related to switch...case Program listing #includestdio.h main() { int x = 9; system(clear); switch(x) { int y=9; case 8: printf(nx=%d,x); break; case 7: printf(nx=%d,x); break; default: printf(nDefault being executed: x=%d,x); printf(ny=%d,y); }
  • 120.
    Computer Concepts andFundamentals of Programming 114 return 0; } A sample output of the program is: Default being executed: x=9 y=9360080 The most intriguing point is that although y is initialised with the value 9 even the the value of y in the output is an unpredictable value. Why? It is for the simple reason that although declarations can appear at the head of compound statement forming the switch construct, the initializations included in the declarations are not performed. b) Explain i) Multiuser Operating system ii) Multithreading operating system (4 marks) Answer. A Multiuser Operating System allows multiple users to access a computer system concurrently. For example, Windows XP. The major functions of an Operating System (OS) are i) resource management, ii) data management, iii) job management, iv) acting as a user interface. A thread is a basic unit of CPU utilization. Multi threading implies that a single process can have multiple code segments running concurrently. In multithreading there will be parent processes and child processes. 5. a) Explain Generations of Computer (7 marks) First Generation Examples are UNIVAC and ENIAC 1940 – 1956 (approx.) Used vacuum tubes for circuitry and magnetic drums for memory. Relied on Machine Language. Input was based on punched cards and paper tapes. Very expensive to operate. Used great deal of electricity. Required large storage space. Second Generation 1956 – 1963 (approx.) Vacuum tubes were replaced by transistors. Second generation computers relied on assembly or symbolic languages. Smaller, faster, cheaper and more energy efficient than the first generation computers. Third Generation 1964 – 1971 (approx.) Used Integrated Circuits. Input was given by keyboard and output was displayed on monitors. Fourth Generation 1971 – present (approx.) Used microprocessors. Fourth Generation computers were accompanied with developments in the Internet, GUIs, mouse device and other handheld devices. Fifth Generation Present – beyond (approx.) Accompanied with development in Artificial Intelligence, parallel processing, quantum computation, nanotechnology. Fourth Generation (VLSI) 4-bit microcomputer Intel 4004, Intel 4040 8-bit microcomputer Intel 8008, Intel 8080, Motorola 6800, Motorola 6809, MOSTechnology 6502, Zilog Z80 16-bit microcomputer Intel 8008, Zilog Z8000, WDC 65816/65802 32-bit microcomputer Intel 80386, Pentium, Motorola 68000, ARM 64-bit microcomputer Alpha, MIPS, PA-RISC, PowerPC, SPARC, x86-64, ARMv8-A Theoretical/Experimental Optical computer, Quantum computer, Spintronics-based computer
  • 121.
    Structures and unions 115 b)Write a Program in C to find the Transpose of a Matrix (7 marks) #includestdio.h main() { int nrows, ncols; /*nrows is for number of rows and ncols is for number of columns */ printf(nNumber of rows in the matrix: ); scanf(%d, nrows); printf(nNumber of cols in the matrix: ); scanf(%d, ncols); int mat[nrows][ncols]; int tranmat[ncols][nrows]; /*tranmat[][] is for holding the transpose */ int i, j; printf(nNow obtaining integers for the %d by %d matrixn, nrows, ncols); for(i=0;inrows;i++) { for(j=0;jncols;j++) { printf(Enter integer for %d row and %d col: ,i,j); scanf(%d, mat[i][j]); } } for(i=0;inrows;i++) { for(j=0;jncols;j++) { tranmat[j][i] = mat[i][j]; } } printf(nOriginal matrix:n); for(i=0;inrows;i++) { for(j=0;jncols;j++) { printf(%7d, mat[i][j]); } printf(n); } printf(nTranspose matrix:n); for(i=0;incols;i++) { for(j=0;jnrows;j++)
  • 122.
    Computer Concepts andFundamentals of Programming 116 { printf(%7d, tranmat[i][j]); } printf(n); } return 0; } A sample output is shown below: 6. a) Explain i) Call by Value ii) Call be reference with example. (10 marks) /* Call by value */ #includestdio.h void swap(int a, int b); main()
  • 123.
    Structures and unions 117 { intvar1, .var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } OUTPUT: /* Call by reference */ #includestdio.h void swap(int *a, int *b);
  • 124.
    Computer Concepts andFundamentals of Programming 118 main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } OUTPUT: In pass by value, the values are simply passed from the calling function to the called function. Any change in values in the called function will not be reflected in the calling function. In pass by reference any change in values in the called function will also be reflected in the calling function.
  • 125.
    Structures and unions 119 [ImportantNote: There is no pass by reference in ‘C’. is also known as referencing operator in C++.] b) Explain gets() and puts(). (4 marks) Answer. The gets() function in ‘C’ reads a line from the input stream and terminates it by ‘0’. The puts() function is used for displaying a string on the standard output. The puts() function automatically inserts a newline character at the end of each string it displays. #includestdio.h main() { char str[80]; printf(nEnter any string: ); gets(str); puts(nThe string you entered is: ); puts(str); return 0; } OUTPUT:
  • 126.
    Computer Concepts andFundamentals of Programming 120 7. a) Explain the Types of Operators in C Answer. Arithmetic operators + Addition – Subtraction * Multiplication / Division % Modulus Increment and decrement operators ++ Increment by 1 Example a++; -- Decrement by 1 Example b--; Relational operators == Equality operator != Not equal to Less than Greater than = Less than or equal to = Greater than or equal to Logical operators And || Or ! Not It performs the logical negation of an expression Bitwise operators left shift operator right shift operator ~ One’s complement operator Bitwise AND operator | Bitwise OR operator ^ Bitwise XOR operator Assignment operator Operator= Performs the operation and then assigns Example: a += b; Would expand to a = a + b; Conditional operator ?: ternary operator expr1 ? expr2: expr3; expr1 is always evaluated first and results in either true or false. If expr1 evaluates to true (1), expr2 is evaluated; otherwise expr3 is evaluated Special operators sizeof() int a, b; b = sizeof(a); sizeof(a); returns the amount of memory in bytes required to hold a ‘address of’ operator * ‘value at address’ operator. The * (asterisk) is also known as the indirection operator.
  • 127.
    Structures and unions 121 8.Write a C program to store information (name, roll and marks) of Student using Structure data where information will be taken as fly (runtime) (10 marks) #includestdio.h struct student_data { char name[40]; char rollno[20]; int marks_sub_1; int marks_sub_2; int marks_sub_3; }; main() { struct student_data svar1; printf(nEnter name of student: ); scanf(%[^n], svar1.name); fflush(stdin); printf(nEnter roll number of student: ); scanf(%[^n], svar1.rollno); printf(nEnter subject1 marks: ); scanf(%d, svar1.marks_sub_1); printf(nEnter subject2 marks: ); scanf(%d, svar1.marks_sub_2); printf(nEnter subject3 marks: ); scanf(%d, svar1.marks_sub_3); printf(nName of student: %s, svar1.name); printf(nRoll number of student: %s, svar1.rollno); printf(nMarks in subject1: %d, svar1.marks_sub_1); printf(nMarks in subject2: %d, svar1.marks_sub_2); printf(nMarks in subject3: %d, svar1.marks_sub_3); return 0; }
  • 128.
    Computer Concepts andFundamentals of Programming 122 A sample interaction with the program is shown below: ***
  • 129.
    Structures and unions 123 INDIANMARITIME UNIVERSITY (Central University, Government of India) May/June 2016 End Semester Examinations B.Tech. (Marine Engineering) Second Semester – Computer Science – (UG11 T1205/T2205) Date: 17.06.2016 Maximum Marks: 100 Time: 3 Hrs Pass Marks: 50 PART – A Marks: 10 X 3 = 30 Compulsory Question 1) a) Can a calculator be considered as a computer? Answer. Calculator Computer Definition An electronic device used for mathematical calculations and has a small keyboard and display screen that shows the results. An electronic device which is capable of receiving information and performing a sequence of operations according to the instructions given (program). Development Wilhelm Schickard (according to two letters written by Schickard to Johannes Kepler in 1623 and 1624) invented the calculator. Blaise Pascal also developed a calculator. Gottfried Leibniz spent forty years designing a four-operation mechanical calculator. The Antikythera mechanism is believed to be the world’s first analog “computer” according to Derek J. de Solla Price. It was designed for calculating astronomical positions. Charles Babbage who is considered the “father of computer” developed the difference engine and thereafter the Analytical Engine. The principle of the modern computer was proposed by Alan Turing in the paper On Computable Numbers (1936). [N.B.: According to the Oxford English Dictionary, the first known use of the word “computer” was in 1613 in a book bearing the name The Yong Mans Gleanings authored by Richard Braithwait.] A programmable calculator can be considered as a computer. The idea of a universal computational device was described by Alan Turing in 1937. Alan Turing proposed that all computations could be performed by a special kind of a machine, now known as a Turing machine. Around 1944 – 45, John von Neumann proposed that along with the data, the programs should also be stored in the memory of a computer. b) Choose the correct one (i) A header file is: (A) A file that contains standard library functions
  • 130.
    Computer Concepts andFundamentals of Programming 124 (B) A file contains definitions and macros (C) A file that contains user defined functions (D) A file that is present in current working directory Answer. (A) A header file in ‘C’ is a file that contains prototype statements and other declarations. It is placed in a library for shared use. (ii) A character variable can at a time store (A) 1 character (B) 8 character (C) 254 characters (D) None of the above Answer. (A) The C standard provides two character types: char and wchar_t. The size of char in ‘C’ is machine dependent. Normally it is one byte or eight bits. [Note: The programs of this section have been executed on Dev C++ Version 5.11] c) Write a C program for adding two numbers. #includestdio.h main() { double num1, num2, result; printf(nEnter first number: ); scanf(%lf, num1); printf(nEnter second number: ); scanf(%lf, num2); result = num1 + num2; printf(n%lf + %lf = %lf, num1,num2, result); return 0; }
  • 131.
    Structures and unions 125 Ashorter method: #includestdio.h main() { double num1, num2; printf(nEnter two numbers: ); scanf(%lf %lf, num1, num2); printf(n%lf + %lf = %lf, num1,num2, num1 + num2); return 0; } d) Differentiate between data and information. Answer. Data refers to facts and figures. Data are unstructured facts and figures. Information is data that is contextualised, categorized, calculated and condensed. Information is data with relevance and purpose. e) What do you understand by secondary memory Answer. Auxiliary storage is also known as secondary storage. The programs and data are stored permanently in the secondary storage. The programs and data remain in the secondary storage, even when the computer is switched off. Auxiliary storage is used for both input and output. Secondary memory includes all permanent or persistent storage devices, such as flash drives, hard disk drives, magnetic tapes, ROM. Secondary memory is slower than primary memory. [N.B.: Primary storage is also known as main memory. The programs and data are stored temporarily in the main memory during processing. The data in primary storage are erased when the computer is switched off (or in case of logging off from a time- sharing computer). ]
  • 132.
    Computer Concepts andFundamentals of Programming 126 f) How is an array represented in memory? Answer. An array is a collection of elements of the same data type. The name of an array refers to the first byte of the array. The index represents an offset from the beginning of the array to the element being referenced. ‘C’ calculates the address of any element of the array using the formula given below: element address = array base address + (sizeof(element) * index) int num[5]; num[0] num[1] num[2] num[3] num[4] g) (i) What do you mean by Nested structure? Answer. #includestdio.h struct date_of_birth { int dd; int mm; int yy; }; struct personal_details { char name[40]; char addr1[80]; char addr2[80]; struct date_of_birth dob; }; main() { struct personal_details person1; printf(nEnter name: ); scanf(%[^n], person1.name); fflush(stdin); printf(nEnter first line of address: ); scanf(%[^n], person1.addr1); fflush(stdin); printf(nEnter second line of address: ); scanf(%[^n], person1.addr2); fflush(stdin); printf(nEnter date of birth: dd mm yyyy: ); scanf(%d %d %d, person1.dob.dd, person1.dob.mm, person1.dob.yy); printf(nName = %s, person1.name); printf(nFirst line of address = %s, person1.addr1);
  • 133.
    Structures and unions 127 printf(nSecondline of address = %s, person1.addr2); printf(nDate of birth = %d/%d/%d, person1.dob.dd, person1.dob.mm, person1.dob.yy); return 0; } (ii) How many bits does a char type data has? Answer. Most of the personal computers use 1 byte to store the char datatype. A byte has 8 bits. [The unit symbol for byte is B and the unit symbol for bit is b. The term byte was coined by Werner Buchholz. The term “qubit” was coined by Benjamin Schumacher. 1 Kilobyte = 1024 bytes 1 Megabyte = 1024 Kilobytes 1 Gigabyte = 1024 Megabytes 1 Terabyte = 1024 Gigabytes 1 Petabyte = 1024 Terabytes 1 Exabyte = 1024 Petabytes 1 Zettabyte = 1024 Exabytes 1 Yottabyte = 1024 Zettabytes] h) Describe the similarities and dissimilarities between algorithm and flowchart. Answer. An algorithm is a logical step-by-step method for solving a problem. An algorithm details the procedure for solving a problem. Algorithm includes calculations, reasoning, and data processing. A flowchart is a pictorial depiction (using different shapes) of the logic used in solving a problem. A flowchart depicts the logic flow of a program. In other words, a flowchart depicts the design of an algorithm. A flowchart helps in pictorial thinking and visualization. A flowchart shows the order and sequence of the actions to be performed for solving a problem.
  • 134.
    Computer Concepts andFundamentals of Programming 128 A few of the symbols used in a flowchart are depicted below: Process Alternate Process Decision Input/Output statement Predefined process (Module Call) Internal storage Document Multidocument Terminator Preparation Manual Input
  • 135.
    Structures and unions 129 ManualOperation Connector Off-page Connector Card Punched Tape Summing Junction Or Collate Sort Extract Merge Stored Data
  • 136.
    Computer Concepts andFundamentals of Programming 130 Delay Sequential Access Storage Magnetic Disk Direct Access Storage Display Flow Line An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition, all algorithms must satisfy the following criteria: 1. Input. Zero or more quantities are externally supplied. 2. Output. At least one quantity is produced. 3. Definiteness. Each instruction is clear and unambiguous. 4. Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps. 5. Effectiveness. Every instruction must be very basic so that it can be carried out, in principle, by a person using only pencil and paper. It is not enough that each operation be definite as in criterion 3; it also must be feasible. (Source for definition of algorithm: Ellis Horowitz, Sartaj Sahni, Sanguthevar Rajasekaran) [N.B.: Algorithmics is a term coined by Brassard and Bratley. Algorithmics is the systematic study of the fundamental techniques used to design and analyse efficient algorithms.] i) List out the various application of computer? Answer. Computers are used in Engineering Design, Defence, Health care, Education, Businesses, Weather forecasting, simulation, etc. j) List the advantage of Pseudo-code? Answer. Pseudocode depicts the logic of solving a problem in simple English and mathematics. It is a stepwise description of the logic used for solving a problem. A pseudocode uses structural conventions of a normal computer programming language. A pseudocode is normally to be read and understood by human beings rather than machines. The word pseudo means false and code means programs.
  • 137.
    Structures and unions 131 PART-B(14 X 5 = 70 Marks) Answer and Five Questions 2 a) Write a C program for printing Fibonacci series, taking how many numbers to be print as an input. Answer. The first few terms of the Fibonacci series are: 0, 1, 1, 2, 3, 5, 8, 13, 21, . . . Except for the first two terms, each term is the sum of the preceding two terms. #includestdio.h main() { int f1=0, f2=1, f3; int num, ctr=2; printf(nHow many terms of the Fibonacci series: ); scanf(%d, num); if(num==0) printf(nNo terms to be printed); else if(num==1) printf(n%d,f1); else if(num==2) printf(n%d %d ,f1,f2); else { printf(n%d %d ,f1,f2); while(ctrnum) { f3=f1+f2; printf(%d ,f3); f1=f2; f2=f3; ctr++; } } return 0; }
  • 138.
    Computer Concepts andFundamentals of Programming 132 Sample output is produced below: b) Write a C program for checking whether a number is a prime number or not? Answer. #includestdio.h main() { int num; int no_of_factors=0; int i; /* a prime number has exactly two factors 1 and itself */ printf(nEnter number to be checked: ); scanf(%d, num); for(i=1;i=num;i++) { if((num%i)==0) no_of_factors++; } if(no_of_factors==2) printf(n%d is a prime number, num); else { printf(n%d is not a prime number, num); printf(nIt is having %d factors, no_of_factors); } }
  • 139.
    Structures and unions 133 [407is divisible by 1, 11, 37, and 407] c) Differentiate between do-while and while loop with a suitable example. (7+4+3) Answer. The do . . . while() loop The general form of the while() loop is: do
  • 140.
    Computer Concepts andFundamentals of Programming 134 { code-block; }while (expr); If the expr after while evaluates to true then the body of the do . . . while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The body of the do . . . while(); loop will be necessarily executed at least once. The do . . . while() loop is an exit-controlled loop. #includestdio.h main() { /* printing the integers from 21 to 30 using a do...while() loop */ int k=21; do { printf(nk = %d, k); k++; }while(k=30); return 0; }
  • 141.
    Structures and unions 135 Thewhile() loop The general form of the while() loop is: while (expr) { code-block; } If the expr after while evaluates to true then the body of the while() loop will be executed, otherwise control is transferred to the statement following the while() loop body. The while() loop is an entry-controlled loop, which implies that if the expr evaluates to false right at the beginning then the body of the while loop will not be executed even once. #includestdio.h main() { /* printing the integers from 11 to 20 using a while() loop */ int j=11; while(j21) { printf(nj = %d, j); j++; } return 0; }
  • 142.
    Computer Concepts andFundamentals of Programming 136 3) a) How application software differs from system software? Relationship between System and Application Software Example of System Software: Operating System. Examples of Application Software: word processors, spreadsheets, database management systems. System software provides a platform to application software. b) Differentiate between a MAN and a WAN. (7 + 7) Answer. A LAN (Local Area Network) is usually privately owned and links the devices (Personal Computers, printers, audio and video peripherals) in a single office, building or campus. As at the time of writing this book, the size of LAN is limited to a few kilometers. LANs are designed so that resources (hardware/software) can be shared between personal computers/workstations. LANs can incorporate the concept of a server and clients. A WAN (Wide Area Network) provides long-distance transmission of data, images, etc. over large geographic areas spanning continents or countries.
  • 143.
    Structures and unions 137 AMAN (Metropolitan Area Network) is a network with a size between a LAN and a WAN. Basis of comparison LAN MAN WAN Expansion Local Area Network Metropolitan Area Network Wide Area Network Geographical Area Small. For example School, College, Hospital, Office Larger region such as a city or a town Countries or even continents Ownership of network Usually private Private or public Private or public Devices used WiFi, Ethernet cables, Hub, Switch, Router Modem and Wire cable Optic fibres, Microwave, Satellites [Note: VLAN is for Virtual Local Area Network] 4) a) Define an algorithm. How is it useful in the context of software development? Answer. An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition, all algorithms must satisfy the following criteria: 1. Input. Zero or more quantities are externally supplied. 2. Output. At least one quantity is produced. 3. Definiteness. Each instruction is clear and unambiguous. 4. Finiteness. If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps. 5. Effectiveness. Every instruction must be very basic so that it can be carried out, in principle, by a person using only pencil and paper. It is not enough that each operation be definite as in criterion 3; it also must be feasible. (Ellis Horowitz, Sartaj Sahni, Sanguthevar Rajasekaran) Program: A program is the expression of an algorithm in a programming language. Algorithms help in developing code. b) Write a pseudo-code to count number of vowels in a text. (7 + 7) Answer. Obtain text as input from the user and assign it to a string variable Set up a counter for counting vowels and initialize it with 0 (zero) find the length of the string and store it in a variable (string_length, for instance) read the entire string from the first character to the last character (string_length) (using a loop) { read a character if the character read is a vowel (a, e, i, o, u, A, E, I, O, U), then increment counter by 1 } print the value of counter [Note: The examinee is required to write only the pseudocode but for the benefit of the reader a program in ‘C’ for counting the number of vowels in a string is produced below:
  • 144.
    Computer Concepts andFundamentals of Programming 138 #includestdio.h #includestring.h main() { char str[80]; char c; int i, len, ctr=0; printf(nEnter any string: ); scanf(%[^n], str); len=strlen(str); for(i=0;ilen;i++) { c=str[i]; if((c=='a') || (c=='A')) ctr++; else if((c=='e') || (c=='E')) ctr++; else if((c=='i') || (c=='I')) ctr++; else if((c=='o') || (c=='O')) ctr++; else if((c=='u') || (c=='U')) ctr++; } printf(nstr = %s, str); printf(nNumber of vowels = %d, ctr); return 0; } A sample output is shown below: Enter any string: Computer Science str = Computer Science Number of vowels = 6 The program for counting the number of vowels in a string can also be written as follows: #includestdio.h #includestring.h main() { char str[80]; char c; int i, len, ctr=0; printf(nEnter any string: ); scanf(%[^n], str); len=strlen(str);
  • 145.
    Structures and unions 139 for(i=0;ilen;i++) { c=str[i]; switch(c) { case'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': ctr++; } } printf(nstr = %s, str); printf(nNumber of vowels = %d, ctr); return 0; } A sample interaction with the program is shown below: Enter any string: Mouse was invented by D. Engelbart str = Mouse was invented by D. Engelbart Number of vowels = 10 ] 5) a) Write a program using pointers to insert a value in an array. Answer. #includestdio.h #define SIZE 10 void func(int *arrptr, int n, int loc); main() { int arr[SIZE]; int i; int num; int location; printf(nNow obtaining %d integers for the array: n, SIZE); for(i=0;iSIZE;i++) { printf(nEnter %dth integer: , i); scanf(%d, arr[i]); } printf(nEnter integer to be inserted: ); scanf(%d, num);
  • 146.
    Computer Concepts andFundamentals of Programming 140 printf(nEnter location at which integer is to be inserted: ); scanf(%d, location); printf(nThe original array elements:); for(i=0;iSIZE;i++) printf(narr[%d] = %d, i, arr[i]); func(arr, num, location); printf(nThe array elements after inserting %d at %d:, num, location); for(i=0;iSIZE;i++) printf(narr[%d] = %d, i, arr[i]); return 0; } void func(int *arrptr, int n, int loc) { if((loc0) || (loc =SIZE)) printf(nThe array subscripts are numbered from 0 to %d, SIZE-1); else arrptr[loc] = n; } A sample interaction with the program is produced below: Now obtaining 10 integers for the array: Enter 0th integer: 0 Enter 1th integer: 1 Enter 2th integer: 2 Enter 3th integer: 3 Enter 4th integer: 4 Enter 5th integer: 5 Enter 6th integer: 6 Enter 7th integer: 7 Enter 8th integer: 8 Enter 9th integer: 9 Enter integer to be inserted: -4521 Enter location at which integer is to be inserted: 3 The original array elements: arr[0] = 0 arr[1] = 1 arr[2] = 2 arr[3] = 3 arr[4] = 4 arr[5] = 5
  • 147.
    Structures and unions 141 arr[6]= 6 arr[7] = 7 arr[8] = 8 arr[9] = 9 The array elements after inserting -4521 at 3: arr[0] = 0 arr[1] = 1 arr[2] = 2 arr[3] = -4521 arr[4] = 4 arr[5] = 5 arr[6] = 6 arr[7] = 7 arr[8] = 8 arr[9] = 9 b) What is a null pointer? Give one example. (10 + 4) Answer. A null pointer is a pointer of any type that is assigned the constant NULL (stdio.h). Examples: char *pChar = NULL; /* NULL pointer of type char */ int *pInt = NULL; /* NULL pointer of type int */ float *pFloat = NULL; /* NULL pointer of type float */ double *pDouble = NULL; /* NULL pointer of type double */ If a pointer variable is declared within the main() function or any other function and it has not been initialised or assigned a value, then it contains a garbage value as demonstrated below: #includestdio.h main() { int *iptr; float *fptr = NULL; printf(niptr = %u, iptr); /*iptr will contain a junk value since it is not initialized */ printf(nfptr = %u, fptr); return 0; } Sample output: iptr = 3 fptr = 0
  • 148.
    Computer Concepts andFundamentals of Programming 142 6) a) Explain different types of variable available in C programming language with their byte size in memory. Answer. The following program helps in determining how much memory (in bytes) is required for different data types. #includestdio.h main() { printf(nsizeof(bool) = %d, sizeof(bool)); printf(nsizeof(char) = %d, sizeof(char)); printf(nsizeof(int) = %d, sizeof(int)); printf(nsizeof(float) = %d, sizeof(float)); printf(nsizeof(double) = %d, sizeof(double)); printf(nsizeof(short int) = %d, sizeof(short int)); printf(nsizeof(long int) = %d, sizeof(long int)); printf(nsizeof(long double) = %d, sizeof(long double)); printf(nsizeof(long long int) = %d, sizeof(long long int)); return 0; } Output: sizeof(bool) = 1 sizeof(char) = 1 sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 sizeof(short int) = 2 sizeof(long int) = 4 sizeof(long double) = 12 sizeof(long long int) = 8
  • 149.
    Structures and unions 143 b)Write a function in C program for finding power (a, b), to calculate the value of a raised to b. (4+10) Answer. #includestdio.h long int power(int x, int y); main() { int a, b; long int ans; printf(nEnter the value of base: ); scanf(%d, a); printf(nEnter the value of exponent: ); scanf(%d, b); ans=power(a,b); printf(n%d to the power of %d = %ld, a, b, ans); return 0; } long int power(int x, int y) { long int p=1; int i; for(i=1;i=y;i++) p=p*x; return p; }
  • 150.
    Computer Concepts andFundamentals of Programming 144 7) a) What is an operating system? List the typical functions of operating systems. Answer. An operating system acts as an interface between the hardware of a computer and the user. The two major design goals of an operating system are (i) efficient use of hardware, (ii) efficient use of resources. The Operating System manages: input devices such as keyboard and mouse output devices such as monitor, printer network devices storage devices processor. The Operating System provides a consistent application interface. When a computer is switched on, the first set of instructions that are usually executed are from the computer’s ROM. This piece of code examines the computer hardware in order to ascertain that the hardware is functioning. This is known as POST (Power-On Self Test). After POST, the computer’s disk drives are activated, and the bootstrap loader is loaded. The bootstrap loader loads the Operating System into the computer’s memory. Examples of Operating Systems: UNIX, Linux, Windows NT, Windows IoT. The UNIX operating system consists of four major components: the kernel, the shell, a standard set of utilities, and application programs. b) What is multi tasking, multi programming, multi threading. (7 + 7) Answer. Multitasking is the concurrent execution of several processes (tasks). The processes share the CPU and main memory. Multitasking can be of several types, for instance, cooperative multitasking, preemptive multitasking, real time multitasking. In Multiprogramming, several different computer programs are loaded into the computer’s memory and execution of the first program loaded onto the memory begins. When the program reaches an instruction which requires it to wait for a peripheral, the context of the program is stored away and execution of the second program in memory begins. Multithreading is the ability of the CPU to execute multiple processes or threads concurrently. For example, three disjoint loops in a single program might be executed concurrently. 8) a) What are library functions? Explain call by value and call by reference with example. Answer. Library functions are in-built functions. The prototype of library functions in ‘C’ is contained in the header files. For example the prototype of printf() is in stdio.h, the prototype of sqrt() function is in math.h. The library functions are optimized for performance. /* Call by value */ #includestdio.h void swap(int a, int b); main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2);
  • 151.
    Structures and unions 145 swap(var1,var2); printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } OUTPUT: /* Call by reference */ #includestdio.h void swap(int *a, int *b); main() { int var1, var2; printf(nEnter two integers separated by a space: ); scanf(%d %d, var1, var2); printf(nBefore invoking swap()); printf(nvar1 = %d, var2 = %dn, var1, var2); swap(var1, var2);
  • 152.
    Computer Concepts andFundamentals of Programming 146 printf(nAfter invoking swap()); printf(nvar1 = %d, var2 = %d, var1, var2); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } OUTPUT: In pass by value, the main program [or function like main()] and the subprogram (or the called function) create two different variables or objects. Communication between the main program (or the calling function) and the subprogram (or the called function) is only one-way, i.e. from the main program to the subprogram. The variables or objects created in the main program belong to the main program and the variables or objects created in the sub-program belong to the sub-program. In pass by reference any change in values in the called function will also be reflected in the calling function. [Important Note: There is no pass by reference in ‘C’. is also known as referencing operator in C++.] b) What is the difference between gets() and scanf() function? Write the differences between structures and arrays. (7 + 7) Answer. gets() is used to obtain a string value from the user. scanf() can be used to obtain a character, int, float, or double type value from the user.
  • 153.
    Structures and unions 147 Conversionspecifications are to be used with scanf()such as %c for character, %d or %i for integer, %f for float. For accepting a string containing spaces ^[n] is used in scanf(). The gets() function accepts a line terminated by the newline character and converts the newline character to ‘0’. A structure is a collection of related elements, possibly of different or same subtypes, identified by a single name. Each element in the structure is called a field. The difference between an array and a structure is that all elements in an array must be of the same type, while the elements in a structure can be of the same or different types. But an array of structures can be created and array(s) can be part of a structure. The fields (or structure elements) should all be related to one object (as a matter of good programming practice). For example: struct book { char book_name[80]; char author1[80]; char author2[80]; char author3[80]; char publisher[80]; char edition[80]; int no_of_pages; char isbn[14]; }; [The student is advised to read the chapters on arrays and structures carefully in order to gain an understanding for answering this question.] *****
  • 154.
    CHAPTER – 12 ELECTRONICCOMMERCE 12.1 Introduction: E-commerce associated with the purchase and sale of goods and/or services via electronic channels such as the internet. E-commerce was first introduced in the 1960s via an electronic data interchange (EDI) on value-added networks (VANs). E-Commerce addresses the need of business organizations, vendors and customers to reduce cost and improve the quality of goods and services also increasing the speed of delivery. A key element of e-commerce is information processing. All steps of commerce, except for production, distribution, and delivery of physical goods, are forms of information gathering, processing, manipulation, and distribution, which computers and networks are perfectly suited to handle E-commerce refers to paperless exchange of business information using different ways: • Electronic Data Exchange (EDI) • Electronic Mail (e-mail) • Electronic Bulletin Boards • Electronic Fund Transfer (EFT) • Other Network-based technologies 12.1.1  Potential Benefits of Electronic Commerce The following are the potential benefits of E-commerce: 1. Internet and web-based electronic commerce is cheaper than traditional EDI. 2. Internet and web-based electronic commerce allows more business partners to be reached than with traditional EDI. 3. Internet arid web-based electronic commerce can reach a more geographically dispersed customer base. 4. Procurement processing costs can be reduced. 5. Cost of purchases can be reduced. 6. Reductions in maintaining records. 7. Lower cycle times. 8. Better customer service and 9. Lower marketing and sales costs. 12.2  Concepts of Electronic Communication Electronic communications the transmission of information using advanced techniques such as computer modems, facsimile machines, voice mail, electronic mail, teleconferencing, video-cassettes and private television network. In general the e-commerce applications will be built on the existing technology infrastructure such as: a set of computers, communications networks, and communications software forming the Information Superhighway.
  • 155.
    Electronic Commerce 149 Media orTypes of Electronic Communication 1. Telephone: The most commonly and widely used electronic device of communication is telephone. By telephone, people can transmit information orally within a minute. Recently-developed satellite telephoning system has added new dimension in telecommunication system. In most of the cases, it is the easiest and less expensive way of communicating distance people. 2. Telex: Telex is an important device of modern communication technology. Under this system, a tele-printer is used by which information can be communicated fm one place to another with the help of a machine. The tele-printer consists of two parts keyboard transmitter and receiver. When a message is to be sent, the typist presses a button, waits for the dial tone, dials the number desired and types the massage. The message is typed on a small strip of paper at the receiver’s end as it is typed in the originating office. This is one of the quickest and most accurate methods of exchanging written messages. 3. Facsimile or Fax: The use of fax a gradually increasing for transmitting visual materials such as picture, diagrams, illustrations etc. here, the fax machine is connected with a telephonic. The document to be transmitted is fed through the machine, then it is electronically scanned and signals are transmitted to the receiving end where an identical copy of the document is reproduced on a bland sheet of paper by the receiving machine. 4. Electronic Mail or E-Mail: E-mail is one of the most widely used and most popular methods of modern communication system. E-mail involves sending message via telecommunicating links. Here two computer terminals are connected together on network to transfer messages from one to another. The message is typed on a computer screen at one end and is conveyed to the other end through electric impulses. 5. Voice Mail or V-Mail: Voice mail is a form of e-mail. It is used to send the voice of the sender instead of sending written massage to the receiver. The mechanism of sending message here is almost same as in case of e-mail. It is useful to communicate with the original voice tone of the sender. 6. Videoconferencing: Videoconferencing is the latest version of teleconferencing system. Under this method people can meet and work together without being gathered in one room. They can hear and see each other over the television or video screen and can share information with one another. Now-a-days multinational companies use videoconferencing method as a widely used means of communication in order to keep touch with the executives staying miles away from the head office. It also saves money and time of high officials. 7. Internet: Internet is the latest and most amazing development that has changed the way of live regarding communication. It is the world’s largest computer network linked together by telephone lines, radio links or satellite links. Internet can be used for multipurpose functions. It can be used for sending e-mail, for advertisement, for teleconferencing, for telephoning and so on. 8. Multimedia: Multimedia is an excellent invention for upgrading the communication system. Multimedia is a combination of many media brought together to transfer messages. These media can include graphics, photo, music, voice, text and animation. When all of these elements are placed together or computer screen, they become multimedia. It can be effectively used for advertising and publicity campaigns. It is very powerful means of communication. 12.3  Internet and Intranet: Internet: The Internet is the global system of interconnected computer networks that use the Internet protocol suite (TCP/IP) to link devices worldwide. The dictionary definition of internet is that it is a large global system of connected computers that enables people to share information and communicate. Also known as the worldwide web. The internet is now for many of us an indispensable part of our daily lives. It enables us to connect and disseminate data with anyone, anytime and anywhere. It’s one common network, only sharing one common addressing scheme. And a lot of open-standard protocols. Formed by the many thousands of independent networks. It’s thousands of networks agreeing to talk to each other: being on one common network: The Internet.
  • 156.
    Computer Concepts andFundamentals of Programming 150 The Internet is a communal of computer network. It is a network of networks that consists of private, public, academic, business, and government networks of local to global scope, linked by extensive array of electronic, wireless, and optical networking technologies. Fig. Internet of things The internet is nothing more than the computer network which is used to transmit the data from one location to another. With the help of Internet user can search for required information as well as other features such as messaging programs, home shopping, file sharing and music or video downloading sites all operate on top of the basic network. The fact is the internet is little more than a collection of standalone computers, which are all linked together mainly using the telephone network. Computers can be connected with the help of old-fashioned copper cables as well as the newer fiber-optic cables along with wireless radio connections and satellite links. In short, the internet is the means by which we move computerized data from one location to another. Fig. Internet Vs Intranet Intranet An intranet is a private network that can only be accessed by authorized users. The prefix “intra” means “internal” and therefore implies an intranet is designed for internal communications. It is a private network based on TCP/IP protocols that belongs to an organization and is accessible to the organization’s employees or others who have authorization.
  • 157.
    Electronic Commerce 151 There iscertain internal information that organizations do not want to make public on the Internet. In such scenarios, intranet allows an organization to make wide range of internal information and services accessible only to its employees and authorized persons. A company-wide intranet establishes an important confluence point of internal communication and collaboration. It offers a common point to access internal and external resources. An intranet is built on the technologies for Local Area Networks (LANs) and Wide Area Networks (WANs). And just like the internet, an intranet offers its own powerful modules that sit on top of the basic platform. These features will vary from organization to organization and intranet to intranet. Companies are using intranets to: - share documents and circulate information - communicate company news and corporate messages - complete online tasks and workflow processes - Improve collaboration and joint working across teams and office locations - Encourage employee engagement with blogs, surveys and company forums. The cloud nature of the intranet whereby information is stored on remote servers means that everything on an intranet is accessible 24/7 using smartphone or internet connection. And in the modern digital workplace where more and more employees are telecommuting and working flexibly. The cloud intranet means that staff no longer need to be physically in the office to get things done. With a cloud intranet employees are still working for company whether on their way to office, attending an overseas conference or out on the road visiting clients. It can help to increase the efficiency and effectiveness of employees as well as overall productivity. 12.4  EDI to E Commerce EDI stands for Electronic Data Interchange. EDI is an electronic way of transferring business documents in an organization internally between its various departments or externally with suppliers, customers or any subsidiaries etc. In EDI, paper documents are replaced with electronic documents like word documents, spreadsheets etc. Following are few important documents used in EDI − • Invoices • Purchase orders • Shipping Requests • Acknowledgement • Business Correspondence letters • Financial information letters Steps in an EDI System • A program generates the file which contains the processed document. • The document is converted into an agreed standard format. • The file containing the document is send electronically on network. • The trading partner receives the file. • An acknowledgement document is generated and sent to the originating organization. Advantages of an EDI System Following are the advantages of an EDI System. • Reduction in data entry errors. − Chances of errors are much less being use of computer in data entry. • Shorter processing life cycle − As orders can be processed as soon as they are entered into the system. This reduced the processing time of the transfer documents. • Electronic form of data − It is quite easy to transfer or share data being in electronic format.
  • 158.
    Computer Concepts andFundamentals of Programming 152 • Reduction in paperwork − As lot of paper documents are replaced with electronic documents there is huge reduction in paperwork. • Cost Effective − As time is saved and orders are processed very effectively, EDI proves to be higly cost effective. • Standard Means of communication − EDI enforces standards on the content of data and its format which leads to clearer communication. Issues and challenges related to the growth of EDI? “Growth in EDI ability is becoming a requirement for effectively servicing many large business customers,” explains the researchers’ report. “Even then, implementation of EDI creates difficult and complex problems for organizations. Thus many companies have adopted EDI but have not received the expected results. Subsequently EDI benefits are not guaranteed.” Some common issues are: 1. Failure to include all business processes. With a data interchange platform in the mix, some enterprises continue their reliance on legacy applications which should be rendered outmoded. Additionally, during the platform selection process, decision makers may choose a system that doesn’t address the immediate needs of the organization. These gaps in utility can add more to employees’ plates, managing B2B communication inside and outside the EDI platform. 2. Inadequate budgetary and management support. Shoring up the support of employees at every level is critical to successful deployment. Those individuals may lean on legacy systems, not because of gaps in the framework, but because they’re prone to resisting the new platform. Working with a third-party solutions provider, decision makers should size up the budgetary costs up front so that point people at every level set reasonable expectations. 3. Insufficient staff training. Fault lines in your EDI platform may emerge because employees haven’t been properly oriented to how the systems work. Effective training reduces the time spent on individual tasks and gives your employees dexterity to move forward with a comprehensive understanding of the system. 4. Errors in data security. Companies with sensitive data to store, send and receive require EDI solutions built to protect and secure data. Choosing a system with insufficient data security can leave your organization susceptible to hackers and other outside parties. 5. Lack of flexibility. Another point is the failure for EDI systems to scale, adapt and update alongside the shifting demands of an industry. This is why maintenance and continuous review are essential. 12.5  Concerns for E-commerce Growth The consequences of some of the issues described below are bad publicity, loss of business, disgruntled customers, possible financial damages, unsecured sensitive customer information, and data corruption. 1. Lack of planning • Unrealistic goals • No business focus or site not integrated with your overall business. 2. No promotion or inappropriate promotion • Spending a lot of money just to develop a site without also investing in promotion is wasteful • Doing promotion and not following up. 3. Bad site design poor usability • Simplicity works. Sometimes, it is more important to have targeted content with an overall customer • focus than to have the latest whiz-bang gizmos and a flashy site. • Is content easily found and is the site easy to navigate? • Are fonts too small or set against the wrong background colour? • Is it intuitive to visitors to know the next steps? • Do you have a strong call to action?
  • 159.
    Electronic Commerce 153 4. Slowperformance • Potentially good sites fail because of performance when visitors wait for the site to load. A site that takes more than a couple of seconds to load will not be successful • Slow sites are usually the result of bad design, a poorly selected host, non-optimised images, or sites overloaded with widgets and gizmos. 5. Coding errors • The site may look and perform well on newer browsers but it can also crash on older browsers • “Page Not Found” and other coding errors. 6. Security hacking issues • Non-secure online payments • Spam attacks on a blog or user comments • Hacked or defaced site • Viruses on your site. 7. Going cheap - you get what you pay for • When outsourcing, if the price sounds too good to be true then it just might be • Free hosting in foreign countries are generally slower with more downtime than local hosting • Not relying on expert advice/help. 8. Content • Spelling grammar issues • Incorrect or inaccurate content • No contact information! • Poorly written content that is difficult to read • Inappropriate content. 12.6  Technical issues 1. Interoperability: • The ability of systems running in different operating environments to communicate and work together. – E.g., clients running Windows XP can access Web pages from servers running Linux. • For the interoperability to work, the same set of rules (protocols) must be followed • Internetworking standard, i.e., TCP/IP 2. Security: Three types of security threats – denial of service, – unauthorized access, and – theft and fraud • Denial of Service (DOS): Two primary types of DOS attacks: spamming and viruses a) Spamming – Sending unsolicited commercial emails to individuals – E-mail bombing caused by a hacker targeting one computer or network, and sending thousands of email messages to it. b) Viruses: self-replicating computer programs designed to perform unwanted events Worms: special viruses that spread using direct Internet connections Trojan Horses: disguised as legitimate software and trick users into running the program • Unauthorized access a) I Illegal access to systems, applications or data b) Passive unauthorized access – listening to communications channel for finding secrets. – May use content for damaging purposes c) Active unauthorized access – Modifying system or data – Message stream modification • Fraud occurs when the stolen data is used or modified, Theft of software via illegal copying from company’s servers, Theft of hardware, specifically laptop.
  • 160.
    Computer Concepts andFundamentals of Programming 154 3. Privacy: • Threats to data Data collection – Faster and easier data collection through online technology – Cross-referencing real offline consumer data with online purchasing habits collected with or without their knowledge. Or cross-referencing online data with other online data between several Web entrepreneurs, for example – Hidden data collection without consumer consent, possibly through cookies. Usage tracking – Patterns of online activity lead to inferences about the user’s product preferences for providing customized pop-up ads and referring sites. – May include spyware. Spyware - A type of program that watches what users do with their computer and then sends that information over the Internet to the spyware’s author. 4. Phishing: • Misspelled URLs or the use of subdomains • Use of JavaScript commands to alter the address bar by placing a picture of the legitimate URL over the fake one. 12.7  Essential security requirement for the e commerce Security is an essential part of any transaction that takes place over the internet. Customer will loose faith in e-business if its security is compromised. Following are the essential requirements for safe transactions − • Confidential − Information should not be accessible to unauthorized person. It should not be intercepted during transmission. • Integrity − Information should not be altered during its transmission over the network. • Availability − Information should be available wherever and whenever requirement within time limit specified. • Authenticity − There should be a mechanism to authenticate user before giving him/her access to required information. • Non-Repudiabiity − It is protection against denial of order or denial of payment. Once a sender sends a message, the sender should not able to deny sending the message. Similarly the recipient of message should not be able to deny receipt. • Encryption − Information should be encrypted and decrypted only by authorized user. • Auditability − Data should be recorded in such a way that it can be audited for integrity requirements. 12.8  Security Technologies: 12.8.1  What is Cryptography? Cryptography is one of the essential technologies used in building a secure virtual private network(VPN). It is the art and science of making a cryptosystem that is capable of providing information security. Cryptography deals with the actual securing of digital data. It refers to the design of mechanisms based on mathematical algorithms that provide fundamental information security services. It is the establishment of a large toolkit containing different techniques in security applications. 12.8.2  What is Cryptanalysis? The art and science of breaking the cipher text is known as cryptanalysis. Cryptanalysis is the branch of cryptography and they both co-exist. The cryptographic process results in the cipher text for transmission or storage. It involves the study of cryptographic mechanism with the intention to break them. Cryptanalysis is also used during the design of the new cryptographic techniques to test their security strengths. Data confidentiality may be provided by one of two categories of encryption algorithm, namely symmetric cryptography and asymmetric cryptography. Symmetric, or conventional, cryptography requires that the sender and receiver share a key, which is an item of secret information used to encrypt and decrypt data. The process by which two peers agree upon a key over an insecure medium can be problematic as, until the key is agreed, the peers have no way to communicate in secret.
  • 161.
    Electronic Commerce 155 12.8.3 CryptographyAlgorithms Cryptography primitives are nothing but the tools and techniques in Cryptography that can be selectively used to provide a set of desired security services − • Encryption • Hash functions • Message Authentication codes (MAC) • Digital Signatures A cryptosystem is an implementation of cryptographic techniques and their accompanying infrastructure to provide information security services. A cryptosystem is also referred to as a cipher system. Fig. Cryptosystem The objective of this simple cryptosystem is that at the end of the process, only the sender and the receiver on this communication channel will know the plaintext. Components of a Cryptosystem are: • Plaintext: It is the data to be protected during transmission. • Encryption Algorithm: It is a mathematical process that yields a ciphertext for any given plaintext and encryption key. It is a cryptographic algorithm that takes plaintext and an encryption key as input and produces a ciphertext. • Cipher text:  It is the scrambled version of the plaintext produced by the encryption algorithm using a specific the encryption key. The ciphertext is not secured. It flows on public channel. It can be intercepted or compromised by anyone who has access to the communication channel. • Decryption Algorithm: It is a mathematical process, that yields a unique plaintext for any given ciphertext and decryption key. It is a cryptographic algorithm that takes a ciphertext and a decryption key as input, and outputs a plaintext. The decryption algorithm essentially reverses the encryption algorithm and is thus closely related to it. • Encryption Key: It is a value that is known to the sender. The sender inputs the encryption key into the encryption algorithm along with the plaintext in order to compute the ciphertext. • Decryption Key: It is a value that is known to the receiver. The decryption key is related to the encryption key, but is not always identical to it. The receiver inputs the decryption key into the decryption algorithm along with the ciphertext in order to compute the plaintext. 12.8.4  Types of Cryptosystems There are two types of cryptosystems based on the manner in which encryption-decryption is carried out in the system − 1. Symmetric Key Encryption 2. Asymmetric Key Encryption (public key cryptography) Symmetric Key Encryption: Symmetric encryption is one of the best-known technique. A secret key, which can be a number, a word, or just a string of random letters, is applied to the text of a message to change the content in a particular way. This might be as simple as shifting each letter
  • 162.
    Computer Concepts andFundamentals of Programming 156 by a number of places in the alphabet. As long as both sender and recipient know the secret key, they can encrypt and decrypt all messages that use this key. Symmetric encryption uses a key, which is known as the Symmetric Key. In today’s computer-based system this Symmetric Key is a series of numbers and letters. This Symmetric Key is used to encrypt a message as well as the same key is also used to decrypt it. In Symmetric Encryption uses only one key. Fig. Symmetric key encryption The features of symmetric key encryption are • Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption. • Persons using symmetric key encryption must share a common key prior to exchange of information. • A robust mechanism needs to exist to exchange the key between the communicating parties. As keys are required to be changed regularly, this mechanism becomes expensive and cumbersome. • In a group of n people, to enable two-party communication between any two persons, the number of keys required for group is n × (n – 1)/2. • Keys are recommended to be changed regularly to prevent any attack on the system. • Processing power of computer system required to run symmetric algorithm is less. Challenges of Symmetric Key Cryptosystem There are two restrictive challenges of employing symmetric key cryptography. • Key exchange − Before any communication, both the sender and the receiver need to agree on a secret symmetric key. The key exchange problem arises from the fact that communicating parties must somehow share a secret key before any secure communication can be initiated, and both parties must then ensure that the key remains secret. It requires a secure key establishment mechanism in place. • Trust Issue − Ensuring the integrity of received data and verifying the identity of the source of that data can be very important. Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver ‘trust’ each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed. Asymmetric Key Encryption The encryption process where different keys are used for encrypting and decrypting the information is known as Asymmetric Key Encryption. Though the keys are different, they are mathematically related and hence, retrieving the plaintext by decrypting ciphertext is feasible. The most commonly used implementations of public key cryptography (also known as public-key encryption) are based on algorithms presented by Rivest-Shamir-Adelman (RSA) Data Security.
  • 163.
    Electronic Commerce 157 Public keycryptography involves a pair of keys known as a public key and a private key (a public key pair), which are associated with an entity that needs to authenticate its identity electronically or to sign or encrypt data. Each public key is published and the corresponding private key is kept secret. Data that is encrypted with the public key can be decrypted only with the corresponding private key. RSA public key pairs can be any size. Typical sizes today are 1024 and 2048 bits. Fig. Asymmetric key encryption The features of Asymmetric key encryption are • Encryption and decryption, which allow two communicating parties to disguise data that they send to each other. The sender encrypts, or scrambles, the data before sending it. The receiver decrypts, or unscrambles, the data after receiving it. While in transit, the encrypted data is not understood by an intruder. • Nonrepudiation, which prevents: The sender of the data from claiming, at a later date, that the data was never sent and the data from being altered. • Every user in this system needs to have a pair of dissimilar keys, private key and public key. These keys are mathematically related − when one key is used for encryption, the other can decrypt the ciphertext back to the original plaintext. • It requires to put the public key in public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption. • Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme. • When Host1 needs to send data to Host2, he obtains the public key of Host2 from repository, encrypts the data, and transmits. • Host2 uses his private key to extract the plaintext. • Length of Keys (number of bits) in this encryption is large and hence, the process of encryption- decryption is slower than symmetric key encryption. • Processing power of computer system required to run asymmetric algorithm is higher. 12.8.5  Digital signatures A digital signature guarantees the authenticity of an electronic document or message in digital communication and uses encryption techniques to provide proof of original and unmodified documentation. Digital signatures are used in e-commerce, software distribution, financial transactions and other situations that rely on forgery or tampering detection techniques. A digital signature is also known as an electronic signature In asymmetric ciphers, one single individual holds the private key, while everyone can get the public key So if you encrypt with the private key, and send both cryptogram and message, anyone can check that “decryption” with the public key does indeed create
  • 164.
    Computer Concepts andFundamentals of Programming 158 the message. Note that some public key systems do not allow “encryption” with the private key. Most systems can be modified to generate and verify signatures. A digital signature can be created using asymmetric cryptography. Fig. Digital signature A digital signature is applied and verified, as follows: • The document or message sender (signer) or public/private key supplier shares the public key with the end user(s). • The sender, using private key, appends the encrypted signature to the message or document. • The end user decrypts the document and verifies the signature, which lets the end user know that the document is from the original sender. Review Questions Q.1 What are the advantages and disadvantages of e commerce? Q.2 What are the intranet features? Q.3 What are issues and challenges related to the growth of EDI? Q.4 What are Types of e commerce? Explain in details. Q.5 What are the Common issues with e-commerce and doing business online? Q.6 What is digital cash and what is the basic model of transaction system? Enlist different properties of digital cash. Q.7 What are the pros and cons of digital cash? Q.8 What are the essential security requirement for the e commerce? Q.9 What are the Measures to ensure Security for e commerce? Q.10 Symmetric vs asymmetric encryption ? Q.11 Explain types of Cryptosystems in detail.
  • 165.
    Appendix Opening a webbrowser via a ‘C’ program Is it possible to open a web page in a browser using a ‘C’ program? The program below provides an answer to the aforementioned question: Program listing one #includestdio.h main() { char url[25] = “www.mail.yahoo.com”; char launch[255]; system(“clear”); sprintf(launch, “gnome-open %s”, url); system(launch); return 0; } [NOTE: 1. The above code should be compiled on a Linux system. 2. Parallel methods for opening a web-browser are available for Windows/Mac OSs. For instance, on a Mac OS, system(“open http://url”); might be used.] An alternative method of opening a web page is given below: Program listing two #includestdio.h main() { char url[25] = “www.iiml.ac.in”; char launch[255]; system(“clear”); sprintf(launch, “firefox %s”, url); system(launch); return 0; }
  • 166.
    Computer Concepts andFundamentals of Programming 160 [Note: The code in Program listing two assumes that firefox is installed on the workstation and the appropriate PATH has been set.] The program below provides an illustration of another method of opening a web-browser via a ‘C’ program: Program listing three #includestdio.h #includeunistd.h main() { execl(“/usr/bin/firefox”, (char *)0); printf(“execl() could not open the web-page”); /* this line will be executed only if execl() above is not able to launch firefox*/ return 0; } The reader may interpret execl()as execute and leave. The execl() function replaces the current process by running the program specified as an argument to the execl()function. The process identifier (PID) of the new process will be the same as the PID of the old process (old process refers to the program in program listing three which is being compiled and executed and new process refers to firefox). The prototype of the execl()function is: int execl(const char *path, const char *arg1,...); execl() is a variadic function and the list of arguments to execl() should be terminated by a NULL pointer, therefore (char *)0 has been used to indicate the end of arguments to execl().
  • 167.
    Appendix 161 INDIAN MARITIME UNIVERSITY (ACentral University, Government of India) June 2017 End Semester Examinations B. SC (Nautical Science – First Semester (Computer Science – UG21T 3104) (AY 2016 - 17 batch onwards) Date: 08.06.2017 Maximum Marks: 70 Time: 3 Hrs Pass Marks: 35 Answer any SEVEN of the following. (7X10=70) 1. What is mail merge? Write the procedure to use mail merge for inviting your friends for your birthday party. (10 Marks) 2. How are charts useful in Excel? Compare any three chart types available in Excel. (10 Marks) 3. a)  What is the difference between Animation and Transition? (5 Marks) b)  Write the procedure to insert a chart in a slide (5 Marks) 4. Carry out the following conversions: (10 Marks) i. (101011)2=(?)10 ii. (247.6875)10=(?)8 iii. (3A.2F)16=(?)10 iv. (5647.45)8=(?)16 v. (35.625)10=(?)2 5. Write short notes on (10 Marks) a. EDI (Electronic data interchange) b. Encryption c. Digicash d. SSL (Secure Socket Layer) e. Hashing 6. a)  Write about character input and output in details (5 Marks) b)  Write a program to accept a number from keyboard and find whether it odd or even (5 Marks) 7. Explain switch-case statement with example (10 Marks) 8. Define function. Explain how a user defined function can be created and used. (10 Marks) 9. a)  Define pointer. Explain how is it declared and used. (5 Marks) b)  Define structure. Explain declaring and accessing of structure members with example. (5 Marks) *****
  • 168.
    Computer Concepts andFundamentals of Programming 162 INDIAN MARITIME UNIVERSITY (A Central University, Government of India) MAY/JUNE 2018 END SEMESTER EXAMINATION BSc (Nautical Science) Semester: III Computer Science Paper I (UG21T2301) Date:02-07-2018 Max Marks: 70 Time: 3Hours Pass Marks: 35 Answer any seven of the following. (7X10=70) 1. a) Represent the decimal 12345.54321 into its equivalent binary number. (10) b) Convert (100001100)2 into Hexadecimal c) Convert decimal 465 to its octal equivalent d) Convert (1001.01)2 to its equivalent decimal e) Convert hexadecimal (2 4 3 F)16 to octal 2. a) Find 2’s complement of 6910 (2) b) Subtract 15 from 87 using two’s complement (4) c) Do as directed (4) i. add (10111)2 and (110101)2 ii. add (1011001 )2 by (111010 )2 3. Write short notes on (a) excess 3 code (5) (b) ASCII code (5) 4. a) Explain the difference between volatile and non-volatile memory give example (5) b) What is the use of virtual memory? (5) 5. Write short note on different computer environments (10) 6. a) Describe Satellite Communication system (5) b) What is E-commerce and Give some applications of E-commerce? (5) 7. a) Distinguish between symmetric and asymmetric cryptography. (5) b) Define digital cash (2) c) Write notes on SET (3) 8. a) Define Electronic Data Interchange (EDI). Explain the process of EDI (5) b) Differentiate between Internet and intranet (5) 9. Explain how SSL protocol is used for secure transaction (10) *****
  • 169.
    Question Bank ForPractice 163 QUESTION BANK FOR PRACTICE 1. The numbers 1, 8, 17, 18, 26, and 27 are very special numbers, because the sum of the digits of the cubes of these numbers is equal to the number itself: Num Cube Sum of the digits of the cube 1 1 1 8 512 5 + 1 + 2 = 8 17 4913 4 + 9 + 1 + 3 = 17 18 5832 5 + 8 + 3 + 2 = 18 26 17576 1 + 7 + 5 + 7 + 6 = 26 27 19683 1 + 9 + 6 + 8 + 3 = 27 Write a program to print all such numbers in the range 1 to 2000. 2. The number 153 is an amazing number, because, 153 is divisible by the sum of its digits: 153/(1 + 5 + 3) = 17 (such integers which are divisible by the sum of their digits are known as Harshad numbers or Niven numbers) Write a program to print all such numbers in the range 1 to 2000. This question is not related to Armstrong Numbers in any way. 3. An emirp is 'prime' spelt backwards and refers to a prime number which will yield a different prime number when written backwards. For instance 13 and 31, 17 and 71, 37 and 73. Write a program to print all such numbers in the range 1 to 2000. 4. The number 1547 is interesting, because 1547 = (1 + 5 + 4 + 7)(12 + 52 + 42 + 72 ) i.e. it is equal to the product of the sum of their digits and sum of the squares of their digits. Write a program to print all such numbers in the range 1 to 4000. 5. The number 301 is a very interesting number because 3012 = 90601 and 1032 = 10609 i.e. 301 and 103 are the reverse of each other and their squares are also the reverse of each other. Write a program to print all such numbers in the range 1 to 4000. 6. Write a program in 'C' to interchange the value of two integer variables. temp=var1; var1=var2; var2=temp; 7. Write a program in 'C' to interchange the value of two integer variables without using a third variable. METHOD 1: var1=var1-var2; var2=var2+var1; var1=var2-var1;
  • 170.
    Computer Concepts andFundamentals of Programming 164 METHOD 2: var1=var1+var2; var2=var1-var2; var1=var1-var2; (i) Write a program to input three sides and determine whether they form a triangle or not? (ii) Write a program to input any string and convert the uppercase letters in the string to lowercase 8. Write a program in ‘C’ to illustrate matrix operations such as addition and multiplication of two matrices. The order of the matrix should be decide at run time. 9. A number of nine (9) digits has the following properties: The first two digits (from the left) are divisible by 2; The first three digits (from the left) are divisible by 3; The first four digits (from the left) are divisible by 4; The first five digits (from the left) are divisible by 5; The first six digits (from the left) are divisible by 6; The first seven digits (from the left) are divisible by 7; The first eight digits (from the left) are divisible by 8; The first nine digits (from the left) are divisible by 9; It contains all the digits from 1 to 9 exactly once. Write a program in ‘C’ to find the number. 10. Write a program to print the sum of the digits of the first 11 prime numbers. Each prime number should be printed on a new line and the sum of the digits of the prime number should appear next to the prime number. For example: PRIME NUMBER SUM OF DIGITS OF THE PRIME NUMBER 2 2 3 3 5 5 7 7 11 2 13 4 17 8 19 10 23 5 29 11 31 4
  • 171.
    Question Bank ForPractice 165 11. Write a program to print the gap between two consecutive prime numbers for the first 20 prime numbers. For example: PRIME NUMBER GAP BETWEEN TWO CONSECUTIVE PRIME NUMBERS 2 3 Gap between 3 and 2 = 1 5 Gap between 5 and 3 = 2 7 Gap between 7 and 5 = 2 11 Gap between 11 and 7 = 4 13 Gap between 13 and 11 = 2 17 Gap between 17 and 13 = 4 19 Gap between 19 and 17 = 2 23 Gap between 23 and 19 = 4 29 Gap between 29 and 23 = 6 31 Gap between 31 and 29 = 2 12. For natural numbers in the range of 1 to 1000,: There are x no of prime numbers: Total no. of prime numbers which end in 1: Total no. of prime numbers which end in 3: Total no. of prime numbers which end in 7: Total no. of prime numbers which end in 9: 13. Write a program to find the sum of the following series: 1 – 2 + 3 – 4 + 5 – 6 + . . . + 99 – 100 Method 1: 1 – 2 = –1 3 – 4 = –1 5 – 6 = –1 … 99 – 100 = –1 Thus, we need to add –1 fifty times. Method 2: s = s + i * (–1)(i+1) Method 3: s=0; for(k=1;k100;k+=2) s= s + k – (k+1);
  • 172.
    Computer Concepts andFundamentals of Programming 166 Method 4: s1=s2=0; for(i=1;i100;i+=2) s1=s1 + i; for(j=2;j=100;j+=2) s2=s2 – j; s3=s1 + s2; Method 5: s1=s2=0; for(i=1;i100;i+=2) s1=s1 + i; for(j=2;j=100;j+=2) s2=s2 + j; s3=s1 – s2; 14. Write a program in ‘C’ to display the first seven lines of the following pattern: 0 1 1 2 2 2 3 4 4 3 4 7 8 7 4 5 11 15 15 11 5 6 16 26 30 26 16 6 15. Write a program in ‘C’ to input any integer and print it in words. For example, if the input is 213, then the output should be Two Hundred Thirteen (range: 1 – 9999). 16. Write a program in ‘C’ to input any integer and print its Roman Equivalent (range: 1 – 2999). 17. Write a program in ‘C’ to input any integer and count the number of digits in it. 18. Write a program in ‘C’ to input any integer and print it in reverse order. 19. Write a program in ‘C’ to input any string and print its words in reverse order. For instance, if the input is LION IS A PET ANIMAL, then the output should be ANIMAL PET A IS LION. 20. Write a program in ‘C’ to input any string and print its words in the same order but internally reversed. For instance, if the input is LION IS A PET ANIMAL, then the output should be NOIL SI A TEP LAMINA 21. Write a program in ‘C’ to input any word and print all its permutations. 22. Write a program in ‘C’ to input two integers and print the greater without using less than and greater than operators. Do NOT use the IF construct. 23. Write a program in ‘C’ to determine the angle (reflex-angle) between the hour hand and minute hand.
  • 173.
    Question Bank ForPractice 167 A book that might help in building basic logic. It dwells on emirp, primorial, Father prime, Sophie-Germain Prime, Wilson prime, Cullen prime, Prime Quadruplet, Prime Quintuplet, Prime Sextuplet, Weifrich prime, Woodall prime, Fermat primes, Mersenne primes, Pi-prime, Circular prime numbers, interprime, twin primes, Left-truncatable prime, Right-truncatable primes, Two-sided primes, Permutable primes, Titancic primes,... Many corporations have lost several billions of opportunities only because of sophistry in the analyses of data available to them. This book is a must-read as it dwells on fundamental mathematical reasoning, fallacies, howlers, and number- tricks.