Monday, 22 December 2014

Simple Programming Problems

Whenever I’m TA for a introductory CS class where students learn some programming language, I have trouble coming up with good exercises. Problems from Project Euler and the like are usually much too difficult for beginners, especially if they don’t have a strong background in mathematics.
This page is a collection of progressively more difficult exercises that are suitable for people who just started learning. It will be extended as I come up with new exercises. Except for the GUI questions, exercises are generally algorithmic and should be solvable without learning any libraries. The difficulty of the exercises of course somewhat depends on the programming language you use. The List exercises for example are more complicated in languages like C that don’t have build-in support for lists.
I suppose they are also useful, although much easier, whenever an experienced person wants to learn a new language.

Elementary

  1. Write a program that prints ‘Hello World’ to the screen.
  2. Write a program that asks the user for his name and greets him with his name.
  3. Modify the previous program such that only the users Alice and Bob are greeted with their names.
  4. Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
  5. Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
  6. Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
  7. Write a program that prints a multiplication table for numbers up to 12.
  8. Write a program that prints all prime numbers. (Note: if your programming language does not support arbitrary size numbers, printing all primes up to the largest number you can represent is fine too.)
  9. Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether his number was too large or too small. At the end the number of tries needed should be printed. I counts only as one try if the user inputs the same number consecutively.
  10. Write a program that prints the next 20 leap years.
  11. Write a program that computes
    4k=1106(-1)k+12k-1=4(1-1/3+1/5-1/7+1/9-1/11).

Lists, Strings

  1. Write a function that returns the largest element in a list.
  2. Write function that reverses a list, preferably in place.
  3. Write a function that checks whether an element occurs in a list.
  4. Write a function that returns the elements on odd positions in a list.
  5. Write a function that computes the running total of a list.
  6. Write a function that tests whether a string is a palindrome.
  7. Write three functions that compute the sum of the numbers in a list: using a for-loop, a while-loop and recursion.
  8. Write a function on_all that applies a function to every element of a list. Use it to print the first twenty perfect squares.
  9. Write a function that concatenates two lists.
  10. Write a function that combines two lists by alternatingly taking elements, e. g. [a,b,c][1,2,3] →[a,1,b,2,c,3].
  11. Write a function that merges two sorted lists into a new list.
  12. Write a function that computes the list of the first 100 Fibonacci numbers.
  13. Write a function that takes a number and returns a list of its digits.
  14. Write functions that add, subtract, and multiply two numbers in their digit-list representation (and return a new digit list). If you’re ambitious you can implement Karatsuba multiplication. Try different bases. What is the best base if you care about speed?
  15. Implement the following sorting algorithms: Selection sort, Insertion sort, Merge sort, Quick sort, Stooge Sort. Check Wikipedia for descriptions.
  16. Implement binary search.
  17. Write a function that takes a list of strings an prints them, one per line, in a rectangular frame. For example the list ["Hello", "World", "in", "a", "frame"] gets printed as:
    *********
    * Hello *
    * World *
    * in    *
    * a     *
    * frame *
    *********
  18. Write function that translated a text to Pig Latin and back. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word and adding ‘ay’. “The quick brown fox” becomes “Hetay uickqay rownbay oxfay”.

Intermediate

  1. Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.
  2. Write a program that takes the duration of a year (in fractional days) for an imaginary planet as an input and produces a leap-year rule that minimizes the difference to the planet’s solar year.
  3. Implement a datastructure for graphs that allows modification (insertion, deletion). It should be possible to store values at edges and nodes. It might be easiest to use a dictionary of (node, edgelist) to do this.
  4. Write a function that generates a DOT representation of a graph.
  5. Write a program that automatically generates essays for you.
    1. Using a sample text, create a directed (multi-)graph where the words of a text are nodes and there is a directed edge between u and v if u is followed by v in your sample text. Multiple occurrences lead to multiple edges.
    2. Do a random walk on this graph: Starting from an arbitrary node choose a random successor. If no successor exists, choose another random node.
  6. Write a program that automatically converts English text to Morse code and vice versa.
  7. Write a program that finds the longest palindromic substring of a given string. Try to be as efficient as possible!

Advanced

  1. Given two strings, write a program that efficiently finds the longest common subsequence.
  2. Given an array with numbers, write a program that efficiently answers queries of the form: “Which is the nearest larger value for the number at position i?”, where distance is the difference in array indices. For example in the array [1,4,3,2,5,7], the nearest larger value for 4 is 5. After linear time preprocessing you should be able to answer queries in constant time.
  3. Given two strings, write a program that outputs the shortest sequence of character insertions and deletions that turn one string into the other.
  4. Write a function that multiplies two matrices together. Make it as efficient as you can and compare the performance to a polished linear algebra library for your language. You might want to read about Strassen’s algorithm and the effects CPU caches have. Try out different matrix layouts and see what happens.
  5. Given a set of d-dimensional rectangular boxes, write a program that computes the volume of their union. Start with 2D and work your way up.

GUI

  • Write a program that displays a bouncing ball.
  • Write a Memory game.
  • Write a Tetris clone

Open Ended

  1. Write a program that plays Hangman as good as possible. For example you can use a large dictionary like thisand select the letter that excludes most words that are still possible solutions. Try to make the program as efficient as possible, i.e. don’t scan the whole dictionary in every turn.
  2. Write a program that plays Rock, Paper, Scissors better than random against a human. Try to exploit that humans are very bad at generating random numbers.
  3. Write a program that plays Battle Ship against human opponents. It takes coordinates as input and outputs whether that was a hit or not and its own shot’s coordinates.

Friday, 21 November 2014

5 Components of Multimedia

TEXT
It may be an easy content type to forget when considering multimedia systems, but text content is by far the most common media type in computing applications. Most multimedia systems use a combination of text and other media to deliver functionality. Text in multimedia systems can express specific information, or it can act as reinforcement for information contained in other media items. This is a common practice in applications with accessibility requirements. For example, when Web pages include image elements, they can also include a short amount of text for the user's browser to include as an alternative, in case the digital image item is not available. 

IMAGES 
Digital image files appear in many multimedia applications. Digital photographs can display application content or can alternatively form part of a user interface. Interactive elements, such as buttons, often use custom images created by the designers and developers involved in an application. Digital image files use a variety of formats and file extensions. Among the most common are JPEGs and PNGs. Both of these often appear on websites, as the formats allow developers to minimize on file size while maximizing on picture quality. Graphic design software programs such as Photoshop and Paint.NET allow developers to create complex visual effects with digital images. Related Reading: The Advantages of Using Multimedia in Web Design 

AUDIO 
Audio files and streams play a major role in some multimedia systems. Audio files appear as part of application content and also to aid interaction. When they appear within Web applications and sites, audio files sometimes need to be deployed using plug-in media players. Audio formats include MP3, WMA, Wave, MIDI and RealAudio. When developers include audio within a website, they will generally use a compressed format to minimize on download times. Web services can also stream audio, so that users can begin playback before the entire file is downloaded. 

VIDEO 
Digital video appears in many multimedia applications, particularly on the Web. As with audio, websites can stream digital video to increase the speed and availability of playback. Common digital video formats include Flash, MPEG, AVI, WMV and QuickTime. Most digital video requires use of browser plug-ins to play within Web pages, but in many cases the user's browser will already have the required resources installed. 

ANIMATION 
Animated components are common within both Web and desktop multimedia applications. Animations can also include interactive effects, allowing users to engage with the animation action using their mouse and keyboard. The most common tool for creating animations on the Web is Adobe Flash, which also facilitates desktop applications. Using Flash, developers can author FLV files, exporting them as SWF movies for deployment to users. Flash also uses ActionScript code to achieve animated and interactive effects.

What is Multimedia?

Multimedia can have a many definitions these include: Multimedia means that computer information can be represented through audio, video, and animation in addition to traditional media (i.e., text, graphics drawings, images). A good general definition is: Multimedia is the field concerned with the computer-controlled integration of text, graphics, drawings, still and moving images (Video), animation, audio, and any other media where every type of information can be represented, stored, transmitted and processed digitally. A Multimedia Application is an Application which uses a collection of multiple media sources e.g. text, graphics, images, sound/audio, animation and/or video. Hypermedia can be considered as one of the multimedia applications.

Sunday, 14 September 2014

What is the Difference Between a Search Engine and a Directory?

A search engine, such as Yahoo or Google, is an online tool that helps users of the Internet find the sites and information they're looking for. Most search engines use automated programs (sometimes called spiders) to look for relevant information based on keywords entered by the user.

A search directory, such as Yahoo Directory, is a catalog of websites organized by category to allow users to easily browse for the information they need. Unlike search engines, which locate and display relevant information based on a formula or algorithm using an automated software program, search directories are organized by real people who discover new sites and relevant information by exploring the Internet themselves and by reviewing submitted sites.
Both search engines and directories can help drive customers to your website. Neither guarantees that your site will be included in their listings.

What is Node?

Definition: A node is any device connected to a computer network. Nodes can be computers, personal digital assistants (PDAs), cell phones, or various other network appliances. On an IP network, a node is any device with an IP address.

Impact of ICT in our daily life

As human being we are always attach with lot of essential things in our life. Jobs, education,retailing, banking these are the compulsory things in our life. It was very hard to get in touch with these before technology changed our life and made it easier for us. It has contributed a lot to  exchange our life from writing a letter which could take one month to arrive to the receiver to writing an e-mail which can be received by the receiver in just one minute, from going to the shop to choose and buy things to choose and buy using E-commerce and no one even needs to go to the shop to collect their goods. Sticking with the book for whole day can be very amusing for the students. Thanks to IT which introduced us to an innovative way of studying. Some of the topics are described in more details below which are changed because of IT.

Jobs-
Information and technology has helped a lot in the field of jobs. IT industry introduced some unique and rare jobs which wasn't very popular even in late 1980. This field has appeared as a solution to increase the number of employments and reduce the number of unemployment in our society. IT industry created a lot of job facilities for people who have skills in IT. It has created jobs like- Web developer, IT network administrator, computer game designer, IT technicians etc. IT industry also helped many people to become successful self-employer. For example-Steve Jobs who was the founder of Apple Inc. along with Ronald Wayne.  Bill Gates who is the founder of “Microsoft.” Mark Zuckerberg the founder of famous social networking site “Facebook.” This is also helpful because they have also employed people in their own company which is also part of IT industry.
It has not only created jobs for many people, but it has also taken away many jobs in the society. For example- now a days people like to buy their products online which has led to reduction in floor jobs. For example- Comet has gone into administration because it can’t cope with the online competition from different online shopping like Amazon and Ebay.
Education-
The technology helped us in our education as well. This has introduced the easiest way of learning and teaching for both students and the teachers. It has also introduced us to know about modern discoveries and also historical things as well. We can use internet every where to different books and also we can watch videos on the internet to get more ideas about the topic that we want to research on. Now a days we use projector in our school and other educational field to discuss the work with the whole class. 

We can also get ideas by reading blogs about different things and also discuss each others view about some topics that is related to the education using blogs. We can also ask question from our teacher using emails while we are at home which could be very important especially before the exam day and we can also research on the internet and we don't have to look at the books and find the right page. This saves lot of time for the students. We can also take help from our friends to learn in a collaborate environment.


Although there are some advantages of using IT in our education it also has some disadvantages as well. Now a days people relies on the Internet too much that they believe on everything that is written on the web page. It has also taken the jobs from the library as because most of the people rely on the internet library as because they can buy their favourite books on the internet. So libraries are shutting down because people are relying on the Internet library.

Crime and Policing-

IT has introduced a lot of things which prevents people committing crime. CCTV camera, GPRS system, using database for finding criminals' information are some unique thing which can not be possible without the blessing of IT. In common days police uses GPRS to track someone's car,mobile phone if it has been stolen. Police uses CCTV camera to detect criminals' face. Fingerprint is another especial method with which the police can identify the thieves. This is making our life safer and very easy in many ways. For example- in big super markets like ASDA or Tesco doesn't need to think about too much if someone tries to still their products, because some products have got chips which can be detected if that product isn't swiped over the bar code reader. 

They can also use CCTV cameras to help them protecting their products. 

The main disadvantage created by the technology system is that anyone who knows how to create program, they can hack others device using viruses, Phishing and also Malicious software. They can be very threatening as because they can take your information which can be very confidential for you. I.e. Your bank card. Sometimes people also delete others files to annoy people which can led someone to loose their important work as well.

Retailing

IT has impacted on Retailing and we are greatly enjoying the benefit of using IT on Retailing. We are using IT on Retailing which helps us to buy anything 24/7 everyday. We can use this facility to choose whatever we want  at any time we want. We can choose range of items on the internet and we don't even have to go to a place to choose whatever we want. We can also reserve the items on the internet. We can pay for the items on the internet with a safe internet payment option which is paypal. We can also choose products from different countries on the internet and buy them using the advantage of IT. IT also helped companies to make more money and spend less on their business. The company does not need to hire more staffs for the company. 
Although it has some advantage on Retailing but there are some disadvantage as well. It can sometimes become very discouraging for small shops as they can't compete with big supermarkets like Tesco which has both online shopping and normal shopping facility for the consumers. So they have to close their shops. Sometimes the customers can't get their necessary staffs when they needed because of the late delivery.

Health
When we get sick,we don't want to go to anywhere instead of staying at home. But we had to move on from that point and we had to forcefully take ourselves to the doctors. Taking appointment, talking to the receptionist, describing the problem we have and then then waiting for it, increases our illness. This is when IT comes to help us. Now a days we don't need to go to the doctor and describe our problems, we can use Internet to contact with our doctor. We can use also use IT to do face to face communication with our doctor even though we are at home. We can also frequently ask question to our doctors and they can also answer us using E-mails.
 We doesn't have to even take appointment to contact with our doctors and we can contact with our doctor whenever we want. We can also use this facility to learn about our disease and how to cure ourselves. We can search on the internet to research about the disease and the medicine we have to use to get better. It is also very helpful for those students who are studying to become doctors and also who like to know more about different kind of medicines. 

IT provides us with lot of advantages. But it also has some disadvantages. If someone uses computer for long time then they can get headache, it can also cause neck pain, can make them nothing apart from sitting in front of the computer. Some teenagers also puts too much time on their games instead of studying or taking part in different physical activities. Some people also gets stretch if they get bullied on the internet, which may stop them to go outside and they sometimes feel scared to talk to anybody. 


 Business

Communication is a very important technique which is used to make a business very famous. In earlier days, people used to communicate in a different way. They had to go to everyone's house to promote their products which could take a long time to promote their product. They sometimes used to take long journey so that they can deal with someone and they can expand their business. Since technology has arrived,people still using the technique which is communication but they have changed the method of promoting their products or dealing  with someone who is far from one another. Instead of going to everyone's house separately, people are making advertisement, which not involves one area or a country but the whole world and we can also use IT to communicate someone who too far from each other. We can use e-mailing method to know more about our customers. They can also frequently ask us some questions related to our business. 



But sometimes we can't heavily rely on writing e-mails as because we can't sometimes share what we are feeling or what we are actually want to ask. So it becomes very compulsory for us to have face to face communication with them. This is when we exploit IT in our life. Video conferencing which assembled us together via internet. We can use this technique to communicate with someone face to face and we can use this benefit for meeting or if we are trying to work together with other company which can be situated in other countries. 

IT has also some negative effect on Business. We rely too much on technology and so we always put whatever we do in our computers. So it increases the cost of a company as the company needs to use LAN and WAN to expand their businesses. Our servers can also crash or get damaged and it can cost millions of pounds for the company to repair. The chance of loosing the whole companies files are random as well. It sometimes can make easier for hackers to break the firewall of the company and use it for their own purposes. So the company needs extra employer which is a network administrator who deals with these things and therefore the company has to pay him as well.


To learn more about video conferencing use this site.(http://en.wikipedia.org/wiki/Videoconferencing)


Money and banking

IT has also showed its beneficial points on money and banking which helped us a lot to buy  necessary things using E-commerce which includes online shopping, online selling etc. It also helped lot of companies to deal with other companies. We can use online money and banking service 24/7 hours a day. Which means people can use this benefit whenever they want from any part of the world. We can also go to different countries and use our same banking account to take money or put money on our account. This is possible because of the WAN (Wide area Network.)  We can also get monthly statement using internet, so we can compare our statement every month and make our plan for upcoming months. We can also transfer money from one country to other buy using online banking. IT has also introduced us to an Eco-friendly world by using less papers for the money and banking. All the information can be stored in our computer and we don't have to worry about loosing important papers.
 
We sometimes face great problems using IT on Money and banking. There are lot of people who makes malicious software which are used to hack others information on the computer. So when someone stores their bank information on their computer, those hackers steals their information and use it for their own benefit. Some times it can happen to the whole company and as a result they can loose all of their consumers' data. For example- Natwest and Nationwide banks also faced this kind of problem. This cost them a lot to repair their servers. Their customers as a result lost their money and also their information. Phishing is another method used by those people to hack information using internet. The company also needs to hire lot of staffs who have IT skills which means  lot of money needs to be spend on staffs and computers to store customers information.

DNS - Domain Name System

Definition:
The DNS translates Internet domain and host names to IP addresses. DNS automatically converts the names we type in our Web browser address bar to the IP addresses of Web servers hosting those sites.
DNS implements a distributed database to store this name and address information for all public hosts on the Internet. DNS assumes IP addresses do not change (are statically assigned rather than dynamically assigned).
The DNS database resides on a hierarchy of special database servers. When clients like Web browsers issue requests involving Internet host names, a piece of software called the DNS resolver (usually built into the network operating system) first contacts a DNS server to determine the server's IP address. If the DNS server does not contain the needed mapping, it will in turn forward the request to a different DNS server at the next higher level in the hierarchy. After potentially several forwarding and delegation messages are sent within the DNS hierarchy, the IP address for the given host eventually arrives at the resolver, that in turn completes the request over Internet Protocol.
DNS additionally includes support for caching requests and for redundancy. Most network operating systems support configuration of primary, secondary, and tertiary DNS servers, each of which can service initial requests from clients. Internet Service Providers (ISPs) maintain their own DNS servers and use DHCP to automatically configure clients, relieving most home users of the burden of DNS configuration.

Define the difference between a URL and an IP address?

A URL, as stated before, is a name, designed for people to remember (IE yahoo.com). A DNS server is used to convert that name to an IP address, which is some odd number IE 209.191.93.52 which routers and computers understand that is used to forward your destination request to a computer IE a server at yahoo.com to send you a message/page back. After all, who on earth who be able to remember websites as a series of numbers (that's why we, as "normal people", use URLs instead of IP addresses)?!

So, in short:

The URL/"Domain Name" is something for you to remember
The IP is for the computer to use to send the message
The DNS is used to translate from the URL to IP address

Sunday, 23 March 2014

Practice for random numbers

This tutorial provides a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().
rand() and RAND_MAX
The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the <cstdlib> header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.
Here's a piece of code that will generate a single random number:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int random_integer = rand();
cout << random_integer << endl;
}

The value of RAND_MAX varies between compilers and can be as low as 32767, which would give a range from 0 to 32767 for rand(). To find out the value of RAND_MAX for your compiler run the following small piece of code:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
cout << "The value of RAND_MAX is " << RAND_MAX << endl;
}

srand()

The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.
We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we pass as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use (though not for serious statistical purposes).
In our earlier example the program would have generated the same number each time we ran it because the generator would have been seeded with the same default value each time. The following code will seed the generator with the system time then output a single random number, which should be different each time we run the program.

#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer = rand();
cout << random_integer << endl;
}

Don't make the mistake of calling srand() every time you generate a random number; we only usually need to call srand() once, prior to the first call to rand().

Generating a number in a specific range
If we want to produce numbers in a specific range, rather than between 0 and RAND_MAX, we can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand()%n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:

#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
for(int index=0; index<20; index++){
random_integer = (rand()%10)+1;
cout << random_integer << endl;
}
}

A better method, though slightly more complicated, is given below. This overcomes problems that are sometimes experienced with some types of pseudo random number generator that might be supplied with your compiler. As before, this will output 20 random numbers from 1 to 10.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;
}
}

If you need to use a pseudo random number generator for anything even remotely serious you should avoid the simple generator that comes with your compiler and use something more sophisticated instead. That said, rand() still has its place and you may find it useful.

my question is, for the functions on choosing random numbers in a specific range, what should i do to make the cout one by one?
As in, like the function given above, it gives the whole 20 outputs at once, but what i would like to do is to get the output one by one, how could i do that?
and let's say i have a range from 2 to N, what should i do to get the output only from 2 to N and not 0 to N?because what's given in the previous thread is a function to choose from 0 to N.
thank you :D

Random Numbers

Intro
This tutorial provides a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().
rand() and RAND_MAX
The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the <cstdlib> header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.
Here's a piece of code that will generate a single random number:
  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. int random_integer = rand();
  7. cout << random_integer << endl;
  8. }
The value of RAND_MAX varies between compilers and can be as low as 32767, which would give a range from 0 to 32767 for rand(). To find out the value of RAND_MAX for your compiler run the following small piece of code:
  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. cout << "The value of RAND_MAX is " << RAND_MAX << endl;
  7. }
srand()
The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.
We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we pass as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use (though not for serious statistical purposes).
In our earlier example the program would have generated the same number each time we ran it because the generator would have been seeded with the same default value each time. The following code will seed the generator with the system time then output a single random number, which should be different each time we run the program.
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. srand((unsigned)time(0));
  8. int random_integer = rand();
  9. cout << random_integer << endl;
  10. }
Don't make the mistake of calling srand() every time you generate a random number; we only usually need to call srand() once, prior to the first call to rand().
Generating a number in a specific range
If we want to produce numbers in a specific range, rather than between 0 and RAND_MAX, we can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand()%n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. srand((unsigned)time(0));
  8. int random_integer;
  9. for(int index=0; index<20; index++){
  10. random_integer = (rand()%10)+1;
  11. cout << random_integer << endl;
  12. }
  13. }
A better method, though slightly more complicated, is given below. This overcomes problems that are sometimes experienced with some types of pseudo random number generator that might be supplied with your compiler. As before, this will output 20 random numbers from 1 to 10.
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4. using namespace std;
  5. int main()
  6. {
  7. srand((unsigned)time(0));
  8. int random_integer;
  9. int lowest=1, highest=10;
  10. int range=(highest-lowest)+1;
  11. for(int index=0; index<20; index++){
  12. random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
  13. cout << random_integer << endl;
  14. }
  15. }
Conclusion
If you need to use a pseudo random number generator for anything even remotely serious you should avoid the simple generator that comes with your compiler and use something more sophisticated instead. That said, rand() still has its place and you may find it useful.

Wednesday, 19 March 2014

Reserved words

The syntax rules (or grammar) of C++ define certain symbols to have a unique meaning within a C++ program. These symbols, the reserved words, must not be used for any other purposes. The reserved words already used are int and void. All reserved words are in lower-case letters. The table below lists the reserved words of C++. C++ Reserved Words
andand_eqasmautobitand
bitorboolbreakcasecatch
charclassconstconst_castcontinue
defaultdeletedodoubledynamic_cast
elseenumexplicitexportextern
falsefloatforfriendgoto
ifinlineintlongmutable
namespacenewnotnot_eqoperator
oror_eqprivateprotectedpublic
registerreinterpret_castreturnshortsigned
sizeofstaticstatic_caststructswitch
templatethisthrowtruetry
typedeftypeidtypenameunionunsigned
usingvirtualvoidvolatilewchar_t
whilexorxor_eq
Some of these reserved words may not be treated as reserved by older compilers. However you would do well to avoid their use. Other compilers may add their own reserved words. Typical are those used by Borland compilers for the PC, which add nearfarhugecdecl, and pascal.
Notice that main is not a reserved word. However, this is a fairly technical distinction, and for practical purposes you are advised to treat maincin, and cout as if they were reserved as well.

Variables, Types and Expressions

This document is part of the HTML publication "An Introduction to the Imperative Part of C++" The original version was produced by Rob Miller at Imperial College London, September 1996. Version 1.1 (modified by David Clark at Imperial College London, September 1997) Version 1.2 (modified by Bob White at Imperial College London, September 1998) Version 1.3, 1.4, 2.0, ..., 2.12 (modified by William Knottenbelt at Imperial College London, September 1999-September 2013) 2. Variables, Types and Expressions 2.1 Identifiers As we have seen, C++ programs can be written using many English words. It is useful to think of words found in a program as being one of three types: Reserved Words. These are words such as if, int and else, which have a predefined meaning that cannot be changed. Here's a more complete list. Library Identifiers. These words are supplied default meanings by the programming environment, and should only have their meanings changed if the programmer has strong reasons for doing so. Examples are cin, cout and sqrt (square root). Programmer-supplied Identifiers. These words are "created" by the programmer, and are typically variable names, such as year_now and another_age. An identifier cannot be any sequence of symbols. A valid identifier must start with a letter of the alphabet or an underscore ("_") and must consist only of letters, digits, and underscores. (BACK TO COURSE CONTENTS) 2.2 Data Types Integers C++ requires that all variables used in a program be given a data type. We have already seen the data type int. Variables of this type are used to represent integers (whole numbers). Declaring a variable to be of type int signals to the compiler that it must associate enough memory with the variable's identifier to store an integer value or integer values as the program executes. But there is a (system dependent) limit on the largest and smallest integers that can be stored. Hence C++ also supports the data types short int and long int which represent, respectively, a smaller and a larger range of integer values than int. Adding the prefix unsigned to any of these types means that you wish to represent non-negative integers only. For example, the declaration unsigned short int year_now, age_now, another_year, another_age; reserves memory for representing four relatively small non-negative integers. Some rules have to be observed when writing integer values in programs: Decimal points cannot be used; although 26 and 26.0 have the same value, "26.0" is not of type "int". Commas cannot be used in integers, so that (for example) 23,897 has to be written as "23897". Integers cannot be written with leading zeros. The compiler will, for example, interpret "011" as an octal (base 8) number, with value 9. (BACK TO COURSE CONTENTS) Real numbers Variables of type "float" are used to store real numbers. Plus and minus signs for data of type "float" are treated exactly as with integers, and trailing zeros to the right of the decimal point are ignored. Hence "+523.5", "523.5" and "523.500" all represent the same value. The computer also accepts real numbers in floating-point form (or "scientific notation"). Hence 523.5 could be written as "5.235e+02" (i.e. 5.235 x 10 x 10), and -0.0034 as "-3.4e-03". In addition to "float", C++ supports the types "double" and "long double", which give increasingly precise representation of real numbers, but at the cost of more computer memory. Type Casting Sometimes it is important to guarantee that a value is stored as a real number, even if it is in fact a whole number. A common example is where an arithmetic expression involves division. When applied to two values of type int, the division operator "/" signifies integer division, so that (for example) 7/2 evaluates to 3. In this case, if we want an answer of 3.5, we can simply add a decimal point and zero to one or both numbers - "7.0/2", "7/2.0" and "7.0/2.0" all give the desired result. However, if both the numerator and the divisor are variables, this trick is not possible. Instead, we have to use a type cast. For example, we can convert "7" to a value of type double using the expression "static_cast(7)". Hence in the expression answer = static_cast(numerator) / denominator the "/" will always be interpreted as real-number division, even when both "numerator" and "denominator" have integer values. Other type names can also be used for type casting. For example, "static_cast(14.35)" has an integer value of 14. (BACK TO COURSE CONTENTS) Characters Variables of type "char" are used to store character data. In standard C++, data of type "char" can only be a single character (which could be a blank space). These characters come from an available character set which can differ from computer to computer. However, it always includes upper and lower case letters of the alphabet, the digits 0, ... , 9, and some special symbols such as #, £, !, +, -, etc. Perhaps the most common collection of characters is the ASCII character set (see for example Savitch, Appendix 3 or just click here). Character constants of type "char" must be enclosed in single quotation marks when used in a program, otherwise they will be misinterpreted and may cause a compilation error or unexpected program behaviour. For example, "'A'" is a character constant, but "A" will be interpreted as a program variable. Similarly, "'9'" is a character, but "9" is an integer. There is, however, an important (and perhaps somewhat confusing) technical point concerning data of type "char". Characters are represented as integers inside the computer. Hence the data type "char" is simply a subset of the data type "int". We can even do arithmetic with characters. For example, the following expression is evaluated as true on any computer using the ASCII character set: '9' - '0' == 57 - 48 == 9 The ASCII code for the character '9' is decimal 57 (hexadecimal 39) and the ASCII code for the character '0' is decimal 48 (hexadecimal 30) so this equation is stating that 57(dec) - 48(dec) == 39(hex) - 30(hex) == 9 It is often regarded as better to use the ASCII codes in their hexadecimal form. However, declaring a variable to be of type "char" rather than type "int" makes an important difference as regards the type of input the program expects, and the format of the output it produces. For example, the program #include using namespace std; int main() { int number; char character; cout << "Type in a character:\n"; cin >> character; number = character; cout << "The character '" << character; cout << "' is represented as the number "; cout << number << " in the computer.\n"; return 0; } Program 2.2.1 produces output such as Type in a character: 9 The character '9' is represented as the number 57 in the computer. We could modify the above program to print out the whole ASCII table of characters using a "for loop". The "for loop" is an example of a repetition statement - we will discuss these in more detail later. The general syntax is: for (initialisation; repetition_condition ; update) { Statement1; ... ... StatementN; } C++ executes such statements as follows: (1) it executes the initialisation statement. (2) it checks to see if repetition_condition is true. If it isn't, it finishes with the "for loop" completely. But if it is, it executes each of the statements Statement1 ... StatementN in turn, and then executes the expression update. After this, it goes back to the beginning of step (2) again. We can also 'manipulate' the output to produce the hexadecimal code. Hence to print out the ASCII table, the program above can be modified to: #include using namespace std; int main() { int number; char character; for (number = 32 ; number <= 126 ; number = number + 1) { character = number; cout << "The character '" << character; cout << "' is represented as the number "; cout << dec << number << " decimal or " < #include using namespace std; int main() { float number; cout << "Type in a real number.\n"; cin >> number; cout.setf(ios::fixed); // LINE 10 cout.precision(2); cout << "The square root of " << number << " is approximately "; cout << sqrt(number) << ".\n"; return 0; } Program 2.3.1 This produces the output Type in a real number. 200 The square root of 200.00 is approximately 14.14. whereas replacing line 10 with "cout.setf(ios::scientific)" produces the output: Type in a real number. 200 The square root of 2.00e+02 is approximately 1.41e+01. We can also include tabbing in the output using a statement such as "cout.width(20)". This specifies that the next item output will have a width of at least 20 characters (with blank space appropriately added if necessary). This is useful in generating tables. However the C++ compiler has a default setting for this member function which makes it right justified. In order to produce output left-justified in a field we need to use some fancy input and output manipulation. The functions and operators which do the manipulation are to be found in the library file iomanip (old header style iomanip.h) and to do left justification we need to set a flag to a different value (i.e. left) using the setiosflags operator: #include #include #include using namespace std; int main() { int number; cout << setiosflags ( ios :: left ); cout.width(20); cout << "Number" << "Square Root\n\n"; cout.setf(ios::fixed); cout.precision(2); for (number = 1 ; number <= 10 ; number = number + 1) { cout.width(20); cout << number << sqrt( (double) number) << "\n"; } return 0; } Program 2.3.2 This program produces the output Number Square Root 1 1.00 2 1.41 3 1.73 4 2.00 5 2.24 6 2.45 7 2.65 8 2.83 9 3.00 10 3.16 (In fact, the above programs work because "cout" is an identifier for an object belonging to the class "stream", and "setf(...)", "precision(...)" and "width(...)" are member functions of "stream". Don't worry too much about this for now - you will learn more about objects, classes and member functions later in the object-oriented part of the course.) (BACK TO COURSE CONTENTS) 2.4 Declarations, Constants and Enumerations As we have already seen, variables have to be declared before they can be used in a program, using program statements such as float number; Between this statement and the first statement which assigns "number" an explicit value, the value contained in the variable "number" is arbitrary. But in C++ it is possible (and desirable) to initialise variables with a particular value at the same time as declaring them. Hence we can write double PI = 3.1415926535; Furthermore, we can specify that a variable's value cannot be altered during the execution of a program with the reserved word "const": Enumerations Constants of type "int" may also be declared with an enumeration statement. For example, the declaration enum { MON, TUES, WED, THURS, FRI, SAT, SUN }; is shorthand for const int MON = 0; const int TUES = 1; const int WED = 2; const int THURS = 3; const int FRI = 4; const int SAT = 5; const int SUN = 6; By default, members of an "enum" list are given the values 0, 1, 2, etc., but when "enum" members are explicitly initialised, uninitialised members of the list have values that are one more than the previous value on the list: enum { MON = 1, TUES, WED, THURS, FRI, SAT = -1, SUN }; In this case, the value of "FRI" is 5, and the value of "SUN" is 0. (BACK TO COURSE CONTENTS) Where to put Constant and Variable Declarations Generally speaking, it is considered good practice to put constant declarations before the "main" program heading, and variable declarations afterwards, in the body of "main". For example, the following is part of a program to draw a circle of a given radius on the screen and then print out its circumference: (There is no need to type in this program) #include using namespace std; const float PI = 3.1415926535; const float SCREEN_WIDTH = 317.24; int drawCircle(float diameter); /* this is a "function prototype" */ int main() { float radius = 0; cout << "Type in the radius of the circle.\n"; cin >> radius; drawCircle(radius * 2); cout.setf(ios::fixed); cout.precision(2); cout << "The circumference of a circle of radius " << radius; cout << " is approximately " << 2 * PI * radius << ".\n"; return 0; } int drawCircle(float diameter) { float radius = 0; if (diameter > SCREEN_WIDTH) radius = SCREEN_WIDTH / 2.0; else radius = diameter / 2.0; ... ... } After the definition of "main()", this program includes a definition of the function "drawCircle(...)", the details of which need not concern us here (we can simply think of "drawCircle(...)" as a function like "sqrt(...)"). But notice that although both "main()" and "drawCircle(...)" use the identifier "radius", this refers to a different variable in "main()" than in "drawCircle(...)". Had a variable "radius" been declared before the "main" program heading, it would have been a public or global variable. In this case, and assuming there was no other variable declaration inside the function "drawCircle(...)", if "drawCircle(...)" had assigned it the value "SCREEN_WIDTH / 2.0", "main()" would have subsequently printed out the wrong value for the circumference of the circle. We say that the (first) variable "radius" is local to the main part of the program, or has the function main as its scope. In contrast, it usually makes sense to make constants such as "PI" and "SCREEN_WIDTH" global, i.e. available to every function. In any case, notice that the program above incorporates the safety measure of echoing the input. In other words, the given value of "radius" is printed on the screen again, just before the circumference of the circle is output. (BACK TO COURSE CONTENTS) 2.5 Assignments and Expressions Shorthand Arithmetic Assignment Statements We have already seen how programs can include variable assignments such as number = number + 1; Since it is often the case that variables are assigned a new value in function of their old value, C++ provides a shorthand notation. Any of the operators "+" (addition), "-" (subtraction), "*" (multiplication), "/" (division) and "%" (modulus) can be prefixed to the assignment operator (=), as in the following examples (mostly copied from Savitch, Section 2.3): Example: number += 1; total -= discount; bonus *= 2; time /= rush_factor; change %= 100; amount *= count1 + count2; Equivalent to: number = number + 1; total = total - discount; bonus = bonus * 2; time = time / rush_factor; change = change % 100; amount = amount * (count1 + count2); The first of the above examples may written in even shorter form. Using the increment operator "++", we may simply write number++; The operator "++" may also be used as a prefix operator: ++number; but care must be taken, since in some contexts the prefix and postfix modes of use have different effects. For example, the program fragment x = 4; y = x++; results in "x" having the value 5 and "y" having the value 4, whereas x = 4; y = ++x; results in both variables having value 5. This is because "++x" increments the value of "x" before its value is used, whereas "x++" increments the value afterwards. There is also an operator "--", which decrements variables by 1, and which can also be used in prefix or postfix form. In general, assignment statements have a value equal to the value of the left hand side after the assignment. Hence the following is a legal expression which can be included in a program and which might be either evaluated as true or as false: (y = ++x) == 5 It can be read as the assertion: "after x is incremented and its new value assigned to y, y's value is equal to 5". (BACK TO COURSE CONTENTS) Boolean Expressions and Operators Intuitively, we think of expressions such as "2 < 7", "1.2 != 3.7" and "6 >= 9" as evaluating to "true" or "false" ("!=" means "not equal to"). Such expressions can be combined using the logical operators "&&" ("and"), "||" ("or") and "!" ("not"), as in the following examples: Expression: (6 <= 6) && (5 < 3) (6 <= 6) || (5 < 3) (5 != 6) (5 < 3) && (6 <= 6) || (5 != 6) (5 < 3) && ((6 <= 6) || (5 != 6)) !((5 < 3) && ((6 <= 6) || (5 != 6))) True or False: false true true true false true The fourth of these expressions is true because the operator "&&" has a higher precedence than the operator "||". You can check the relative precedence of the different C++ operators in a C++ programming manual or text book (see for example Savitch, Appendix 2). But if in doubt use ( ) parentheses, which in any case often make the program easier to read. Compound Boolean expressions are typically used as the condition in "if statements" and "for loops". For example: ... ... if (total_test_score >= 50 && total_test_score < 65) cout << "You have just scraped through the test.\n"; ... ... Once again, there is an important technical point concerning Boolean expressions. In C++, "true" is represented simply as any non-zero integer, and "false" is represented as the value 0. This can lead to errors. For example, it is quite easy to type "=" instead of "==". Unfortunately, the program fragment ... ... if (number_of_people = 1) cout << "There is only one person.\n"; ... ... will always result in the message "There is only one person" being output to the screen, even if the previous value of the variable "number_of_people" was not 1. (BACK TO COURSE CONTENTS) 2.6 Summary In this lecture we have discussed variables in more detail. We have seen how variables are always of a particular data type, and have listed different ways in which variables may be temporarily or permanently assigned values. We have also seen how new values of various types can be generated by the use of operators. The material here is also covered in more detail in Savitch, Chapter 2, and Sections 4.2 and 4.5. Exercises