[go: up one dir, main page]

0% found this document useful (0 votes)
65 views8 pages

Overview: Fundamentals of C, Part 1: Some Simple C Programs

This document provides an overview of a simple C program that calculates the area of a rectangle given its length and width. It discusses: 1. The program declares integer variables for the length, width, and area of a rectangle. It initializes the length and width variables. 2. An assignment statement calculates the area by multiplying the length and width variables and stores the result in the area variable. 3. The program uses printf statements to output the length, width, and calculated area to the screen. When compiled and executed, the program will output the length, width, and calculated area of the rectangle to the screen based on the initial length and width variable values.

Uploaded by

Ryhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views8 pages

Overview: Fundamentals of C, Part 1: Some Simple C Programs

This document provides an overview of a simple C program that calculates the area of a rectangle given its length and width. It discusses: 1. The program declares integer variables for the length, width, and area of a rectangle. It initializes the length and width variables. 2. An assignment statement calculates the area by multiplying the length and width variables and stores the result in the area variable. 3. The program uses printf statements to output the length, width, and calculated area to the screen. When compiled and executed, the program will output the length, width, and calculated area of the rectangle to the screen based on the initial length and width variable values.

Uploaded by

Ryhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

A simple C program

Overview: Fundamentals of C, part 1 What happens when you compile this program?
What happens when you execute (or run) this program?
• Some simple C programs /* Date: 18/01/2014 Version: 1.0 */
/* Program to calculate the area of a rectangle, given its length and width */

• C program syntax: identifiers, datatypes, punctuation #include <stdio.h> /* definition of printf and scanf */

int main()
• Arithmetic operators {
int length=3; /* declare and initialise length to 3 */
int width=4; /* declare and initialise width to 4 */
int area;; /* declare area,, no initialisation */

/* Calculate the area of the given rectangle */


area = length * width; /* now area has the value 12 */

/* Output the data and results to the screen */


printf("Length is %d\n",length); /* output: Length is 3 */
printf("Width is %d\n",width); /* output: Width is 4 */
printf("Area is %d\n"
%d\n",area);
area); /* output: Area is 12 */
return 0;
1 } 2

A simple C program – variables


Write source code
using an Editor
int length=3;
• This is the declaration of a variable called length, of type
area.c Compiler tries to
translate the program int (meaning: only holds integer values), and at the same time
i iti li i length
initialising l th with
ith the
th value
l 3
success
(you can choose
the filename)
• Variables are a veryy important
p concept
p in C. In order to pprocess
a.out (you can choose the filename) data, we need a way of storing and referring to the data. Using
variables, we can store data values in memory, and then use them in
subsequent
b e e t statements
t te e t whenhe the data
d t is
i to
t be processed.
e ed
Run Program Length is 3
(once it is loaded Width is 4
into memory) Area is 12
• A variable declaration reserves a memoryy location of the
appropriate size in which the variable’s data can be stored. In order
(how it appears to know how much memory to reserve, the computer needs to
on your screen) know what type of data (integer,
(integer floating-point,
floating point …)) will be stored.
stored
3 4
A simple C program – variables (contd.) A simple C program – assignment statement

• recall: a variable in C has a name (called its identifier), a area = length * width;
memory location where it is stored,
stored a type,
type and a value:
• the interpretation of this statement is: get the current values of the
• identifier should be meaningful
e.g. length instead of data1, x, etc. variables on the right-hand side, multiply these values, and store
the result in the variable on the left-hand
left hand side.
side
• identifier, type, and value -- you decide
• memory location -- the computer decides
• general syntax of an assignment statement:
• general syntax of a variable declaration: type name; varname = expression;
• type can be int, float, char, … • varname is an already-declared variable
• expression is a piece of code that evaluates to some value
• optional (but a good idea): initialise variable at declaration
•g
general syntax:
y type
yp name = value; the computer evaluates the current value of expression and
• value can be a constant, e.g. int length = 3; stores the result in varname, overwriting the current value of
varname
• value can refer to earlier variables, e.g. could have had
int area = length * width;
5 6

Assignment statement A simple C program – output to the screen


Warning: in C, the assignment operator = does NOT mean equals • how did the code printf("Length is %d\n",length);
(in the mathematical sense).
sense) It makes perfect sense to write p ("Width is %d\n
printf( \ ",
,width);
);
printf("Area is %d\n",area);
x = x * 2;
produce the screen output Length is 3
which is interpreted as: get the current value of x,
x multiply it by 2,
2
and store the result back in x. The effect is to double the value of x
Width is 4
Area is 12
?
What are the final values of x, y, and z in the following? • usually, everything inside the double quotes " " is written as-is to
the screen (the double quotes themselves are not).
int x = 4; int x = 4; • however,
h %d is
i a special
i l character
h sequence which
hi h tells
ll the
h
int y = 10; int y = x; computer to replace the %d with the value of the corresponding
int z = x; int z; integer variable when writing to the screen.
x = y; x = 2;
y = x; y = x; • \n is an escape sequence which tells the computer to start the
z = y * 3; next output on a new line.
• in order to use printf, need: #include <stdio.h>
7 8
A ssimple
peCpprogram
og – main()
a () Another simple C program
• recall: execution of a C program always starts with main() /* Date: 18/01/2014 Version: 1.0 */
//* Program to calculate the area of a circle
circle, given its radius *//
• main() is an example of a function in C. In general, programs can contain
a number of functions, each of which may be responsible for implementing a #include <stdio.h> /* definition of printf and scanf */
small ppart of the overall algorithm.
g #define PI 3.1415927 /* definition of constant value for  */

• Example: write one function to get data input, one function for data int main(void)
{
output, and one or more functions to process the data. Then activate
int diameter = 3; / declare and initialise diameter to 3 *//
/*
functions in the correct order to solve the problem! float radius = diameter/2.0; /* declare and initialise radius to 1.5 */
float area = PI * radius * radius; /* declare and calculate area */
• the function main() is activated by the computer’s Operating System
(OS) when the program is run.
run /* Output the data and results to the screen */
printf("Diameter is %d\n", diameter); /* output: Diameter is 3 */
• void main(void) means: main() receives no input data from printf("Radius is %.2f\n", radius); /* output: Radius is 1.50 */
the OS before the start of program execution, and returns no output data printf("Area
printf( Area is %.4f\n",area);
%.4f\n ,area); //* output: Area is 7.0686 *//
to the OS at program termination.
return 0;
• the statements that make up a function are called the body of the function, }
and are enclosed in braces { }
9 10

Another simple C program – a more detailed look Another simple C program – importance of variables
• since radius could in general have a fractional part, it is • could have written the previous program like this:
declared as a float
int main(void)
•area must also be declared as a float, since in general it is {
gp
also a floating-point number. float radius = 3 / 2.0; /* declare and initialise radius to 1.5 */
fl t area = PI * radius
float di * radius;
di /* declare
d l and
d calculate
l l t area */
• What happens if you declare them as int instead? (rest as before)
Answer: their fractional parts are truncated (not rounded).
(i.e.
(i e dropped diameter and replaced it with its value 3). 3) This
• PI is defined as a constant, so program can’t change it. Makes results in more compact code and gives the same result as before.
the program more readable for us – computer doesn’t care! However, the above code is more difficult to understand.
• printf("Area is %.4f\n",area); means that the • variables make programs easier to read, debug, & understand.
floating-point variable area is to be written to the screen with 4
places of decimals (rounding is used if needed – as in this case). • a program can change the value off a variable i while
i the
• %.4f is a placeholder which specifies the format in program is running. The programs we’ve examined so far
which
hi h the
th corresponding
di variable
i bl area will
ill be
b output.
t t haven’t
ave t do
donee so, but we
we’ll see eexamples
a p es oof tthiss later…
ate …
11 12
Another simple C program – integer division C program syntax
• float radius=diameter/2.0; why 2.0 and not 2? • when viewed as a typed document, a natural language (e.g.
English) document consists of:
• answer: diameter and 2 are both integers, and according words
to C, the result of dividing one integer by another is also an punctuation
i
integer – even if that
h means truncating
i the
h result
l (i.e.
(i dropping
d i special symbols
the fractional part). spaces and blank lines
• if we had radius=diameter/2 , the value of radius
• when viewed as a typed document, a C program consists of:
would be 1 (3/2 = 1.5, then drop the fractional part).
keywords
• but if any of the quantities involved are floating-point, then identifiers
the entire calculation is done using floating-point arithmetic. punctuation
We can “force”
force the computer to do this by making one of the comments
quantities of type float: this is why we had 2.0 instead of 2 spaces and blank lines

13 14

C keywords and identifiers Datatypes in C


• C keywords: words which have special meaning to the compiler and are • a datatype defines a set of values and a set of operations on those values
essentially the ‘building
building blocks
blocks’ of the language.
language These include • operations: comparison of values, arithmetic operations, …
break, continue, else, enum, float, int, do, case … • some standard C datatypes are predefined
(this is only a partial list – see any C text for more keywords) e.g. float, double, int, long, short, char
• when choosing an identifier (e.g. a variable name), you can only use • float and double are for real numbers
uppercase and lowercase letters, the digits 0—9, and the underscore _ • int, long, and short are for integers (i.e. whole numbers)
• further restrictions on choosing an identifier: • char is used for characters
• must start with a letter or _
• followed by any mixture of letters, digits, and _ • a constant in C is simply a specific value:
• cannot beb a C keyword
k d 7 (the integer value 7)
• also: maximum recommended identifier length = 31 characters 2345 (the integer value 2345)
4.2 ((the floating-point
gp value 4.2))
• examples of invalid identifiers: 3letter,
3letter int,
int Hello!,
Hello! air-temp
air temp
'a' (the character ‘a’)
• examples of valid identifiers: letter3, letter_3, _letter3 "abcdef" (the character string “abcdef”)
• remember: C is case
case-sensitive
sensitive – letter and Letter are different

15 16
Datatypes in C (contd.) Datatypes in C (contd.)

Data Type: int, long, short • floating-point can represent both integer and non-integer values
• not all
ll integers
i can be
b represented,
d due
d to finite
fi i memory constraints
i e g 1.0,
e.g. 1 0 0.05,
0 05 91.1
91 1
e.g. int: 2 bytes wide, ranging from 215 to (2151) Scientific notation: 1.0100, 5.0102, 9.11101 (mantissa  power of 10)
long: 4 bytes wide, ranging from 2231 to (2311)
1) Exponential notation: 11.0e0,
0e0 5.0e
5 0e22, 99.11e1
11e1
short: 1 byte wide, ranging from 128 to 127 • number of digits the computer allows for the decimal part of the mantissa
(on some computers, int gets 4 bytes, and/or short gets 2 bytes) determines the precision of the floating-point representation.
• number of digits the computer allows for the exponent determines the
Data Type: float, double range of the floating-point representation.
• represents
t reall numbers
b
• integral part and fractional part separated by decimal point
float: for single
single-precision
precision floating point numbers
double: for double-precision floating point numbers
• float and double are datatypes for real numbers but do not
include all of them, again due to memory constraints
17 18

The char datatype


Datatypes in C (contd.) • represents individual character value: letter
letter, digit,
digit special symbol e.g.
eg +$.,@
• A single character constant is enclosed in single quotes e.g. 'A', 'b', '1', ' '
• datatype hierarchy: double high
float Character variables are typically assigned one byte of storage.
storage They are stored using a
long standard “encoding”, such as ASCII (American Standard Code for Information
int Interchange) or EBCDIC (Extended Binary Coded Decimal Interchange Code). Both
short
h t are ways of assigning each character to a unique byte sequence of 1 1’ss and 0
0’ss.
l
low
Examples: ASCII for ‘Z’ is 01011010, ASCII for ‘4’ is 00110100. In decimal: ASCII
for ‘Z’ is 90, ASCII for ‘4’ is 52.
• no information is lost if a value is moved to a higher-order datatype, e.g.
double x;
Characters can be treated as integers! Each char is stored using these binary
x=10;
codes just like integers, and so we can manipulate them in the same way that we can
After this assignment, x has the value 10.0
manipulate other integers:
char c = 'a'; /* OR: char c = 97 */
• information may be lost if a value is moved to a lower-order datatype, e.g. while (c <= 'z') { /* OR: while (c <= 122) */
int a; ; printf("%c",
printf( %c , c);
a=12.8; c++;
After this assignment, a has the value 12 (due to truncation). }
p
Produces the screen output: abcdefghijklmnopqrstuvwxyz
g j pq y
This works because in ASCII, a-z follow each other in sequence (so do 0-9 and A-Z)
19 20
Punctuation in C C program layout
 Semi-colon ; --every C statement must end with ; • the C compiler doesn’t care about spaces, indentation, identifiers, line
breaks,, and other features of pprogram
g layout…
y
 Full-stop
F ll t or “d “dot”
t” . --usedd as the
th decimal
d i l pointi t for
f reall numbers.
b
#include <stdio.h>
 Comma , --used to separate elements of a list. For example we #define CON1 0.88288
can declare a number of variables at the same time ((if theyy are all main() {float v1,v2;printf("Enter the value of the product in Sterling: ");scanf("%f",&v1);
v2=v1/CON1;printf("That equals %.2f Euro.\n",v2);}
of the same type):
int celsius,fahrenheit,count; • … but people do! equivalent
 Single
Si l quote t ' --usedd to
t indicate
i di t single
i l characters.
h t
#include <stdio.h>
 Double quote " --used to indicate strings (sequences of #define CONVERSION_RATE 0.88288
characters).
) main()
 Braces { } --used to group a number of statements into a single, {
float value_sterling, value_euro;
compound statement.
 Parentheses ( ) --used
sed to group
gro p certain items such
s ch as arguments
arg ments printf( Enter the value of the product in Sterling: ");
printf("Enter );
scanf("%f",&value_sterling);
to functions, or to indicate the order of calculation in arithmetic
value_euro=value_sterling/CONVERSION_RATE;
expressions.
printf("That equals %.2f Euro.\n",value_euro);
}
21 22

Arithmetic operators in C Arithmetic operators in C (contd.)


+ (addition) • Examples:
- (subtraction)
* (multiplication) rectarea = length * width;
/ ((division – value of 3/2.0
/ is 1.5,, value of 3/2
/ is 1 circarea = radius * radius * PI;
Also: value of 2/7 is 0) root1 = (-b + sqrt(b*b-4*a*c))/(2.0*a);
% (remainder – value of 5%2 is 1, value of 4%2 is 0,
 parentheses used to explicitly order arithmetic:
value of 2%7 is 2)
w = x - y / z; expression in parentheses
is evaluated ffirst.
W i
Warning: /b or a%b
a/b %b will
ill cause a run-time
ti error if b is
i 0 w = (x - y)/z;
nested parentheses: evaluated
w = x - (y/z);
 meaning: C compiler won’t see an error, but during from the inside out.
program execution,
i if the
h value
l off b is
i 0 when
h the h
 without parentheses: *, / before +, - and left-to-right
above division or remainder operations are applied, between operators with same precedence (e.g. * and / )
the program will fail.
fail
23 24
Arithmetic operators in C – Exercise Arithmetic operators in C – operator precedence
What is the assigned (left-hand side) value in each case? Given the radius of a sphere R, the volume of the sphere is (4/3)()(R3)
Suppose we have a statement float radius;
int s, m=3, n=5, r, t;
Which of the following C statements calculates this volume correctly, and why?
float x=3.0, y;
t = n/m; float vol = 4/3 * PI * radius * radius * radius; NO
r = n%m;
y = n/m; float vol = PI * radius * radius * radius * 4/3; YES
t = x*y-m/2; float vol = (4/3) * PI * radius * radius * radius; NO
x = x*2.0;
x 2.0;
s = (m+n)/r; float vol = PI * radius * radius * radius * (4/3); NO
y = -n; /* unary operator */ float vol = (4.0/3) * PI * radius * radius * radius; YES
(unary +, – have higher precedence than *, /, %, which in float vol = 4.0/3 * PI * radius * radius * radius; YES
turn have higher precedence than binary +, –)) float vol = PI * radius * radius * radius * 4/3.0;
4/3 0; YES
25 26

Operators and expressions Type casting in C


What is the value of each of these C expressions? To “temporarily” force the computer to regard a variable of a particular
type as having a different type,
type put the desired type in parentheses before
5 * (3 / 5.0) the variable name.
Examples:
5 * (3 / 5)
(float)i forces the computer to temporarily regard i as a float
(int)x forces the computer to temporarily regard x as an int
5 * 3 / 5
As seen before, we can “force” the computer to use floating-point arithmetic Note: the type of the variable being cast is NOT changed (e.g. if i had
by using 5.0 instead of 5 (if this is the desired behaviour). But what if the been declared as an int, it is still an int – it is just treated as a float
quantities
titi involved
i l d in
i the
th expressioni are variables,
i bl rather
th than
th constants?
t t ? For
F for the duration of the statement in which it is cast to type float).
float)
example, how would you ensure floating-point calculations in this case:
int i=3,
, j
j=5; Type casting is not just for variables – can also be applied to constants, e.g.
float k; (int)6.5 is the integer “6”
k = j*(i/j); /* want k to be assigned the value 3.0 */ (float)5 is the floating point number “5.0”
W can’t
We ’ just
j write
i i.0
i 0 or j.0…
j 0
27 28
Type casting in C – an example Arithmetic operators in C – other operators

Strip all but 2 decimal points from a float (not rounding): 12.34567 => 12.34 Increment and decrement operators:
x++ ; is equivalent to x = x + 1;
y ; is equivalent to y = y  1;
float trimmed = ((int)(100*number))/100.0 ;
Compound
C d ((or abbreviated)
bb i t d) assignment
i t operators:
t
1234.567
x += 3; is equivalent to x = x + 3;
sum = y; is equivalent to sum = sum  y;
1234
product *= z; is i equivalent
i l to product = product * z;
d /= 4.5; is equivalent to d = d / 4.5 ;
r %= 2; is equivalent to r = r % 2 ;
12.34, as required
In general: identifier operator= expression;
(this can be generalised to stripping all but N decimal points,
points for any value means identifier=identifier operator
p (
(expression);
p );
of N – details later) (Note: expression is evaluated first in these compound assignments)

29 30

You might also like