PLAY AND WIN

click the image below to play more games

Tuesday, November 10, 2009

Computer Graphics

Introduction
Computer graphics are images displayed or animated on a computer screen. Applications of
computer graphics are widespread and growing rapidly. For instance, computer-aided design is
an integral part of many engineering processes. The entertainment industry has made the most
spectacular use of computer graphics–from the special effects in King Kong to the Nintendo
Wii.
Most interactive computer software for business and industry makes use of computer graphics
including screen displays, desktop publishing, and slide production for commercial and education
presentations. Consequently, most students studying a computer language spend some time
learning how to use two-dimensional (2D) graphics, and maybe three dimensional (3D) graphics.
2 Transformations in 2D
We begin by examining some of the basic mathematics used to manipulate and display graphical
images such as a letter of the alphabet. Such an image consists of a number of points, connected
lines or curves, and information about how to fill closed regions bounded by the lines and
curves. Often, curved lines are approximated by short straight-line segments, and a figure is
defined mathematically by a list of points.
The capital letter N can be determined by eight points, or vertices. The coordinates of the
points can be stored in a data matrix D. In addition to D, it is necessary to specify which
vertices are connected by lines, but we will omit this detail for now.
The main reason graphical objects are described by a collection of straight-line segments is that
the standard transformations in computer graphics map line segments onto other line segments.
Once the vertices that describe an object have been transformed, their images can be connected
with the appropriate straight lines to produce the compete image of the original object.
1. On graph paper, carefully draw the letter N. Construct a data matrix D containing the
eight points or vertices from your drawing. Include in your report a picture of your letter
N.
1
2. Given a matrix A =  1 .25
0 1 , describe the effect of left multiplication by A on the letter
N. Include in your report a picture of the letter N after the transformation by A.
3. In the previous question, the N looks a bit too wide after the transformation by the
matrix A. to compensate, multiply (on the left) the coordinates of the letter obtained in
the previous question by the matrix S =  .75 0
0 1 . Include a picture of this letter N
in your report and describe with a short sentence the effect of left multiplication by the
matrix S.
There are three different ways we can move an object to another location. The first way
is by translation. We can translate points in the xy-plane to a new position by adding
translation amounts to the coordinates of the points. For example, we translate the point
(x, y) by moving dx units parallel to the x-axis and by dy units parallel to the y-axis to
the new point (x′, y′). Then x′ = x + dx and y′ = y + dy.
4. Translate your original letter N by 3 units to the right and 2 units up. Include a picture
of the translated letter N in your report, and describe in a short sentence the effect of this
translation on the original letter N.
Points can also be scaled (stretched) by sx along the x-axis and by sy along the y-axis into
a new point by the multiplications x′ = sx · x and y′ = sy · y.
5. Scale your original letter N by 1/2 in x and 1/4 in y. Now scale the original letter N by 2
in x and 4 in y. Include a printout of both scaled letters and describe in a short sentence
the effect of these transformations on the original letter N.
6. In the previous question, what matrices A and B would produce the effects of the trans-
formations on the letter N when the matrix D is multiplied on the left by A or B?
Points can also be rotated through an angle  about the origin. Let (x, y) denote a point
in the plane that we wish to rotate through the angle , and let (xr, yr) denote the new
point after the rotation. Our first objective is to calculate the new coordinates in terms
of the old ones. Let b denote the length of the line segment from (0, 0) to (x, y) and
denote the angle between the x-axis and this line. Then x = b cos( ) and y = b sin( ).
Similar formulas give us xr and yr in terms of the angle  + .
2
7. Find formulas for xr and yr similar to those given for x and y in terms of the angle  + .
Use trigonometric identities to rewrite these formulas in terms of the angles  and . Then
identify occurrences of x and y in these expressions, and rewrite the formulas to give xr
and yr in terms of x, y, and  only.
8. Rewrite this transformation (the rotation through the angle ) as left multiplication by a
matrix A, that is, find A so that A x
y  =  xr
yr . We will call A the rotation matrix for
the angle .
9. Test your result from the previous question by rotation the point (1, 0) through an angle
of 60◦. First, use some scratch paper and trigonometry to see what the answer should be.
Then let B be the 2×2 rotation matrix for the angle  of 60◦. Apply B to the appropriate
vector for the point (1, 0). Check that your matrix B gives the same result as the hand
calculation.
10. Repeat the preceding step with the point (0, 1).
11. Using your calculator, compute B6,B12,B18, and B24. Explain your results in terms of
rotations. In particular, how could you have predicted the particular matrices that your
calculator produced?
12. Let K be the 2 × 2 rotation matrix for a rotation of 15◦. Compute B2,K4,K2B,KBK
and BK2. Compare the results and explain what you see.
13. Explain why the product of any two 2 × 2 rotation matrices is another rotation matrix.
Illustrate your argument with a specific example.
14. In general, we know that matrix multiplication is not commutative; i.e., if A and B are
both n×n matrices, then usually AB is not the same as BA. However, rotation matrices
are a special case. Explain why, for any two 2D rotation matrices Q and R, it must follow
that QR = RQ. Then use B and K from the preceding step to illustrate your argument.
3 Homogeneous Coordinates
In Part 1, we saw that there were three types of transformations in 2D – translation, scaling,
and rotation. OF these three, scaling and rotation can be accomplished by left multiplication
of a 2 × 2 matrix. It turns out that translation cannot be accomplished by left multiplication
of a 2 × 2 matrix. WE would like to be able to treat all three transformations in a consistent
way, so that they can be combined easily. This can be done by expressing the points in homogeneous
coordinates. Homogeneous coordinates were first developed in geometry and have been
applied in graphics. Numerous graphics subroutine packages and display processors work with
homogeneous coordinates and transformations.
3
Each point (x, y) in the xy-plane can be identified with the (x, y, 1) on the plane in R3 that
lies one unit above the xy-plane. We say that (x, y) has homogeneous coordinates (x, y, 1). For
example, the point (0, 0) has homogeneous coordinates (0, 0, 1). Homogeneous coordinates for
points can be transformed via multiplication by 3 × 3 matrices.
1. What 3×3 matrix has the effect of translating the point (x, y) by dx units parallel to the
x-axis and by dy units parallel to the y-axis to the new point (x′, y′)? That is, find a 3×3
matrix A so that A

x
y
1

=

x′
y′
1

.
2. Repeat the previous question for scaling by sx along the x-axis and by sy along the y-axis.
3. Repeat for rotations through the angle .
The movement of a figure on a computer screen often requires two or more basic transfor-
mations. The compositions of such transformations corresponds to matric multiplication
when homogeneous coordinates are used. For the next three questions below, find 3 × 3
matrices that produce the described composite 2D transformation, using homogeneous
coordinates. Illustrate each composite 2D transformation on the image of a triangle with
data matrix D =  5 2 4
0 2 3 .
4. Translate by (3, 1) and then rotation 45◦ about the origin.
5. Translate by (−2, 3) and then scale the x-coordinate by .8 and the y-coordinate by 1.2.
6. Reflect points in the x-axis, and then rotate 30◦ about the origin.
7. Consider the following geometric 2D transformations: D a dilation (in which x-coordinates
and y-coordinates are scaled by the same factor), R a rotation, and T a translation. Does
D commute with R? In other words, is DR = RD for any rotation and dilation D? Does
D commute with T ? Does R commute with T ?
8. A rotation on a computer screen is sometimes implemented as the product of two shear-
and-scale transformations, which can speed up calculations that determine how a graphic
image actually appears in terms of screen pixels. (The screen consists of rows and columns
of small dots, called pixels.) The first transformation A1 translates vertically and then com-
presses each column of pixels; the second A2 translates horizontally and then stretches each
row of pixels, where A1 =

1 0 0
sin() cos() 0
0 0 1

and A2 =

sec() −tan() 0
0 1 0
0 0 1

. Us-
ing  = 30◦, apply A1 followed by A2 to the rectangle with data matrixD =  1 1 4 4
1 3 1 3 .
4
Show, for a given angle , that the composition of the two transformations is a rotation
in 2D.
4 3D Computer Graphics
Some of the newest and most exciting work in computer graphics is connected with molecular
modeling. With 3D graphics, a biologist can examine a simulated protein molecule and search
for active sites that might accept a drug molecule. The biologist can rotate and translate an
experimental drug and attempt to attach it to the protein. This ability to visualize potential
chemical reactions is vital to modern drug and cancer research. In fact, advances in drug design
depend, on some extent, upon progress in the ability of computer graphics to construct realistic
simulations of molecules and their interactions.
Current research in molecular modeling is focused on virtual reality, an environment in which a
researcher can see and feel the drug molecule slide into the protein. Another design for virtual
reality involves a helmet and glove that detects head, hand, and finger movements. The helmet
contains two tiny computer screens, one for each eye. Making this virtual environment more
realistic is a challenge to engineers, scientist, and mathematicians. The mathematics we will
examine barely opens the door to this interesting and important field of research.
In 3D, a point can be rotated about any one of the three axes. The 3d version of the 2d rotation
matrix A are given by: P =

cos() −sin() 0
sin() cos() 0
0 0 1

, Q =

1 0 0
0 cos() −sin()
0 sin() cos()

, and
R =

cos() 0 sin()
0 1 0
−sin() 0 cos()

.
The matrix P rotates a point in 3D about the z-axis, Q about the x-axis, and R about the
y-axis. These are not the only possible rotations in 3D, but we will limit our attention to these
possibilities for now.
1. What feature of each of the matrices above tells us quickly the axis about which the
rotation is being done?
2. We saw earlier that multiplication of 2D rotation matrices is commutative, even though
matrix multiplication in general is not commutative. We’ll try this for 3D rotation matri-
ces. Let P30 and P45 be the matrices for rotations of 30◦ and 45◦, respectively, around the
z-axis. Compute P30P45 and P45P30. What do you observe?
3. Now compute P30R45 and R45P30. what do you observe? Hold an object (such as your
textbook) out in front of you, and rotate it as indicated in these product matrices. Try to
convince yourself that what you observed mathematically is consistent with reality. Write
a couple of sentences to describe what you observed, both physically and mathematically.
5
4. Try to generalize what you computed in the preceding steps. In particular, are any 3D
rotation matrices multiplicatively commutative? If so, which ones?
5. Suppose an image is stored in computermemory as we described earlier–a set of coordinates
in 3D space. Assume that when the object is displayed on the screen, the x-axis is
perpendicular to the screen, the y-axis is horizontal, and the z-axis is vertical. Thus, the
yz-plane is on the surface of the screen. The software can perform rotations by multiplying
each point (as a vector) by an appropriate rotation matrix and then displaying the result.
If we want to display the object so that it is first flipped over from our right to our left,
and then the axis projected toward us is tilted upward 20◦, what matrix can the computer
use to do this transformation? Explain your reasoning, and compute the matrix.
5 Homogeneous Coordinates in 3D
Just as 2D transformation can be represented by 3 × 3 matrices, using homogeneous coordi-
nates, 3D transformations can be represented by 4×4 matrices, providing we use homogeneous
coordinate representations of points in 3-space as well. By analogy with the 2D case, we say
that (x, y, z, 1) are homogeneous coordinates for the point (x, y, z).
In the first four questions below, give the 4×4 matrix for performing the indicated translations
in 3D.
1. Rotation about the y-axis through an angle of 30◦.
2. Translation by (−6, 4, 5).
3. Scaling by (−6, 4, 5).
4. Rotation about the z-axis through an angle of −30◦, and then translates by (5,−2, 1).
5. Illustrate the effects of the above transformations on the triangle with vertices (4.2, 1.2, 4),
(6, 4, 2), and (2, 2, 6).

aap ki nazron ne samjha pyar ke kabil mujhey


old is gold
Full Remix Song - Aapki Nazaron ne Samajha - Ba...

Bollywood Old songs, Bollywood Old movies & albums from Dishant Home of Indian Music Rare Old Hindi Songs By Classic Movie Club Listen to your favourite Hindi, Punjabi, Pakistani, Ghazals, Pop, Filmi, and Bhangra songs in Real Audio and MP3 format. Over 1000 of songs Old Hindi Songs, Bollywood Songs, Hindi Movie Film Music, Videos ...
Listen to all Old Hindi Songs, Bollywood Songs, Hindi Movie Film Music, Videos, Mp3 Songs, download MP3 songs, lyrics and watch videos Music ranging from Old melodies, Classical music and Ghazals to latest hot hits, MP3s, ... Click Here for 'Hot Hits' and listen to latest Film Songs vintage Telugu songs: Film, Light, Folk .. We plan to post old songs, in batches, updated every old hindi songs asha bhosle old song old songs geeta dutt old folk songs old telugu songs lata old songs old songs 2009 old song lyrics

Monday, November 9, 2009

» Google AdSense
Google AdSense is a fast and easy way for website publishers of all sizes to display relevant, unobtrusive Google ads on their website's content pages and earn money. Because the ads are related to what your users are looking for on your site, you'll finally have a way to both monetize and enhance your content pages.

It's also a way for web site publishers to provide Google search to their site users, and to earn money by displaying Google ads on the search results pages.
The program is free, and combines pay-per-click and pay-per-impression advertising - meaning you get paid for valid clicks on the ads on your site or search results pages as well as impressions on your content pages. So go ahead and try this program. If you comply with this program policies, just complete online application and select either or both of AdSense for content pages and AdSense for search. One application gets you approved for both AdSense and AdSense for search - you can decide to use any combination of these products on your pages.

Google will review your application and follow up with an email within 2-3 days. If you are accepted into the program, you can log in to your new account and get the HTML code to insert into your web pages.

Earning Types: CPC, CPM, CPA
Payment: Check, EFT
Ad Types: Text, Image and Video based ads are available. Different ads on will pay different CPCs (EG Debt Consolidation CPCs might be $5 while game site CPCs might be $0.02)
payout: %40 - %70

following these simple rules will help keep your account in good standing:
1.Don't click on your own Google ads.
2.Don't ask others to click on Google ads.
3.Don't employ pop-up prompts or automatic software installations.
4.Be aware of how your site is promoted.
5.Don't place Google ads on sites that contain prohibited content.
6.Respect Google trademarks.
7.Don't tamper with the AdSense code.
8.Provide a positive user experience.
9.Provide a good environment for advertisers.
10.Be responsive.
11.Do not mask ad elements.
12.Do not place more than 3 ad units and 3 ad links or 2 adsense search boxes on any web page.
13.Do not run competitive contextual text ad or search services on the same site.
14.Never launch a New Page for clicked ads by default.
15.Place ads only on Content Pages.
16.Do not alter the results after ad clicks or searches




» Link Worth
LinkWorth is one of the web's largest and most innovative marketing portals that caters to both Advertisers and Partners.
They have a multitude of products and services to fill your every online marketing need.
They products consist of text link ads, paid blog reviews, in-text links, in-content pay per click ads, rotating text ads, hosted content pages, article submission, directory submission and many more.
We highly reccomend checking out Linkworth and see if you can increase your web traffic and revenue.

LinkWorth for Advertisers:

* Buy ads and increase traffic, visibility and search positions
* SEO/SEM Consulting, Reputation Management
* Article Distribution, Directory Submission, Press Releases, Custom Content & more
* Huge inventory of publishers growing daily
* Perfect backend for Agencies to White Label or Add-on to existing services
* Use our Control Center to manage one or all of your accounts with one login

LinkWorth for Partners:

* Sell ads and monetize your site with relatively little maintenance
* Earn up to 70% of ad revenue recurring monthly in most situations
* Get paid to blog and write reviews for products & services
* Tons of advertisers, from Fortune 500 to small businesses
* The more websites you list, the more money you earn
* Manage all of your published ads and websites with our Control Center


Payment: Check, Wire transfer, Paypal
payout: %70
minimums: Partner websites must be complete with working pages and links between pages. Submissions must be a unique domain that is owned by the Webmaster and easily maintained. Listings that reside on free web servers that result in long and confusing subdirectory URLs will be declined.


Visit LinkWorth and Get More Details


» Chitika eMiniMalls
More than 12000 bloggers and publishers are already using Chitika's ads to earn revenue.
Earning Types: CPC
Payment: Check, Wire transfer, Paypal
payout: %60
minimums: English website/blog, minimum 3000 visits/month
Ad Types:

* eMiniMalls
Chitika's flagship product, eMiniMalls brings pay-per-click product promotion to life on the web. It provides visitors with relevant content and comparative shopping information without even leaving your site.
* Related Products Unit (RPU)
RPU is a simple, non-intrusive text link format that integrates right in to your content, requiring minimal design changes. The RPU is a PPC (pay-per-click) unit designed to complement rather than cannibalize revenue from other ad networks.
* ShopLincs
ShopLinc gives you the power to create your own personalized shopping experience for your audience. Your expert reviews will be featured alongside the products you choose to endorse!
* ShopCloud$
Display popular products in an interactive tag cloud format where each product is linked to cost-per-click (CPC) search results featuring deals, promotions and offers from hundreds of name brand merchants.
* Owna
Showcase one of thousands of products in any of five Ownas on your blog, website or myspace! OWNA's are available in different skins to provide diverse looks.
* Linx
Chitika | Linx will automatically identify key products/keywords mentioned in the content on a website or blog and hyperlink (double underline) those keywords to interactive paid (CPC-based) product listings featuring best deals, offers and promotions from name brand merchants. When users mouse-over these links, a small bubble-like scroll over is revealed listing offers from merchants.


Visit Site and Get More Details


» Widget Bucks
WidgetBucks is a shopping widget that you can place on your website or blog. You earn money every time someone clicks on it. just like Google Adsense, They pay-per-click (PPC). also They are claiming an amazing $3-$6 CPM on widgets, about three times that of traditional ad networks.

the widgets’ content is contextually based according to your site’s content. From there, readers and site visitors can see various information regarding certain products, such as the lowest price available, and from which online retailer.

There are about 5 or so different widget sizes to choose from, and they are all fairly customizable in terms of color, to be better matched with your existing website. a “grab it” option will soon be made available for its widgets, enabling visitors to take the widgets to be placed on their own site.

widgetbucks 300x250 pixels ad

In order to encourage you to sign up or the WidgetBucks program, it’s offering you a $25 credit, meaning you’ll only need to earn another $25 to get your first payment. The shopping widgets are a bit flashy and very much resemble an ad.

Earning Types: CPC, CPM
Payment: Check, Paypal
payout: about $0.3-$6 eCPM
minimums: English website/blog
Ad Types:
770x90 leaderboard widget can earn up to a $7.28 eCPM
160x600 skyscraper widget can get up to a $6.05 eCPM
300x250 rectangle widget can earn up to a $5.50 eCPM
660x330 custom widget can earn up to a $4.65 eCPM
468x60 banner widget can earn up to a $4.50 eCPM
Visit WidgetBucks and Get More Details




Terms :
CPA is Cost Per Acquisition, CPC is Cost Per Click, CPM is Cost Per 1000 Ads Displayed (where M is the Roman letter for 1000), eCPM is effective rate of CPM for CPC based Ads.

Monday, November 2, 2009

Super Bike Game

Sunday, November 1, 2009

JavaScript

JavaScript cookies are stored in the document.cookie object and are created by assigning values to this object. When creating a cookie, you typically specify a name, value, and expiration date and time for that cookie. The cookie will then be accessible in your scripts every time the user returns to your site until the cookie expires. These cookies will also be sent to your server every time the user requests a page from your site. The simplest way to create a cookie is to assign a string value to the
document.cookie object, which looks like this:
name=value;expires=date


video of basic javascript

Cookie management in web technology

A cookie management system serves as a central storage location for information and other data on users. A user's machine contains a cookie having a key and the cookie management system associates user information with this key. Upon receiving a request from a user, a web site retrieves the key from the user's machine and queries the cookie management system for the user information. The cookie management system retrieves the data associated with the key and returns the user information to the site. The sites therefore do not need to store information on all users nor do they need to place their own cookies on the user's machine. If sites obtain more data about a user during an interaction, the sites send this data to the cookie management system which updates its database. The user's machine may contain multiple cookies that correspond to different people and the site can prompt the user to select the appropriate one. The cookies may correspond to the same user and specify different amounts or categories of information. The user may supply a password to enable sites to access their data from the cookie management system.

JavaScript cookies are stored in the document.cookie object and are created by assigning values to this object. When creating a cookie, you typically specify a name, value, and expiration date and time for that cookie. The cookie will then be accessible in your scripts every time the user returns to your site until the cookie expires. These cookies will also be sent to your server every time the user requests a page from your site. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
name=value; expires=date

<head>

<script language=”JavaScript”>

document.cookie = “myCookie=” + escape(“This is my
Cookie”);

</script>

</head>

Monday, October 26, 2009





Untitled Document



CS102: Topic #2 - Variables and Expressions


The topic of variables is one of the most important in C or any other high-level programming language.


We will start with an example.  Here is a simple, totally useless example of a variable in use:


#include <stdio.h>


int main(void)

{

int x;


x = 5;

printf("The value of x is %d.\n", x);

return 0;

}


In this example, "x" is the name of a variable.  The line "int x;" is an example of a local declaration.  We are declaring that "x" is the name of a variable of type "int" which stands for "integer".  So "x" can take on integer values.  When the computer sees a declaration like this, it sets aside a space in memory to store the value of the variable.  The line "x = 5;" sets the value of "x" to 5.  We've previously seen "printf" used to print just strings.  The %d is a special code that causes the "printf" function to fill in to this part of the string with an integer value specified after the string.  If an integer variable appears after the string, the value of that variable is printed out.  You could also include a constant.  If the value 5 is used instead of the variable "x", the output of this program would be the same.  Either way, it causes the string "The value of x is 5." to be printed on its own line.


Technically speaking, a variable is a named memory location.  Every variable has a type, which defines the possible values that the variable can take, and an identifier, which is the name by which the variable is referred.


 


In order to use a variable in a C program, you must first declare it.  You declare a variable with a declaration.  As in the example shown above, a declaration of a variable consists of the variable’s type followed by the variable’s name and then a semicolon.  There must be whitespace between the type and the name.  It is also possible to declare multiple variables on one line, as we’ll see later.


You probably have some notion of a variable from algebra.  In algebra, most variables are single letters, like "x" or "y".  These are acceptable variable names in C also, but when programming in C, you often you use several characters to create descriptive variable names.  Here are the rules that bind possible variable names, or identifiers, in C:


Rules for identifiers:



  1. The first character must be an alphabetic character (lower-case or capital letters) or an underscore ‘_’.

  2. All characters must be alphabetic characters, digits, or underscores.

  3. The first 31 characters of the identifier are significant.  Identifiers that share the same first 31 characters may be indistinguishable from each other.

  4. Cannot duplicate a reserved word.  A reserved word is one that has special meaning to C.


Valid identifiers:

x

Name

first_name

name2

_maxInt


Invalid identifiers:

2name             /* Can’t start with number */

first name       /* Can’t use ‘ ’ */

first-name       /* Can’t use ‘-’ */

int                    /* Can’t use reserved word */


The type, or data type, of a variable determines a set of values that the variable might take and a set of operations that can be applied to those values.


Four standard data types provided for by C are:

int – used for variables that can take on numeric integer values.

char – used for variables that can take one character from the computer’s "alphabet" as a value.  Most computers use the American Standard Code for Information Interchange (ASCII) alphabet.

float – used for variables that can take on numeric values with a fractional part.

void – used mainly for functions that don’t take any parameters or functions that don’t return a value.


In addition to these basic types, there are modifiers that you can apply to the types.  For instance, you can specify that a variable is a signed int (one that can take both positive and negative values) or an unsigned int (one that can only take positive values).


Remember that a variable is a named memory location.  Memory of a computer is divided into bytes.  A byte is a sequence of 8 bits.  A bit is a 0 or a 1.  The number of bytes that a variable occupies in memory determines the number of possible values that it can take.  C does not specify the size of an integer variable.  Most computers today use 32 bit integers (4 bytes), although until recently, many used 16 bit integers (two bytes).  One way to control the size of an integer variable is to specify that it is a short int (16 bits) or a long int (32 bits).


Let’s say that an integer uses 4 bytes, or 32 bits, of memory.  Then there are 2^32 possible values that this variable can take (corresponding to the 2^32 possible combinations of 0’s and 1’s).


A 32 bit integer can have 2^32 = 4,294,967,296 possible values.

A signed 32 bit integer can have values ranging from –2,147,483,648 to 2,147,483,647.

An unsigned 32 bit integer can gave values ranging from 0 to 4,294,967,295.


A 16 bit integer can have 2^16 = 65,536 possible values.

A signed 16 bit integer can have values ranging from –32,768 to 32,767.

An unsigned 16 bit integer can have values ranging from 0 to 65,535.


A character, or "char", occupies just one byte of memory.  Remember 1 byte = 8 bits, so there are only 2^8 = 256 possible characters.  As mentioned above, the "alphabet" used by most computers is the ASCII alphabet.  There are actually only 128 characters defined in standard ASCII, corresponding to the numbers from 0 to 127.  So characters with values between 128 and 255 won’t be consistent from computer to computer.


Here are some of the important ranges within the ASCII character set:

48 – 57: the digits ‘0’ through ‘9’

65 – 90: the capital letters ‘A’ through ‘Z’

97 – 122: the lowercase letters ‘a’ through ‘z’


Here is a simple, useless example of a program using a character variable:


#include <stdio.h>


int main(void)

{

char x;


x = ‘Q’;

            printf("The value of x is %c.\n", x);

            return 0;

}


This program prints out the string "The value of x is Q." on its own line.


There are two ways to specify a character in C.  A simple character that appears on the keyboard can usually be specified by just typing the character within single quotes, like in this example.  The other way is to specify it with a number, the number whose ASCII code represents the character.  Remember that the range from 65 to 90 in ASCII represents the capital letters.  This means that 81 represents Q.  So an equivalent statement to "x = ‘Q’;" would be "x  = 81".  Because x is declared to be a "char", the computer knows that the 81 represent the letter Q.


Notice that instead of "%d", the "printf" string now contains a "%c", which means that the value that gets printed in its place should be considered a character.  If a "%d" were used in the program, it would print "The value of x is 81."!


In C, the ‘=’ symbol is an assignment operator.  It causes the computer to evaluate the expression to the right of the ‘=’ and assign the value of the expression to the variable to the left of the ‘=’.  So let’s say that x is an integer.  The statement "x = 5;" will set the value of the variable named x to 5.  This is different than the use of ‘=’ in algebra, in which it is used to express a fact.  In algebra, if you see the following two lines:


x = 5;

x = 7;


They would express a contradiction.  In C, this is perfectly valid.  The first statement sets the value of x to 5.  The second resets the value of x to 7.  The value of x is no longer 5.  In fact, if these two statements appear right next to each other in a C program with nothing in between, the first of the two statements is useless, but perfectly valid.


The expression to the right of the ‘=’ doesn’t have to be a single constant.  It could be a mathematical expression, possibly containing variables.  In the following examples, we’re going to assume that x and y are integer variables.  The following statement is valid:


x = 2 * (3 + 99) / 20;


Since x is declared to be an integer, and the expression to the right of ‘=’ evaluates to 204 / 20 which is 10.2, the final value of x will be 10.  The fractional part of the expression is cut.


The following statement is also valid:


x = y + 5;


In this case, the value of x will be 5 more than the value of y.


Here is another valid statement:


x = x + 1;


In algebra, if you ever derive a formula like this, it either means that you made a mistake or that there was a contradiction between other formulas somewhere.  In C, this is a perfectly valid and very common statement.  Remember, the expression to the right of the equal sign is evaluated first, and its value is then assigned to the variable to the left.  So if x equals five when this statement is first reached, the expression to the right of ‘=’ evaluates to 6, and the value of 6 is assigned back to x.


Here is a non-valid statement:


x + 1 = 10;


In algebra, you could solve this and discover that x = 9.  In C, this is not valid.  You can not assign a value to the quantity "x+1".  Only variables can appear to the left of ‘=’.


Now consider one of the previous programs with an extra line:


#include <stdio.h>


int main(void)

{

char x;


x = ‘Q’;

x = x + 9;

            printf("The value of x is %c.\n", x);

            return 0;

}


Since "x" is a character, the statement "x = ‘Q’;" is equivalent to "x = 81".  The new value of x after the statement "x = x + 9;" will be 90, which is the ASCII code for a capital Z.  So this program prints "The value of x is Z." to the screen on its own line.


There are some special characters that have special symbolic sequences set aside to represent them.  We've already seen one case of this; the newline character is represented by ‘\n’.  It is also number 10 in the ASCII chart.  So if x is a character, then the lines "x = ‘\n’;" and "x = 10;" are equivalent.  Some other special characters are:

\t          tab

\b         backspace

\a         bell

\’          single quote

\"         double quote

\\          backslash


Here is a simple example using a float.


#include <stdio.h>


int main(void)

{

float x;


x = 2.5;

x = x * 3;

            printf("The value of x is %f.\n", x);

            return 0;

}


Note the %f in the printf string, which means that the value that gets printed in its place should be considered a float.  This may not print exactly what you expect.  This program will print the string "The value of x is 7.500000." on its own line.  It is possible to control the format of how floats get printed, but that is a later topic.


When you have multiple variables of the same type, you can declare them with multiple lines or one line.  The following three lines:


int first;

int second;

int third;


is equivalent to the following one line:


int first, second, third;


Variable in C are not necessarily initialized automatically.  You should always initialize a variable before using its value.  The following program has unpredictable behavior:


#include <stdio.h>


int main(void)

{

int x;


            /* x is not initialized, its value is not predictable */

printf("The value of x is %d.\n", x);

            return 0;

}


Since x is never initialized, there is no way of predicting its value.


Variables can be initialized while they are declared.  So the following code at the start of a function:


int x;


x = 5;


is equivalent to:


int x = 5;


If you declare multiple variables with one line and want to initialize all of them, you must specify all of their values.  For example:


int x = 0, y = 0, z = 0;


If you just used:


int x, y, z = 0; /* Only z is initialized */


only z would be initialized.


Another operator that C recognizes is known as the modulus operator.  This operator returns the remainder when one operand is divided by another.  Here’s an example:


#include <stdio.h>


int main(void)

{

int operand1 = 22, operand2 = 5, quotient, remainder;


            quotient = operand1 / operand2;

            remainder = operand1 % operand2;

printf("When %d is divided by %d the quotient is %d and the remainder is %d.\n", operand1, operand2, quotient, remainder);

            return 0;

}


This program prints the string "When 22 is divided by 5 the quotient is 4 and the remainder is 2." to the screen on its own line.


This is the first example I’ve given in which the "printf" string includes more than one variable.  It’s pretty straightforward how this works.  All instances of a special symbols in the string get replaced with values given by the corresponding expressions or variables appearing after the string, in order, separated by commas.


Two other common operators are the increment and decrement operators.  The following statements:


++x;

x++;


are both equivalent to:


x = x + 1;


while

--x;

x--;


are both equivalent to:


x = x –1;


You will often see these operators used to increment or decrement a variable that is also being used as part of an expression.  If the operator appears before the variable, the variable’s final value is used in the expression.  If the operator appears after the variable, the variable’s original value is used in the expression.  For example;


x = 5;

y = x++;


After these two statements, y will equal 5 and x will equal 6.


x = 5;

y = ++x;


After these two statements, y will equal 6 and x will equal 6.


x = 5;

y = x--;


After these two statements, y will equal 5 and x will equal 4.


x = 5;

y = --x;


After these two statements, y will equal 4 and x will equal 4.


Notice that some of the expressions we’ve been using mix variables with constants.  So far, when we’ve used numerical constants, we just specified the number outright.  Sometimes, you may want to code common constants, such as pi, so that you don't have to type in the value multiple times.  There are at least two ways to do this.  One is to use the const qualifier in the declaration of a variable.  For example:


const float pi = 3.14159;


Of course,  this is not the exact value of pi, but an approximation!


The variable pi can now be used in expressions like any other float variable, but the value can never be changed.  If your program tries to change it, the compiler will notice and give you an error.


Here is an example:


#include <stdio.h>


int main(void)

{

const float pi=3.14159;

int radius = 5;


printf("The approximate circumference of a circle with radius %d is %f.\n", radius, 2*pi*radius);

            return 0;

}


This program prints "The approximate circumference of a circle with radius 5 is 31.415901." to the screen.


Another way to do it is to use the preprocessor command "#define".  The "#define" preprocessor command causes the compiler to replace all instances of specific text with other text.  Here is an example of its use:


#include <stdio.h>


#define PI 3.14159


int main(void)

{

int radius = 5;


printf("The approximate circumference of a circle with radius %d is %f.\n", radius, 2*PI*radius);

            return 0;

}


Two things to note here:  First, there is no semicolon at the end of the "#define" line.  If there were, the semicolon would get added along with the 3.14159 wherever you see PI in the code, and this would cause an error.  Second, using "#define" can lead to some weird errors.  For instance, let’s say you define "PI" like here, and then later you try to name a variable "SPICE".  The PI would be replaced with 3.14159 by the compiler, and this would lead to an error.


Two other topics related to expressions are those of precedence and associativity.


The precedence of operators determines the order in which different operators are evaluated when they occur in the same expression.  Operators of higher precedence are applied before operators of lower precedence.


Consider the statement:


x = 2 * (140 + 60) / 20;


The precedence of multiplication and division are higher than the precedence of addition, but the precedence of parentheses is highest of all.  So the value of "x" will be 20.


If the statement was written without the parentheses:


x = 2 * 140 + 60 / 20;


Then the value of "x" will be 283.


The associativity of operators determines the order in which operators of equal precedence are evaluated when they occur in the same expression.  Most operators have a left-to-right associativity, but some have right-to-left associativity.


Here are some more examples.  Assume that x is an int:


x = 5 - 2 * 7 - 9;


The ‘*’ has a higher precedence than ‘-’ so it is evaluated first, and the statement is equivalent to:


x = 5 – 14 – 9;


The minus has left-to-right associativity, so the statement is equivalent to:


x = -18;


Also, the ‘=’ has lower precedence than either ‘-’ or ‘*’ or any other operator, and this is how C enforces the rule that the expression to the right of the ‘=’ gets evaluated first and then the resulting value gets assigned to the variable to the left of the ‘=’.


The ‘=’ itself is one of the few operators that has right-to-left associativity.  The following is actually a valid C statement, assuming that "x", "y", and "z" are integers:


x = y = z = 7;


This statement assigns the value of 7 to "z" first, then to "y", and then to "x". 


If ‘=’ was given left-to-right associativity, the old value of "y" would be assigned to "x", then the old value of "z" would be assigned to "y", and then the value of 7 would be assigned to "z".  This is pretty counter-intuitive, and that’s why ‘=’ was given right-to-left associativity!