Introduction to C
© Khalid Nazim S.A. Assistant Professor, Department of Computer Science & Engineering PES School of Engineering, Bangalore -100
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 numbers Real numbers Text etc
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
eureka!
Algorithm: Algorithm A set of instructions describing how to do a task (or process)
Program: 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 Process Four stages 2. Editing 3. Preprocessing 4. Compiling: translates source code -> object code 5. Linking: Produces executable code
Portable programs will run on any machine.
Program correctness and robustness are most important than program efficiency
Machine Language
10100110 01110110 00100110 00000000 11111010 11111010 01001110 10100110 11100110 10010110 11001110 00101110 10100110 01001110 11111010 01100110 01001110 10000110 etc...
Compilation of a C program
Compilation Source1.c
Machine language with “holes” Executable
Source1.obj Linker
Compilation Source2.c
Machine language with “holes” Source2.obj
myprog.exe
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
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) 24
Why C? Flexible language: Structured language Low 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 categories 3. Letters : uppercase A..Z lowercase a..z
• • •
Digits: All decimal digits 0..9 Special Characters 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
“
Quotation mark
<
Opening angle bracket ( or less than sign)
! |
Exclamation markbar Vertical
>
/
Slash
(
Left parenthesis
\
Backslash
)
Right parenthesis
~
Tilde
[
Left bracket
_
Underscore
]
Right bracket
$
Dollar sign
{
Left brace
%
Percent sign
}
Right brace
#
Number sign
Closing angle bracket ( or greater than sign)
C tokens C tokens
Keywords int Float while
Identifiers main Amount time
Constants 10 3.1415
Strings “PES”
Special Symbols [] {}
Operators +-*,
Keywords Has a special meaning in C is “case-sensitive” Cannot be used as variable names Keywords auto double int break else long case enum register char extern return const float short continue for signed default goto sizeof do if static
struct switch typedef union unsigned void volatile while
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 digit must 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 C Numeric constants Integer constants
Real constants
Character 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 constants Type of constant
Meaning
‘\a’ ‘\b’
Bell 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 line 4. A blank space is required between #define and symbolic name and between symbolic name and value(constant) 6. #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 it tells 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;
Variable Declaration: Examples
“Keywords” short int myHeight = 152; /* cm */ int mySalary = 1000000000; long int mySalary = 1000000000; float commission = 0.05; double chance_of_a_date = 3e-500;
Assignment Puts a specified value into a specified variable Assignment operator: = = <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 int a = 5; double b = 3.5;
a
b
5
3.5
Variables in memory • 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
a
b
5
3.5
Declaring variables in C double cm, inches;
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.
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_2c area
First character cannot be a digit 2c_ISE is not valid!
Case sensitive ISE_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 Types Integer
Character
Floating
signed
Unsigned
Char
Float
int
Unsigned int
Signed char
Double
short int
Unsigned short int Unsigned long int
Unsigned char
Long double
long int
Data type Range of values char -128 to 127 int float
-32,768 to 32,767 3.4e-38 to 3.4e+e38
double
1.7e-308 to 1.7e+308
Void It is used to specify the type of functions
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 % 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 %
Operations with different types 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. When the operands are of the same type, the 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
Basic structure of a C program [documentation section] [definition section] [function prototype] [global variables] /* function main which is compulsory*/ main() { declaration section; Body of the program executable section; } [user defined functions]
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.}
A simple C program /* welcome to c programming – An example program */ #include <stdio.h> int main( ) { printf(“Hello, world!\n”); return 0; } Thistells is aanthe instruction towe theare compiler theacontents This compiler define function This Note Yet another is that Call statement. C statements statement. This endabout with onetoto terminates a insert semicolon the (;).program This is a comment – starts with a /* and ends with a */. Curly braces indicate the beginning and end of a of the file stdio.h to the program prior to compilation. named main. thecalls This and statement informs operating a function system called thatprintf, it haswhich endedcauses Comments are used to explain the program to a human block of instructions. main isfile a contains special – itabout is where the program text successfully. be printedfunction on the screen. Thisto information the printf fuction. starts reader, and are ignored by the compiler. Specifically in this case – a function. running.