0% found this document useful (0 votes)
23 views

2 - Variables, User Input, Math Functions

Uploaded by

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

2 - Variables, User Input, Math Functions

Uploaded by

Simon Rizvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Data Types – this covers the full range of available Variable Types

Variable Type Meaning Range of Values Relative size inBytes

char character -128 - 127 1


unsigned char short integer 0 – 255 1
int integer -32,768 - 32,767 2
unsigend int integer 0 to 65,1535 2
long long integer -2,147,483,648 to 2,147,483,647 2
unsigned long unsigned long integer 0 to 4,294,967,295 2
float floating point 3.4 E +/- 38 (7 digits) 4
double double floating point 1.7 E +/- 308 (15 digits) 4

Field Type Format Specifiers Used by printf() following % sign

Character Argument Resulting Output

d integer Signed decimal integer


i integer Unsigned decimal integer
o integer Unsigned octal integer
u integer Unsigned decimal integer
x integer Unsigned hex. integer using lowercase letters
X integer Unsigned hex. integer using uppercase letters
f floating point Signed floating point number
e floating point Signed floating point number using e notation
E floating point Signed floating point number using e notation
g floating point Signed decimal number using either e or f form
whichever is shorter
G floating point Signed decimal number using either e or f form
whichever is shorter
c character A single character
s string Prints character strings
% none Prints the % sign

Note: use a lower case L in front of d, I, o, u, x and X to print long integers

Escape Sequences

Sequence Meaning Sequence Meaning

\n New line \f Form feed


\t Tab \' Single Quotation Mark
\b Backspace \" Double Quotation Mark
\r Carriage return \\ Backslash
\xdd ASCII code for hexadecimal (eg. \x41 equals 'A') where dd is a decimal
number
\ddd ASCII code in octal (eg. \101 equals 'A') where ddd is a decimal number
PRG155 Getting User input Week 2

Entering numerical values

To enter a number use the scanf( ) command.

To input an integer use the following:

int x; // declare an integer variable x


printf(“Please enter an integer: “); // tell the user what to do (prompt)
scanf(“%i”, &x); // read the value entered
// NOTE: you must use “&” before the variable

To input a floating point value use the following:

float y;
printf(“Please enter a float value => “); // prompt
scanf(“%f”, &y); // read the value entered, note again the use of “&”
// NOTE: when READING a value do not use %5.2f, just %f

NOTE: Although you can enter multiple values in one scanf statement (by puttng a
space between numbers to be entered) it is confusing for the user. Therefore, use one
prompt and one scanf for each value to be entered.

To enter numbers in exponential notation use %f for input and enter the number as:

123.456e4 or 1.23e-3 or something similar

To print values in exponential notation use the following:

float z = 12.3e6;
printf(“%.2e”, z); // this will print 1.23e7
or printf(“%.4E”, z); // this will print 1.2300E7
Initializing characters and strings

A variable has a name and a content (value).


The content has a particular format.

char letter = 'A'; /* declaring and initializing a character variable */


char name[] = "Michael"; /* a string is a group of characters */
printf("%c %s ", letter, name);

fflush(stdin); /* needed to prevent input errors when entering characters


by first flushing the input buffer before using a scanf(),
gets(), getch() and getchar() */

Input buffer

Keyboard
Memory

Inputting characters

1. char x; // declare a character variable


printf(“Please enter a character: “); // tell the user what to do
fflush(stdin); /* needed to prevent errors if another character entered earlier */
scanf(" %c", &x); /* user must hit a key and then hit the Enter key */
printf(" \n%c", x); /* user will see two characters on the screen, the one
he entered and the one printed */

3. char x;
printf(“Please enter a character: “);
fflush(stdin); /* needed to prevent errors if another character entered */
x = getch(); /* user hits a key to enter value for x, no need for Enter */
printf("%c", x); /* user only sees the character that's printed */

4. char x;
printf(“Please enter a character: “);
fflush(stdin);
x = getche(); /* user hits a key to enter value for x, no need for Enter */
printf("%c", x) /* user sees two values, one that he entered and the
printed one - NOTE the e at the end of getche() means echo (show) the
character entered*/

5. char x;
printf(“Please enter a character: “);
fflush(stdin); // Visual C++ requires the use of fflush(stdin) before getchar()
x = getchar(); /* user hits a key to enter value for x, AND Enter */
printf("%c", x); /* user sees two values, one that he entered
and the printed one */

Note:
Try each of these ways of entering characters and note the differences.
Inputting strings

Note: When entering strings you MUST NOT use &. The Ampersand

1. char x[ ] = "good morning"; /* Example of a string – note use of " " */


/* the [ ] indicates that a string will be */
/* stored */

2. char x[30]; /* set aside 30 memory locations to store string x */


printf(“Please enter a sentence: “); //prompt to the user
fflush(stdin);
gets(x); /* user can enter more than one word – hit Enter to end */
printf(" %s", x); /* this can print all the words entered, to 10 char's */

3. char x[30]; /* set aside 30 memory locations to store x */


` printf(“Please enter a sentence: “); //prompt to the user
fflush(stdin);
scanf("%s", x); /* enter ONE WORD and hit Enter to finish */
printf("%s", x); /* this will print only the first word entered even if
more than one word is entered
NOTE: with string input you don’t use & */

Getting input and printing characters and strings

#include<stdio.h>
main()
{
char letter; /* declare letter to be of type char. Can hold ONE character */
char name[20]; /* the square bracket indicates that up to 20 (in this case)
characters can be entered for variable “name”. */
printf("Please enter a letter and hit Enter ");
fflush(stdin); /* this command is used to clear the buffer and avoid input
errors. */
scanf(" %c", &letter);

printf("Please enter a word ");


fflush(stdin);
scanf(" %s", name); /* to enter a word*/
printf(“\n%c %s", letter, name); /* print a character followed by a string */
fflush(stdin);
getch();
}
To keep display open use:

getch(); /* Keeps output window open until user hits a key to continue OR */
getchar(); /* but with getchar() you must use the Enter key after a key is hit or
just hit Enter. Use fflush(stdin); before getchar(); */
Storing Characters

How does the computer store characters and strings, when all data is stored in binary
form using 0s and 1s?

Characters are stored as numbers, where a character is converted to its ASCII code
equivalent. Check the Appendix in your book for ASCII codes. Do NOT memorize
them.

The standard character set is converted to numbers ranging from 0 to 127. For
example, an A is converted to 65, B to 66, C to 67 and so on. Here is an example of how
a character is saved and how it is printed.

char x = 'A' // the decimal value of A is stored as binary 65 in location assigned to x.

If we now print the value of x, the value printed will depend on the format that is
specified in the print statement.

printf("%c", x); /* prints an A which is the ASCII equivalent of 65 */

However if you print x as an integer,

printf("%i", x); /* will print 65 the ASCII value of A stored at x */

And printing x as a hexadecimal value,

printf("%x", x); /* prints 41, the Hexadecimal value of A */

More on Strings

A string is simply a series of characters and is stored as a series of ASCII values in


memory, one byte of memory assigned to each character in sequence.

char val[ ] = "Hello"; /* sets aside 6 bytes to val and (five for Hello and one
for the null character at the end of the string */

Address Char Decimal


Number Value (ASCII value of the character)
x H 72 x is any address chosen by the computer
x+1 e 101 x + 1 is the next memory address and so on
x+2 l 108
x+3 l 108
x+4 o 111
x+5 /0 0 The zero (null character) indicates the end of a string

NOTE: You do not need to memorize ASCII values and the information is presented
only to help you understand how characters are stored.
Sample Program 1.

/* Program to calculate the sum of two integers */

#include<stdio.h>
main()
{
int x, y, total;
printf("Please enter an integer: ");
scanf("%i", &x);
printf("\nPlease enter another integer: ");
scanf("%i", &y);
total = x + y;
printf("The sum of %i and %i = %i", x, y, total);
getch();
}

Sample Program 2

/* Program to input and print strings and characters */

#include<stdio.h>

main()
{
char first_name[20], last_name[10], initial;
printf("Please enter your first name: ");
fflush(stdin);
scanf("%s", first_name); // allows input of one word
printf("\nPlease enter your last name: ");
scanf("%s", last_name);
printf("\nPlease enter your middle initial: ");
fflush(stdin); // use before charcter input
scanf(" %c", &initial); // allows input of one character

printf("\n\tYour name is: %s %c. %s", first_name,


initial, last_name); // Note: a statement can go over two lines.
printf("\n\nHit enter to continue");
fflush(stdin);
getch();
printf("\n\nPlease enter your full name including middle initial: ");
fflush(stdin); // Use before character or string input
gets(first_name); // allows input of multiple words.
printf("\n\tYour full name is: %s", first_name);
getch();

}
Doing Math in C.

The following are called OPERATORS. They’re used to carry out math operations.

Addition: +
Subtraction: -
Multiplication: *
Division: /
Remainder: % Modulus operator

Example: x = 7 % 2 gives a value of 1. The remainder after you divide 7 by 2


Modulus operator can only be used with integers

Order of operations. PEMDAS


Parenthesis, Exponents, Multiplication, Division, then Add and Subtract – left to right

Use brackets () where possible to avoid ambiguity or you may get errors.

If you need to enter very large numbers you need to use exponential notation.

For example, 1000 can be written as or 1E3 or 1e3 in C.

You may initialize a floating point value as follows:

float x = 1.23e23; // this equals 1.23 x 1023

Using Exponential Notation - Example

#include<stdio.h>
main()
{
float x;
printf("Please enter a floating point number: ");
scanf("%f", &x);
printf("\nYou entered %.2e", x);
getch();
}
The user can enter a number as 12345.678 or as 12.345678e3

The output in either case will be 1.23e4 which in mathematical form is 1.23x104
More math functions

#include<math.h> /* use the math.h header file for the following functions

log ( ) returns the logarithm of the double valued argument

value = log ( 3) returns the value 0.47712

pow (x.y) returns the value of xy

value = pow ( 2, 3 ) returns the value 8

sqrt ( c) returns the square root of a positive number

value = sqrt ( 9.0 ) return the value of 3.00000


You may use int, float, long or double types

abs( ) returns the absolute value of an integer

v = abs ( y );

labs( ) returns the absolute value of along integer

rand ( ) returns a random integer value

v = rand( ); will generate a random integer between 1 and ? try it.

trigonometric functions - sin, cos, tan, asin, acos, atan as in:

angle = cos( .5) /* where the argument is given in radians */


/* result is pi/3 */

remember 2 * Pi = 360 degrees

Originated by: Professor Gabriel Heti


Updated by: Professor A. Bagherian, September 2013

You might also like