You are on page 1of 13

Coventry University

Faculty of Engineering & Computing

Section 2 Introduction to C Programming Objectives :To be able to write simple C programs. To become familiar with identifiers and basic data types. To be able to use simple input and output statements. To understand computer memory concepts. To be able to use arithmetic operators. To understand the precedence of arithmetic operators. To be able to use shorthand operators.

2010 R.J.Rider\Basic C

Page - 2.1

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

An Elementary C Program
// A first program in C : Example .1 #include <stdio.h> void main(void) { printf("Welcome to C Programming!"); }

Text following // is a comment and ignored by the compiler. Comments cannot be nested (one inside another). All C programs consist of one of more functions. There must always be a function called main. All C programs begin executing at main. The { and } mark the beginning and end of main. A portion of program between { and } is also called a block. Individual statements are terminated by a ;

2010 R.J.Rider\Basic C

Page - 2.2

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Identifiers and Basic Data Types


Identifiers give names to program objects such as:constants functions are made up of:letters digits underscores variables macros data types labels

The number of signifcant characters in an identifier is compiler dependent. In TurboC only the first 32 characters are significant. In some implementations only the first 6 may count. The first character must not be a digit. Use a letter as the first character as many of the identifiers in the standard library begin with an underscore. C is case sensitive, ie. it matters whether you use small letters or capitals. Choose identifier names that have some relation to what you are doing. This makes programs easier to read, understand and de-bug. Must not be the same as any of C's reserved words (all lower case): Table 2.1 Reserved Words auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

2010 R.J.Rider\Basic C

Page - 2.3

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Basic Data Types


char a single byte, capable of holding one ASCII character. May be qualified by the keywords signed or unsigned. an integer number. May be qualified by the keywords short, long, signed or unsigned. a single precision floating point number a double precision floating point number. May be qualified by the keyword long.

int

float double

The range and storage of these objects are machine dependent, as shown in table 2.2 for a 16-bit processor: Table 2.2 Sizes of Data Objects (16-bit m/c)

Type unsigned char char enum unsigned int short int int unsigned long long float double long double near pointer far pointer

Bytes 1 1 2 2 2 4 4 4 8 10 2 4

Range 0 to 255 -128 to 127 depends on type 0 to 65,535 -32,768 to 32,767 -32,768 to 32,767 0 to 4,294,967,295 -2,147,483,648 to +2,147,483,647 3.4x10-38 to 3.4x1038 1.7x10x308 to 1.7x10308 3.4x10-4932 to 1.1x104932 not applicable not applicable

Sig Dig

6 15 19

2010 R.J.Rider\Basic C

Page - 2.4

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Input and Output


Input is the means by which the user or some external device provides a program with information to operate on. Output is the means by which a program sends information to the user or some external device. I/O stands for input & output operations. C does not have any I/O facilities built into the language. I/O is achieved by calling library objects and functions. We will use the standard library stdio.h library printf scanf for output for input

Programs that use these facilities must include the statement :#include <stdio.h> prior to the main function, with the #include word starting in column 1. Useful formatting characters Escape sequence '\t' '\n' '\f' '\g' Meaning tab newline formfeed bell

2010 R.J.Rider\Basic C

Page - 2.5

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Another Basic C Program // Basic program in C : Example .2 #include <stdio.h> void main(void) { int int1, int2, sum; printf("\nEnter 1st integer : "); scanf("%d", &int1); // reads into the address of int1 printf("\nEnter 2nd integer : "); scanf("%d", &int2); sum = int1 + int2; printf("\nSum = %d\n", sum); // or printf("\nSum = %d\n ", int1 + int2); } Possible run :Enter 1st integer : 10 Enter 2nd integer : 20 Sum = 30 Sum = 30

2010 R.J.Rider\Basic C

Page - 2.6

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Memory Concepts
In the previous example, three variables were used, each with a name (identifier), a type and a value i.e. :Identifier int1 int2 sum Type int int int Value 10 20 30

At compile time the compiler must allocate an amount of memory to each variable corresponding to the largest possible value of its associated data type. This is achieved by the declaration statement:int int1, int2, sum; which, on a 16-bit processor, reserves 2 bytes each. A meaningful value will not exist in these memory locations until either an input or an assignment statement occurs:scanf("%d", &int1); sum = int1 + int2;

/* puts a value in int1 */ /* puts a value in sum */

N.B. an assignment statement takes the value of the r.h. expression. Variables can also be initialised in their declarations, e.g.:int int1 = 0, int2 = 5, sum = 74;

This statement makes use of integer constants i.e. 0, 5, 74. Other integer formats are available (using 74 etc. as examples):74 74L 74u 07 07L 0xB 0xBL decimal decimal long decimal unsigned octal octal long hexadecimal hexadecimal long (decimal numbers must not begin with zero) (int x = 74L and long int x = 74 both give same result) (octal numbers must begin with zero) (hex numbers must begin 0x - zero, small x)

2010 R.J.Rider\Basic C

Page - 2.7

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Other basic constant types are :Floating point constants, which are taken as doubles and written as e.g. :100.0, -100.0, 10.1e2, 46.34e-3, -52.6E6

Character constants, which are single characters enclosed in single quotes :'a', '8', '!', '\007', '\'', '\n'

String constants, which are characters enclosed in double quotes. A NULL terminator '\0' is automatically placed at the end of each string. The string "four" takes 5 bytes of memory, one for each of :f o u r \0

Variables and constants of different types can be mixed according to promotion rules. These will be dealt with later.

2010 R.J.Rider\Basic C

Page - 2.8

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Arithmetic in C
Table 2.6 The Arithmetic Operators C operation Arithmetic operator + * / % Algebraic expression f+7 p-c bm x/y r mod s C expression

Addition Subtraction Multiplication Division Modulus

f+7 p-c b*m x/y r%s

The arithmetic operators are binary operators, i.e. they have two operands. Division of integers, using /, truncates any fractional part thus 14 / 5 = 2

The modulus or remainder operator % can only be used with integers and produces the remainder of a division, thus 14 % 5 = 4

Precedence of Arithmetic Operators


Evaluation proceeds according to C's rules of precedence. These are summarised in table 2.7 for arithmetic operators. Table 2.7 Arithmetic operator Precedence Operators ( ) Operations Parentheses Precedence Highest If nested, the innermost expression is evaluated first. Several pairs at the same level are evaluated. Several at the same level are evaluated left to right. Several at the same level are evaluated left to right.

* / % + -

Multiplication, Division, Modulus Addition Subtraction

Second Lowest

Parentheses can always be used to force an expression to be evaluated as intended. The direction left or right in which evaluation proceeds is governed by the associativity of the operators. Associativity will be dealt with later.

2010 R.J.Rider\Basic C

Page - 2.9

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Shorthand Operators
C provides several operators that can be used to achieve significant improvements in speed of program compilation and execution (and in writing). They go a long way to making C programs difficult for the novice to read because their definitions seem quite arbitrary. As an example, x = x +1 is easily understood when we realise that = means 'takes the value of' (assignment) and we are not trying to prove 0 = 1! In C the incrementing of x can be written as ++x and you will soon come to recognise this and similar 'fast operators'. Assignment operators :These operators have the general form :variable operator= variable or constant ie. they are modifications of = where operator is a binary operator. The arithmetic operators are summarised in Table 2.8. Assume: int c = 3, d = 5, e = 4, f = 6, g = 12

Table 2.8 Shorthand operators Operator += -= *= /= %= Expression c += 7 d -= 4 e *= 5 f /= 3 g %= 9 meaning = c + 7 = d - 4 = e * 5 = f / 3 = g % 9 Assigns 10 to c 1 to d 20 to e 2 to f 3 to g

c d e f g

Increment and Decrement operators :The symbol ++ increments a variable by 1 The symbol -- decrements by 1. If the symbol is placed before the variable the operation is performed before the variable is used. Placing it after the variable causes the old value of the variable to be used and then the variable is incremented/decremented. These operators make use of fast machine instructions (if available) and should generally be used where possible, eg. ++a would be preferred to a = a + 1;

2010 R.J.Rider\Basic C

Page - 2.10

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Type Conversions
Expressions can only be evaluated if the operands are all of the same data type. However C allows mixed types to appear in source code expressions. The compiler must then convert all operands to a common type according to a set of rules. In arithmetic expressions :char's and int's may be freely intermixed. All char's are automatically converted to int's. Any ASCII character stored in a char is guaranteed to be converted to a positive integer. If a binary operator has operands of different types, the "lower" type is promoted to the "higher" type before the operation proceeds. The result is of the higher type. The ANSI C promotion rules are detailed in the booklet. The ANSI C rules differ in two ways from the pre-ANSI C rules. 1. Arithmetic on float operands may be done in single rather than double precision. 2. Shorter, unsigned types, when combined with a larger signed type do not propagate the unsigned property to the result type. In assignment operations :The value on the right hand side is converted to the type of the left, which is the type of the result, e.g. :int i; char c; float x; double y; i = c; c = i; x = i; i = x; /* value of c promoted to int */ /* High-order bits in i discarded */ /* value of i promoted to float. */ /* i is assigned integral part of x */

2010 R.J.Rider\Basic C

Page - 2.11

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Explicit type conversions:A type conversion can be forced using the cast operator. It has the general form :type-name (expression) (type-name) expression C syntax C syntax

This causes a temporary value of expression to be created of the defined type. Example :printf("Pi is approximately %f", float(int(22.0/7.0))); Would display :Pi is approximately 3 The cast operator has the same precedence as the other unary operators.

2010 R.J.Rider\Basic C

Page - 2.12

basic_c_concepts_osh.docx

Coventry University

Faculty of Engineering & Computing

Examples :

#include <stdio.h> #include <conio.h> void main( void ) { int w, x; unsigned int y; // Precedence ex. x = 7 + 3 * 5; printf("A. x = %d", x); // Order of evaluation ex. x = 5 / 3 * 3; printf("B. x = %d", x); x = 3 * 5 / 3; printf("C. x = ", x); // Shorthand operator ex. w = 5; x = w++; printf("D1. x = %d", x); printf("D2. w = %d", w); // Type conversion examples printf("E. ans = %f", 5/3*6.0); printf("F. ans = %f", 6.0*5/3); getchar(); } // end of main function

2010 R.J.Rider\Basic C

Page - 2.13

basic_c_concepts_osh.docx

You might also like