Introduction to C Department of Computer Science.

64
Introduction to C Department of Computer Science

Transcript of Introduction to C Department of Computer Science.

Page 1: Introduction to C Department of Computer Science.

Introduction to C

Department of Computer Science

Page 2: Introduction to C Department of Computer Science.

What programming is? Programming is taking

A problem

“Find the area of a circle”

A set of data

radius

PI

A set of functions

area = PI *radius* radius

Then

Applying functions to data to get answer

Page 3: Introduction to C Department of Computer Science.

What can a computer do?

Strictly speaking, very little: Store and retrieve numbers

very quickly very accurately

Add, subtract, multiply, and divide also fast and accurate

Compare numbers (with 0) Follow a list of instructions

jump around in the list

Page 4: Introduction to C Department of Computer Science.

What about everything else?

More complex math Combination of atomic operations

Interaction with peripheral devices Output: graphics cards and printers Input: keyboards, mice, joysticks All sorts of specialized devices

Everything done using numbers To the computer everything is numbers

Page 5: Introduction to C Department of Computer Science.

What numbers does a computer work with?

Instructions. Addresses. Data:

Integer numbersReal numbersTextetc

Page 6: Introduction to C Department of Computer Science.

Basic computer model

Page 7: Introduction to C Department of Computer Science.

What is a computer program?

A sequence of processor instructions designed to achieve a specific purpose.

The instructions are executed sequentially.

Each instruction has a numerical code.

Page 8: Introduction to C Department of Computer Science.

Examples of instructions

Load data (from an address in the memory)

Store data (in an address) Add two numbers If two numbers are equal, jump to another

part of the program Instructions are numbers!

Page 9: Introduction to C Department of Computer Science.

Machine language

Computers understand only machine language. Every processor has its own machine language. Basically looks like a sequence of 1’s and 0’s. Very inconvenient to work with and non intuitive.

All other computer languages were created for human convenience The computer does not understand C. Must be converted into machine language.

Page 10: Introduction to C Department of Computer Science.

Computer languages (getting closer to human languages)

Assembly – machine language with some text codes (still inconvenient)

Interpreted languages – Java, Perl, MATLAB The program is translated into machine language

line by line during execution Compiled languages – C, C++, Pascal, Fortran…

The program is translated into machine language before execution

Page 11: Introduction to C Department of Computer Science.

High level languages vs.

machine languages.

Actually, binary instructions.

Page 12: Introduction to C Department of Computer Science.

Syntax and Semantics

The syntax of a programming language: Set of rules that specify allowable statements in

the language. Similar to a grammar for a natural language.

The semantics of a programming language: Rules for interpreting the computational operations

specified by statements in a programming language.

Page 13: Introduction to C Department of Computer Science.

C is a procedural language

It enables the user (= the programmer) to create new instructions (procedures) from existing ones.

Instead of re-writing the same code over and over again, write it once and call it when needed.

Page 14: Introduction to C Department of Computer Science.

Why different languages?

Many languages were developed with specific applications in mind: Data processing Web applications Mathematical calculations Artificial intelligence

Page 15: Introduction to C Department of Computer Science.

How do we compile?

A special program – the “compiler” – “translates” from computer language to machine language.

Page 16: Introduction to C Department of Computer Science.

The whole process of executing a C program

Write a program Using a text editor

Compile + link the program C compiler will do one of two things:

print error messages and abort (most probably…) produce an executable program

Run the program

Page 17: Introduction to C Department of Computer Science.

The C Compilation Model

Page 18: Introduction to C Department of Computer Science.

AlgorithmAlgorithm: A set of instructions describing how to do a task (or process)

eureka!

ProgramProgram: C: C

Page 19: Introduction to C Department of Computer Science.

From Algorithms to Programs

Both are sets of instructions on how to do solve a given problem

Algorithm: Easy to understand represented in simple English statements

Program: by use of a compiler.can be regarded as a “formal expression” of an

algorithm

Page 20: Introduction to C Department of Computer Science.

Development ProcessFour stages1. Editing2. Preprocessing 3. Compiling: translates source code -> object code4. Linking: Produces executable code

Portable programs will run on any machine.

Program correctness and robustness are most important than program efficiency

Page 21: Introduction to C Department of Computer Science.

Machine Language

10100110 0111011000100110 0000000011111010 1111101001001110 1010011011100110 1001011011001110 0010111010100110 0100111011111010 0110011001001110 10000110

etc...

Page 22: Introduction to C Department of Computer Science.

Compilation of a C program

Source1.c

Compilation

Source1.obj

Machine language with “holes”

myprog.exe

Executable

Source2.c

Compilation

Source2.obj

Machine language with “holes”

Linker

Page 23: Introduction to C Department of Computer Science.

Features of C language

C provides: efficiency flexibility many high-level and low-level operations stability

C is used in: data compression, graphics and computational geometry databases, operating systems

Page 24: Introduction to C Department of Computer Science.

24

History of C

CPL Combined Programming Language

(Barron et al., 1963)

BCPL Basic CPL (Richards, 1969)

B (Thompson, 1970)

C K & R (Ritchie, 1972)

ANSI C American National Standards Institute C

(X3J11, 1989)

C99 (JTC1/SC22/WG14, ISO/IEC 9899, 1999)

Page 25: Introduction to C Department of Computer Science.

Why C?

Flexible language:Structured languageLow level activities possible

Standard library exists, allowing portability It can produce simple and efficient code Portable Widely used in different types of applications

Page 26: Introduction to C Department of Computer Science.

The main function main( ) int main( ) void main( ) main (void) void main (void) int main (void) The word void means that the function does not return any

information to the O.S. int means that the function returns an integer value to the

operating system i.e. when int is used the the last

statement in the program should be “return 0”

Page 27: Introduction to C Department of Computer Science.

Character Set

The characters in c language are grouped into the following categories1. Letters : uppercase A..Z

lowercase a..z

2. Digits: All decimal digits 0..93. Special Characters4. White Spaces- blank space, new line,

carriage return, horizontal tab, form

feed

Page 28: Introduction to C Department of Computer Science.

Special characters

, comma & Ampersand

. Period ^ caret

; Semicolon * asterisk

: Colon - Minus sign

? Question mark + Plus sign

‘ Apostrophe

<

Opening angle bracket

“ Quotation mark ( or less than sign)

! Exclamation mark >

Closing angle bracket

| Vertical bar ( or greater than sign)

/ Slash ( Left parenthesis

\ Backslash ) Right parenthesis

~ Tilde [ Left bracket

_ Underscore ] Right bracket

$ Dollar sign { Left brace

% Percent sign } Right brace

# Number sign

Page 29: Introduction to C Department of Computer Science.

C tokens

C tokens

Keywordsint

Floatwhile

Constants10

3.1415

Strings“PES”

Operators+ - * ,

Identifiers

mainAmount

time

Special Symbols

[ ]{ }

Page 30: Introduction to C Department of Computer Science.

Has a special meaning in Cis “case-sensitive”Cannot be used as variable names

Keywords

auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while

Keywords

Page 31: Introduction to C Department of Computer Science.

Identifiers

These refer to the names of variable, functions, arrays.

is a series of characters consisting of letters, digits and underscores ( _)

cannot begin with a digitmust not be a keyword is “case-sensitive”Examples:

sum, x1, y2, my_ID, Main (careful!)

Page 32: Introduction to C Department of Computer Science.

Constants

These refer to those values that are fixed

and do not change during the execution of

the program

constants in CNumeric constants Character constants

Integer constants

Real constants

Single character

constants

String constants

Page 33: Introduction to C Department of Computer Science.

Integer constants

It refers to a sequence of digits

The types of integer constants are

a. decimal integer : 0..9 , preceded by a + or - sign

b. octal integer: 0..7, with a leading 0 ex: 037 etc.

c. hexadecimal integer: preceded with a 0x or 0X

i.e.: these may include alphabets from A..F or a..f

ex: 0x2,0xabc etc

Page 34: Introduction to C Department of Computer Science.

Real constants

These include the numbers containing

fractional parts like 123.45

Page 35: Introduction to C Department of Computer Science.

Single character constants

It comprises of a single character enclosed

within a pair of single quotation marks

‘3’, ‘a’ etc..

Page 36: Introduction to C Department of Computer Science.

String constants

It comprises of a sequence of characters

enclosed in double quotes (“ “)

Ex: “welcome to c”

Page 37: Introduction to C Department of Computer Science.

Backslash character constantsType of constant Meaning

‘\a’ Bell

‘\b’ Back space

‘\f’ Form feed

‘\n’ New line

‘\r’ Carriage return

‘\t’ Horizontal tab

‘\v’ Vertical tab

‘\” Single quote

‘\’” Double quote

‘\0’ Null

Page 38: Introduction to C Department of Computer Science.

Defining symbolic constants

Syntax:

#define symbolic-name value of the constant

Ex: #define PI 3.14152

Symbolic names are also called as constant

identifiers

Page 39: Introduction to C Department of Computer Science.

Rules to be followed while using a symbolic constant

1. Names are usually written in CAPITALS to distinguish them from the normal variable names- just a convention

2. No blank space between the hash # symbol and the word define is allowed

3. # must be the first character in the line4. A blank space is required between #define and

symbolic name and between symbolic name and value(constant)

5. #define should not end with a semicolon

Page 40: Introduction to C Department of Computer Science.

Variables

is a logical name that is used to store a data value(an actual piece of computer memory for

values)

has a type associated with ittells the computer how to interpret the bits

must be declared before use:int i; float result;

int i=0; char initial=’K’;

Page 41: Introduction to C Department of Computer Science.

Declaration of variables

data- type v1,v2,….vn;

V1,v2,…vn = variables.

Variables are seperated by commas

It should end with a semicolon

Ex: int a,b,c;

float d;

char s;

Page 42: Introduction to C Department of Computer Science.

Variable Declaration: Examples

short int myHeight = 152; /* cm */

int mySalary = 1000000000;

long int mySalary = 1000000000;

float commission = 0.05;

double chanceOfADate = 3e-500;

Page 43: Introduction to C Department of Computer Science.

short int myHeight = 152; /* cm */

int mySalary = 1000000000;

long int mySalary = 1000000000;

float commission = 0.05;

double chance_of_a_date = 3e-500;

Variable Declaration: Examples

“Keywords”

Page 44: Introduction to C Department of Computer Science.

Assignment

Puts a specified value into a specified variable

Assignment operator: =

<variable name> = <expression> ;

not to be confused with ==

Page 45: Introduction to C Department of Computer Science.

What are variables?

A named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, etc.)

They contain the data your program works with.They can be used to store data to be used

elsewhere in the program. In short – they are the only way to manipulate

data.

Page 46: Introduction to C Department of Computer Science.

Variables in memory

5

int a = 5;

double b = 3.5;

3.5

a

b

Page 47: Introduction to C Department of Computer Science.

Variables in memory

5

• Whenever we write the variable name (a), we ask to read the value of that variable

• If we write &variable_name, we ask for the address of that variable

3.5

a

b

Page 48: Introduction to C Department of Computer Science.

Declaring variables in C

Before using a variable, one must declare it.The declaration first introduces the variable

type, then its name.When a variable is declared, its value is

undefined.

double cm, inches;

Page 49: Introduction to C Department of Computer Science.

Example: variable declarations

int i;char c;float area, radius;float a=3.0, b = 1.3;unsigned int n = 0;

Page 50: Introduction to C Department of Computer Science.

Variable naming rules

Letters, digits, underscores i ISE_2carea

First character cannot be a digit2c_ISE is not valid!

Case sensitiveISE_2c is different from ise_2a

Page 51: Introduction to C Department of Computer Science.

Data types

C supports 3 classes of data types namely

1. Fundamental or primary data types

2. Derived data types

3. user- defined data types

Page 52: Introduction to C Department of Computer Science.

Primary Data TypesInteger Character Floating

Void

It is used to specify the

type of functions

signed Unsigned Char Float

int Unsigned int Signed char Double

short int Unsigned short int

Unsigned char

Long double

long int Unsigned long int

Data type Range of values

char -128 to 127

int -32,768 to 32,767

float 3.4e-38 to 3.4e+e38

double 1.7e-308 to 1.7e+308

Page 53: Introduction to C Department of Computer Science.

User defined data type

C provides a facility wherein the users can

define an already existing identifier

typedef int total;

typedef float amount;

Page 54: Introduction to C Department of Computer Science.

printf and scanf

printf – prints to the screen.

Can also accept variables and print their

values.

scanf – reads the values from the user

i.e. from the standard input and

assigns them to variables.

Page 55: Introduction to C Department of Computer Science.

printf can print variable values

printf(“a=%d\n", a);The sequence %d is a special

sequence and is not printed!It indicates to printf to print the value

of an integer variable written after the printed string.

Page 56: Introduction to C Department of Computer Science.

scanf gets input from the user

scanf("%lf", &cm);

This statement waits for the user to type in a double value, and stores it in the variable named ‘cm’.

To get 2 doubles from the user, use –scanf("%lf%lf", &var1, &var2);

Page 57: Introduction to C Department of Computer Science.

prinft/scanf conversion codes

A %<conversion code> in the printf/scanf string is

replaced by the respective variable.%c – a character%d – an integer, %u – an unsigned integer.%f – a float%lf – a double%g – a nicer way to show a double (in printf)%% - the ‘%’ character (in printf)

Page 58: Introduction to C Department of Computer Science.

Arithmetic operators

An operator is an action performed on something (e.g. constants, variables).

That “something” is called an operand. Common operators:

Assignment = Addition + Subtraction - Multiplication * Division / Modulo %

Page 59: Introduction to C Department of Computer Science.

When operands of two different types are involved in an operation, the operand of the ‘weaker’ type is promoted to the other type (int → float → double).

The result of the operation is of the higher type.The result of the operation is of the higher type. When the operands are of the same type, the When the operands are of the same type, the

result is of that type as well.result is of that type as well.

Operations with different types

Page 60: Introduction to C Department of Computer Science.

For example - 3 + 4 = 7 3.0 + 4 = 7.0 3 / 4 = 0 !!! 3.0 / 4 = 0.75

Operations with different types

Page 61: Introduction to C Department of Computer Science.

Basic structure of a C program

[documentation section][definition section][function prototype][global variables]/* function main which is compulsory*/main(){

declaration section;executable section;

}[user defined functions]

Body of the program

Page 62: Introduction to C Department of Computer Science.

A simple C program

1. /* welcome to first program in C – An example program */

2. #include <stdio.h>3. main( )4. {5. printf(“welcome to first program in C!\n”);6.}

Page 63: Introduction to C Department of Computer Science.

This is a comment – starts with a /* and ends with a */.Comments are used to explain the program to a human reader, and are ignored by the compiler.

Curly braces indicate the beginning and end of a block of instructions. Specifically in this case – a function.

This is an instruction to the compiler to insert the contents of the file stdio.h to the program prior to compilation.

This file contains information about the printf fuction.

Yet another C statement. This one terminates the program and informs the operating system that it has ended successfully.

This tells the compiler we are about to define a function named main.main is a special function – it is where the program starts running.

This is a C statement. This statement calls a function called printf, which causes text to be printed on the screen.

Note that all C statements end with a semicolon (;).

A simple C program

/* welcome to c programming – An example program */

#include <stdio.h>int main( ){ printf(“Hello, world!\n”); return 0;}

Page 64: Introduction to C Department of Computer Science.