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
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
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
What numbers does a computer work with?
Instructions. Addresses. Data:
Integer numbersReal numbersTextetc
Basic computer model
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.
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!
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.
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
High level languages vs.
machine languages.
Actually, binary instructions.
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.
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.
Why different languages?
Many languages were developed with specific applications in mind: Data processing Web applications Mathematical calculations Artificial intelligence
How do we compile?
A special program – the “compiler” – “translates” from computer language to machine language.
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
The C Compilation Model
AlgorithmAlgorithm: A set of instructions describing how to do a task (or process)
eureka!
ProgramProgram: C: C
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
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
Machine Language
10100110 0111011000100110 0000000011111010 1111101001001110 1010011011100110 1001011011001110 0010111010100110 0100111011111010 0110011001001110 10000110
etc...
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
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
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)
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
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”
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
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
C tokens
C tokens
Keywordsint
Floatwhile
Constants10
3.1415
Strings“PES”
Operators+ - * ,
Identifiers
mainAmount
time
Special Symbols
[ ]{ }
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
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!)
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
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
Real constants
These include the numbers containing
fractional parts like 123.45
Single character constants
It comprises of a single character enclosed
within a pair of single quotation marks
‘3’, ‘a’ etc..
String constants
It comprises of a sequence of characters
enclosed in double quotes (“ “)
Ex: “welcome to c”
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
Defining symbolic constants
Syntax:
#define symbolic-name value of the constant
Ex: #define PI 3.14152
Symbolic names are also called as constant
identifiers
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
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’;
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;
Variable Declaration: Examples
short int myHeight = 152; /* cm */
int mySalary = 1000000000;
long int mySalary = 1000000000;
float commission = 0.05;
double chanceOfADate = 3e-500;
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”
Assignment
Puts a specified value into a specified variable
Assignment operator: =
<variable name> = <expression> ;
not to be confused with ==
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.
Variables in memory
5
int a = 5;
double b = 3.5;
3.5
a
b
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
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;
Example: variable declarations
int i;char c;float area, radius;float a=3.0, b = 1.3;unsigned int n = 0;
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
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
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
User defined data type
C provides a facility wherein the users can
define an already existing identifier
typedef int total;
typedef float amount;
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.
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.
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);
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)
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 %
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
For example - 3 + 4 = 7 3.0 + 4 = 7.0 3 / 4 = 0 !!! 3.0 / 4 = 0.75
Operations with different types
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
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.}
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;}