SlideShare a Scribd company logo
Fundamentals of Programming 
Introduction to the C language 
Giuseppe Lipari 
http://retis.sssup.it/~lipari 
Scuola Superiore Sant’Anna – Pisa 
February 29, 2012 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 1 / 58 
Outline 
1 First steps 
2 Declarations and definitions 
3 Variables 
Simple Input/output 
First exercises 
Advanced operators 
4 Statements and control flow 
If then else 
While loop 
For loop 
Exercises 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 2 / 58
My first C program 
Let’s start with a classic: 
hello.c 
#include <stdio.h> 
int main() 
{ 
printf("Hello world!n"); 
return 0; 
} 
include includes definitions for library functions (in this case, the 
printf() function is defined in header file stdio.h) 
main function this function must always be present in a C program. It 
is the first function to be invoked (the entry point) 
return end of the function, returns a value to the shell 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 4 / 58 
How to compile and run the program 
The C language is a compiled language 
It means that the above program must be translated into a binary 
code before being executed 
The compiler does the job 
reads the source file, translates it into binary code, and produces 
an executable file 
In Linux, the following command line produces executable file hello 
from source file hello.c 
gcc hello.c -o hello 
In Windows (with DevC++), you must build the program 
When you run the program (from a Linux shell, type ./hello, 
from Windows, click on Run), you obtain: 
(in Windows you may not be able to see the output because the 
shell is automatically closed!) 
Hello world! 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 5 / 58
Compiling the code 
The translation from high-level language to binary is done by the 
compiler (and the linker) 
the compiler translates the code you wrote in the source file 
(hello.c) 
the linker links external code from libraries of existing functions (in 
our case, the printf() function for output on screen) 
compile & 
link 
executable 
std library 
(printf) 
hello.c 
gcc hello.c −o hello hello 
Figure: Compiling a file 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 6 / 58 
Multiple source files 
A program can consist of multiple source files 
Every source file is called module and usually consists of a set of 
well-defined functions that work together 
every source file is compiled separately (it is a compilation unit) to 
produce an object file (extension: .o or .obj) 
all objects files and libraries are then linked together to produce an 
executable 
We will see later how it works 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 7 / 58
Running a program 
To execute a program, you must tell the Operating System to 
load the program in main memory (RAM) 
start executing the program instructions sequentially 
The OS is itself a program! 
It is a high-order program that controls the execution of user 
programs 
The OS can: 
Execute several user programs concurrently or in parallel 
suspend or kill a user program 
coordinate and synchronize user programs 
let them communicate and exchange data 
and many other things! 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 8 / 58 
Declarations, functions, expressions 
A C program is a sequence of global declarations and definitions 
declarations of global variables and functions 
definitions of variables and functions 
often, declarations are implicit (the definition is an implicit 
declaration) 
Examples: 
int a; // declaration + definition 
int b = 10; // declaration + definition + init 
int f(int); // declaration only 
int f(int p) // definition 
{ 
... 
} 
int g() // declaration + definition 
{ 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 10 / 58
Functions 
The code goes inside functions 
There must be always at least one definition of a function called 
main 
In the hello example: 
hello.c 
int main() 
{ 
printf("Hello world!n"); 
return 0; 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 11 / 58 
Anatomy of the main function 
There can be another form of main function: 
int main(int argc, char *argv[]) 
{ 
... 
} 
main is the function name, and must be unique in a program 
there cannot be two functions with the same name 
int is the return type (will see later) 
between () parenthesis we have the list of parameters with their 
type, separated by commas: 
in the example above, two parameters, argc and argv 
between {} parenthesis, we have the function body: 
the code that is executed when the function is called 
The OS implicitly calls the main function when the program is 
launched 
the main function is also called the program entry point 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 12 / 58
Variables and types 
A variable is a location in memory with a symbolic name 
A variable is used as temporary or permanent storage of data to 
perform complex computation 
In C, every variable must have a type 
Predefined types in C: 
int an integer number (usually 32 bits) 
char a ASCII character (8 bits) 
float floating point number, single precision (32 bits) 
double floating point number, double precision (64 bits) 
A type dictates the variable range (or domain) (from the number of 
bits) and the operations you can perform on a variable 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 14 / 58 
Variables definition 
Usually, declaration and definition coincide for variables 
The definition consists of the type keyword followed by the name 
of the variable, followed by the “;” symbol 
Examples 
int a; /* an integer variable of name a */ 
double b; /* a double-precision floating point */ 
char c; /* a character */ 
... 
a = 10; /* assignment: a now contains 10 */ 
b = b + 1.5; /* after assignment, b is equal to 
the previous value of b plus 1.5 */ 
c = ’a’; /* c is equal to the ASCII value of 
character ’a’ */ 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 15 / 58
Constants 
Constants are numeric or alphabetic values that can be used in 
operations on variables or in functions 
Example: 
const double pi = 3.1415; /* a double precision constant */ 
int a = 325; /* 325 is a constant integer */ 
char c = ’?’; /* ’?’ is a constant character */ 
printf("Hello world!n"); /* "Hello world!n" is a * 
* constant string */ 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 16 / 58 
Variable names 
Variable names cannot start with a number 
cannot contain spaces 
cannot contain special symbols like ’+’, ’-’, ’*’, ’/’, ’%’, etc. 
cannot be arbitrarily long (255 char max) 
cannot be equal to reserved keywords (like int, double, for, etc.) 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 17 / 58
Variable initialization 
It is possible to assign an initial value to a variable during definition 
If you do not specify a value, the initial value of the variable is 
undefined 
It is good programming practice to always initialize a variable 
Many programming errors are due to programmers that forget to 
initialize a variable before using it 
int a = 0; /* the initial value is 0 */ 
int i; /* undefined initial value */ 
int b = 4; 
b = i + 5; /* error! the value of i is not defined! */ 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 18 / 58 
Operations on variables 
The basic arithmetic operators are: 
+ addition 
- subtraction 
* multiplication 
/ division 
% modulus (remainder of the integer division) 
Notes: 
when division is applied to integers, the result is an integer (it 
truncates the decimal part) 
modulus can only be applied to integers 
multiplication, division and modulus have precedence over addition 
and subtraction 
to change precedence, you can use parenthesis 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 19 / 58
Expressions 
A C program is a sequence of expressions, and expression is a 
combination of operators on variables, constants and functions 
Examples of expressions: 
/* definitions of variables */ 
int a, b; 
int division; 
int remainder; 
double area_circle; 
double radius; 
... 
/* expressions */ 
a = 15; 
b = 6; 
division = a / b; 
remainder = a % b; 
radius = 2.4; 
area_circle = 3.14 * radius * radius; 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 20 / 58 
Assignment and expressions 
Assigning a value to a variable is itself an expression 
area_circle = 3.14 * radius * radius; 
The above expression is composed by three elements: 
the operator is = 
the left operand must always be a variable name (cannot be 
another expression!) 
the right operand can be any expression, (in our case two 
multiplications) 
the right operand is evaluated first, and then the result is assigned 
to the left operand (the variable) 
area_circle / 3.14 = radius * radius 
the code above is illegal! Why? 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 21 / 58
Assignment expressions 
The following expression is perfectly legal: 
int a, b; 
b = a = 5; 
You must read it from right to left: 
a=5 is first evaluated by assigning value 5 to variable a; the result 
of this expression is 5 
then, the result is assigned to variable b (whose value after 
assignment is hence 5) 
What are the values of a and b after the following two 
expressions? 
int a, b; 
b = (a = 5) + 1; 
b = a = 5 + 1; 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 22 / 58 
Formatted output 
To output on screen, you can use the printf library function 
exprintf.c 
/* fprintf example */ 
#include <stdio.h> 
int main() 
{ 
printf ("Characters: %c %c n", ’a’, 65); 
printf ("Decimals: %d %ldn", 1977, 650000); 
printf ("Preceding with blanks: %10d n", 1977); 
printf ("Preceding with zeros: %010d n", 1977); 
printf ("Some different radixes: %d %x %o %#x %#o n", 
100, 100, 100, 100, 100); 
printf ("floats: %4.2f %+.0e %E n", 3.1416, 3.1416, 3.1416); 
printf ("Width trick: %*d n", 5, 10); 
printf ("%s n", "A string"); 
return 0; 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 24 / 58
Formatted Input 
To input variables from the keyboard, you can use the scanf 
library function 
exscanf.c 
/* scanf example */ 
#include <stdio.h> 
int main () 
{ 
char str [80]; 
int i; 
printf ("Enter your family name: "); 
scanf ("%s",str); 
printf ("Enter your age: "); 
scanf ("%d",&i); 
printf ("Mr. %s , %d years old.n",str,i); 
printf ("Enter a hexadecimal number: "); 
scanf ("%x",&i); 
printf ("You have entered %#x (%d).n",i,i); 
return 0; 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 25 / 58 
Exercises 
1 Write a program that asks the user to enter the radius of a circle, 
computes the area and the circumference 
define variables and initialize them 
use scanf to input radius variable 
compute the values 
formatted input on screen 
2 Write a program that asks for two integer numbers a and b, 
computes the quotient and the remainder, and prints them on 
screen 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 27 / 58
Shortcuts 
It is possible to combine assignment with common operators, as 
follows: 
a += 5; // equivalent to a = a + 5; 
x /= 2; // equivalent to x = x / 2; 
y *= x + a; // equivalent to y = y * (x+a); 
In general 
var <op>= <expr>; // equivalent to var = var <op> (<expr>); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 29 / 58 
Increment / decrement 
If you just need to increment/decrement, you can use the following 
shortcuts 
x++; // equivalent to x = x + 1; 
++x; // equivalent to x = x + 1; 
y--; // equivalent to y = y - 1; 
--y; // equivalent to y = y - 1; 
Of course, it can only be used on variables; 
(a+b)++; // compiler error! cannot increment 
// an expression 
x = (a+b)++; // error again: use x = (a+b)+1; 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 30 / 58
Pre and post-increment 
What is the difference between x++ and ++x? 
They are both expressions that can be used inside other 
expressions (like assignment), as follows; 
int a, x; 
x = 5; 
a = ++x; // what is the value of a after the assignment? 
The only difference is the value of the expression: 
x++ has the value of x before the increment; 
++x has the value of x after the increment; 
x = 5; 
a = x++; // value of a is 5, b is 6 
x = 5; 
a = ++x; // value of a is 6, b is 6 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 31 / 58 
Boolean operators 
In there is no boolean type 
Every expression with a value equal to 0 is interpreted as false 
Every expression with a value different from 0 is interpreted as 
true 
It is possible to use the following boolean operators: 
&& logical and operator 
|| logical or operator 
! logical not operator 
It is possible to interpret integer values as booleans and vice versa 
int a, b, c; 
a = 0; b = 5; 
c = a && b; // after assignment, c is 0; 
c = a || b; // after assignment, c is 1; 
c = !b; // after assignment, c is 0; 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 32 / 58
Comparison operators 
These operators compare numbers, giving 0 or 1 (hence a 
boolean value) as result 
< less than 
<= less than or equal to 
> greater than 
>= greater than or equal to 
== equal 
!= not equal 
int a = 7; int b = 10; int c = 7; 
int res; 
res = a < b; // res is 1 
res = a <= c; // res is 1 
res = a < c; // res is 0 
res = b == c; // res is 0 
(will come back to these later) 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 33 / 58 
Binary operators 
It is possible to do binary operations on integer variables using the 
following operators: 
& binary (bit-to-bit) and 
| binary (bit-to-bit) or 
 binary (bit-to-bit) not (complement) 
unsigned char a = 1; // in binary: 0000 0001 
unsigned char b = 2; // in binary: 0000 0010 
unsigned char c = 5; // in binary: 0000 0101 
unsigned char d; 
d = a  b; // d is now 0000 0000 
d = a  c; // d is now 0000 0001 
d = a | b; // d is now 0000 0011 
d = ~a; // d is now 1111 1110 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 34 / 58
Execution flow 
Usually, instructions are executed sequentially, one after the other, 
until the end of the function 
However, in many cases we must execute alternative instructions, 
depending on the value of certain expressions 
Also, sometimes we need to repeat instructions a number of 
times, or until a certain condition is verified 
we need to control the execution flow 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 36 / 58 
If statement 
To select alternative paths, we can use the if then else statement 
The general form is the following: 
if (expression) 
statement; 
expression must be a boolean expression; 
The statement can be a single code instruction, or a block of code: 
if (expression) { 
statement1; 
statement2; 
statement3; 
} 
A block is a set of statements encloses by curly braces {} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 38 / 58
Examples 
here are two example of usage of if 
int x; 
... 
if (x % 2) 
printf(number %d is oddn, x); 
double a; 
if (a  0) { 
printf(a is negative!n); 
a = -a; 
printf(a is now positiven); 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 39 / 58 
Complete form 
In its most complete form: 
if (expression) 
statement1; 
else 
statement2; 
Of course, both statement1 and statement2 can be blocks of 
statements; 
if (x  0) { 
if (y  0) 
printf(Northeast.n); 
else 
printf(Southeast.n); 
} 
else { 
if (y  0) 
printf(Northwest.n); 
else 
printf(Southwest.n); 
} 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 40 / 58
Statements 
A statement can be: 
an expression; 
a if then else construct; 
a block of statements (recursive definition!) 
Expressions and statements are not the same thing! 
You can use expressions wherever you can use a statement 
You cannot use a statement where you see expression! 
For example, you cannot use a statement inside a if condition! 
But you can use another if as a statement 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 41 / 58 
Statements - 2 
You can write the following: 
if (x  0) if (y  0) printf(north eastn); 
else printf(south eastn); 
else if (y  0) printf(north westn); 
else printf(south westn); 
here if is used as a statement inside another if 
You cannot write the following: 
if (if (x  0)) ... 
in facts, an if condition can only be an expression! 
Remember: 
An expression has always a (numerical) value which is the result of 
an operation 
0 is interpreted as false, any other number is interpreted as true 
A statement may be an expression (in which case it has a 
numerical value), or something else 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 42 / 58
More on if conditions 
To check if variable i is between 1 and 10: 
if (i = 10  i= 1) ... 
or alternatively: 
if (1 = i  i = 10) ... 
Don’t use the following: 
if (1 = i = 10) ... 
(what happens? check out 
./examples/03.c_intro-examples/condition1.c) 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 43 / 58 
Common mistakes 
One common mistake is the following: 
int a = 5; 
if (a = 0) printf(a is 0n); 
else printf(a is different from 0n); 
What does the code above print on screen? (see 
./examples/03.c_intro-examples/condition2.c) 
The value of expression a = 0 (which is an assignment, not a 
comparison!) is 0, i.e. the value of a after the assignment 
Probably, the programmer wanted to say something else: 
if (a == 0) printf(a is 0n); 
else printf(a is different from 0n); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 44 / 58
Loops 
In many cases, we need to execute the same code many times, 
each time on a different set of values 
Example: 
Given an integer number stored in variable a, print “number is 
prime” if the number is prime (divisible only by 1 and by itself) 
To solve the problem, we need to check the remainder of the 
division between a and all numbers less than a. If it is always 
different from 0, then the number is prime 
However, we do not know the value of a before program execution; 
how many division should we do? 
Solution: use the while construct 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 46 / 58 
While loop 
The general form: 
while (expression) 
statement; 
As usual, statement can also be a block of statements 
Similar to an if, but the statement is performed iteratively while the 
condition is “true” (i.e. different from 0) 
Example: sum the first 10 numbers: 
int sum = 0; 
int i = 0; 
while (i  10) { 
sum = sum + i; 
i = i + 1; 
} 
printf(The sum of the first 10 numbers: %dn, sum); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 47 / 58
Break and continue statements 
Sometimes we need to go out of the loop immediately, without 
completing the rest of the statements. To do this we can use the 
break statement 
int i = 0; 
while (i  10) { 
i++; 
if ((i % 5) == 0) break; 
printf(%d is not divisible by 5n, i); 
} 
printf(Out of the loop); 
Another possibility is to continue with the next iteration without 
complete the rest of the statements: 
int i = 0; 
while (i  10) { 
i++; 
if (i % 5 != 0) continue; 
printf(%d is divisible by 5n, i); 
} 
printf(Out of the loopn); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 48 / 58 
Prime numbers 
isprime.c 
int main() 
{ 
int k, i, flag; 
printf(This program tests if a number is primen); 
printf(Insert a number: ); 
scanf(%d, k); 
flag = 1; 
i = 2; 
while (i  k) { 
if (k % i == 0) { 
printf(%d is a divisor: %d = %d x %dn, i, k, i, k/i); 
flag = 0; 
break; 
} 
i++; 
} 
printf(%d is , k); 
if (!flag) printf(not ); 
printf(primen); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 49 / 58
Loops 
if then else and while constructs are all we need to program 
It can be proved in theoretical computer science that with one loop 
construct and one selection construct, the language is equivalent to 
a Turing Machine, the simplest and more general kind of calculator 
However, sometimes using only while loops can be annoying 
The C language provides two more loop constructs: for loops and 
do-while loops 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 51 / 58 
For loop 
The most general form is the following: 
for(expr1; expr2; expr3) statement; 
expr1 is also called initialization; it is executed before entering the 
first loop iteration 
expr2 is also called condition; it is checked before every iteration; 
if it is false, the loop is terminated; 
if it is true, the iteration is performed 
expr3 is also called instruction; it is performed at the end of every 
iteration 
The most common usage is the following: 
for (i=0; i10; i++) 
printf(The value of i is now %dn, i); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 52 / 58
Sum the first 10 numbers 
int n = 10; 
int i; 
int sum = 0; 
for (i=0; in; i++) sum += i; 
printf(The sum of the first %d numbers is %dn, n, sum); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 53 / 58 
Prime numbers 
isprime2.c 
int main() 
{ 
int k, i, flag; 
printf(This program tests if a number is primen); 
printf(Insert a number: ); 
scanf(%d, k); 
flag = 1; 
for (i=2; ik/2; i++) 
if (k % i == 0) { 
printf(%d is a divisor: %d = %d x %dn, i, k, i, k/i); 
flag = 0; 
break; 
} 
printf(%d is , k); 
if (!flag) printf(not ); 
printf(primen); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 54 / 58
Equivalence between for and while 
We can always rewrite any while loop as a for loop, and vice versa 
for (expr1; expr2; expr3) statement; 
can be rewritten as: 
expr1; 
while (expr2) { 
statement; 
expr3; 
} 
On the other hand, the following while loop; 
while (expr) statement; 
can be rewritten as: 
for( ; expr ; ) statement; 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 55 / 58 
Exercises 
1 Given the following for loop, rewrite it as a while loop; 
int k, i=0; j=8; 
for (k=0; kj; k++) { 
i = k+j; 
j--; 
printf(i is now %dn, i); 
} 
2 Write a program that, given an integer number in input, prints on 
screen all prime factors of the number, 
For example, given 6, prints 2, 3 
given 24, prints 2, 2, 2, 3 
given 150, prints 2, 3, 5, 5 
etc. 
Suggestion: use a while loop initially 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 57 / 58
Exercises: strange for loops 
Since an expression can be pretty much everything, you can write lot 
of strange things with for loops 
1 Incrementing 2 variables with the comma operator: 
int i, j; 
for (i=0, j=0; i  5; i++, j+=2) 
printf( i = %d, j = %dn, i, j); 
What does the code above print on screen? 
2 What the code below prints on screen? 
int i; 
int g=0; 
for (i=0; i10; g += i++); 
printf(%d, g); 
G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 58 / 58

More Related Content

What's hot

What's hot (20)

C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
Introduction to C Programming - I
Introduction to C Programming - I Introduction to C Programming - I
Introduction to C Programming - I
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Com Ed 6 Prelim
Com Ed 6 PrelimCom Ed 6 Prelim
Com Ed 6 Prelim
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
C basics
C   basicsC   basics
C basics
 
C programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakilC programming slide day 01 uploadd by md abdullah al shakil
C programming slide day 01 uploadd by md abdullah al shakil
 
C Language
C LanguageC Language
C Language
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
C language
C languageC language
C language
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Chapter3
Chapter3Chapter3
Chapter3
 
C programming language
C programming languageC programming language
C programming language
 
C programmimng basic.ppt
C programmimng basic.pptC programmimng basic.ppt
C programmimng basic.ppt
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programming
 

Viewers also liked

Language Teaching Methodology 1G
Language Teaching Methodology 1GLanguage Teaching Methodology 1G
Language Teaching Methodology 1G
emma.a
 
Lec 07 image enhancement in frequency domain i
Lec 07 image enhancement in frequency domain iLec 07 image enhancement in frequency domain i
Lec 07 image enhancement in frequency domain i
Ali Hassan
 

Viewers also liked (20)

Aspiring to Oxbridge
Aspiring to OxbridgeAspiring to Oxbridge
Aspiring to Oxbridge
 
Writing engaging tutorials
Writing engaging tutorialsWriting engaging tutorials
Writing engaging tutorials
 
Ctutor
CtutorCtutor
Ctutor
 
English presentation
English presentationEnglish presentation
English presentation
 
Introduction to Digital Image Processing
Introduction to Digital Image ProcessingIntroduction to Digital Image Processing
Introduction to Digital Image Processing
 
Ee 583 lecture10
Ee 583 lecture10Ee 583 lecture10
Ee 583 lecture10
 
Image processing1 introduction
Image processing1 introductionImage processing1 introduction
Image processing1 introduction
 
Language Teaching Methodology 1G
Language Teaching Methodology 1GLanguage Teaching Methodology 1G
Language Teaching Methodology 1G
 
C tutorial for beginners - with puzzles
C tutorial for beginners - with puzzlesC tutorial for beginners - with puzzles
C tutorial for beginners - with puzzles
 
Ielts
IeltsIelts
Ielts
 
Digital Image Processing Notes - Akshansh
Digital Image Processing Notes - AkshanshDigital Image Processing Notes - Akshansh
Digital Image Processing Notes - Akshansh
 
Digital Image Processing: An Introduction
Digital Image Processing: An IntroductionDigital Image Processing: An Introduction
Digital Image Processing: An Introduction
 
DIGITAL IMAGE PROCESSING - LECTURE NOTES
DIGITAL IMAGE PROCESSING - LECTURE NOTESDIGITAL IMAGE PROCESSING - LECTURE NOTES
DIGITAL IMAGE PROCESSING - LECTURE NOTES
 
Lec 07 image enhancement in frequency domain i
Lec 07 image enhancement in frequency domain iLec 07 image enhancement in frequency domain i
Lec 07 image enhancement in frequency domain i
 
Basics of dip
Basics of dipBasics of dip
Basics of dip
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Digital Image Processing: Image Enhancement in the Frequency Domain
Digital Image Processing: Image Enhancement in the Frequency DomainDigital Image Processing: Image Enhancement in the Frequency Domain
Digital Image Processing: Image Enhancement in the Frequency Domain
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
Introduction to Digital image processing
Introduction to Digital image processing Introduction to Digital image processing
Introduction to Digital image processing
 

Similar to Fundamentals of c programming

Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 

Similar to Fundamentals of c programming (20)

Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
2.Overview of C language.pptx
2.Overview of C language.pptx2.Overview of C language.pptx
2.Overview of C language.pptx
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Intro cpp
Intro cppIntro cpp
Intro cpp
 
Programming.pptx
Programming.pptxProgramming.pptx
Programming.pptx
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
Learn C
Learn CLearn C
Learn C
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
Unit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptxUnit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptx
 
UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
 
Chaptr 1
Chaptr 1Chaptr 1
Chaptr 1
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
 
C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
 

More from NYversity

Programming methodology-1.1
Programming methodology-1.1Programming methodology-1.1
Programming methodology-1.1
NYversity
 
3016 all-2007-dist
3016 all-2007-dist3016 all-2007-dist
3016 all-2007-dist
NYversity
 
Programming methodology lecture28
Programming methodology lecture28Programming methodology lecture28
Programming methodology lecture28
NYversity
 
Programming methodology lecture27
Programming methodology lecture27Programming methodology lecture27
Programming methodology lecture27
NYversity
 
Programming methodology lecture26
Programming methodology lecture26Programming methodology lecture26
Programming methodology lecture26
NYversity
 
Programming methodology lecture25
Programming methodology lecture25Programming methodology lecture25
Programming methodology lecture25
NYversity
 
Programming methodology lecture24
Programming methodology lecture24Programming methodology lecture24
Programming methodology lecture24
NYversity
 
Programming methodology lecture23
Programming methodology lecture23Programming methodology lecture23
Programming methodology lecture23
NYversity
 
Programming methodology lecture22
Programming methodology lecture22Programming methodology lecture22
Programming methodology lecture22
NYversity
 
Programming methodology lecture20
Programming methodology lecture20Programming methodology lecture20
Programming methodology lecture20
NYversity
 
Programming methodology lecture19
Programming methodology lecture19Programming methodology lecture19
Programming methodology lecture19
NYversity
 
Programming methodology lecture18
Programming methodology lecture18Programming methodology lecture18
Programming methodology lecture18
NYversity
 
Programming methodology lecture17
Programming methodology lecture17Programming methodology lecture17
Programming methodology lecture17
NYversity
 
Programming methodology lecture16
Programming methodology lecture16Programming methodology lecture16
Programming methodology lecture16
NYversity
 
Programming methodology lecture15
Programming methodology lecture15Programming methodology lecture15
Programming methodology lecture15
NYversity
 
Programming methodology lecture14
Programming methodology lecture14Programming methodology lecture14
Programming methodology lecture14
NYversity
 
Programming methodology lecture13
Programming methodology lecture13Programming methodology lecture13
Programming methodology lecture13
NYversity
 
Programming methodology lecture12
Programming methodology lecture12Programming methodology lecture12
Programming methodology lecture12
NYversity
 
Programming methodology lecture11
Programming methodology lecture11Programming methodology lecture11
Programming methodology lecture11
NYversity
 
Programming methodology lecture10
Programming methodology lecture10Programming methodology lecture10
Programming methodology lecture10
NYversity
 

More from NYversity (20)

Programming methodology-1.1
Programming methodology-1.1Programming methodology-1.1
Programming methodology-1.1
 
3016 all-2007-dist
3016 all-2007-dist3016 all-2007-dist
3016 all-2007-dist
 
Programming methodology lecture28
Programming methodology lecture28Programming methodology lecture28
Programming methodology lecture28
 
Programming methodology lecture27
Programming methodology lecture27Programming methodology lecture27
Programming methodology lecture27
 
Programming methodology lecture26
Programming methodology lecture26Programming methodology lecture26
Programming methodology lecture26
 
Programming methodology lecture25
Programming methodology lecture25Programming methodology lecture25
Programming methodology lecture25
 
Programming methodology lecture24
Programming methodology lecture24Programming methodology lecture24
Programming methodology lecture24
 
Programming methodology lecture23
Programming methodology lecture23Programming methodology lecture23
Programming methodology lecture23
 
Programming methodology lecture22
Programming methodology lecture22Programming methodology lecture22
Programming methodology lecture22
 
Programming methodology lecture20
Programming methodology lecture20Programming methodology lecture20
Programming methodology lecture20
 
Programming methodology lecture19
Programming methodology lecture19Programming methodology lecture19
Programming methodology lecture19
 
Programming methodology lecture18
Programming methodology lecture18Programming methodology lecture18
Programming methodology lecture18
 
Programming methodology lecture17
Programming methodology lecture17Programming methodology lecture17
Programming methodology lecture17
 
Programming methodology lecture16
Programming methodology lecture16Programming methodology lecture16
Programming methodology lecture16
 
Programming methodology lecture15
Programming methodology lecture15Programming methodology lecture15
Programming methodology lecture15
 
Programming methodology lecture14
Programming methodology lecture14Programming methodology lecture14
Programming methodology lecture14
 
Programming methodology lecture13
Programming methodology lecture13Programming methodology lecture13
Programming methodology lecture13
 
Programming methodology lecture12
Programming methodology lecture12Programming methodology lecture12
Programming methodology lecture12
 
Programming methodology lecture11
Programming methodology lecture11Programming methodology lecture11
Programming methodology lecture11
 
Programming methodology lecture10
Programming methodology lecture10Programming methodology lecture10
Programming methodology lecture10
 

Recently uploaded

Recently uploaded (20)

Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdf
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Forest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDFForest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDF
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 

Fundamentals of c programming

  • 1. Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant’Anna – Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 1 / 58 Outline 1 First steps 2 Declarations and definitions 3 Variables Simple Input/output First exercises Advanced operators 4 Statements and control flow If then else While loop For loop Exercises G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 2 / 58
  • 2. My first C program Let’s start with a classic: hello.c #include <stdio.h> int main() { printf("Hello world!n"); return 0; } include includes definitions for library functions (in this case, the printf() function is defined in header file stdio.h) main function this function must always be present in a C program. It is the first function to be invoked (the entry point) return end of the function, returns a value to the shell G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 4 / 58 How to compile and run the program The C language is a compiled language It means that the above program must be translated into a binary code before being executed The compiler does the job reads the source file, translates it into binary code, and produces an executable file In Linux, the following command line produces executable file hello from source file hello.c gcc hello.c -o hello In Windows (with DevC++), you must build the program When you run the program (from a Linux shell, type ./hello, from Windows, click on Run), you obtain: (in Windows you may not be able to see the output because the shell is automatically closed!) Hello world! G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 5 / 58
  • 3. Compiling the code The translation from high-level language to binary is done by the compiler (and the linker) the compiler translates the code you wrote in the source file (hello.c) the linker links external code from libraries of existing functions (in our case, the printf() function for output on screen) compile & link executable std library (printf) hello.c gcc hello.c −o hello hello Figure: Compiling a file G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 6 / 58 Multiple source files A program can consist of multiple source files Every source file is called module and usually consists of a set of well-defined functions that work together every source file is compiled separately (it is a compilation unit) to produce an object file (extension: .o or .obj) all objects files and libraries are then linked together to produce an executable We will see later how it works G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 7 / 58
  • 4. Running a program To execute a program, you must tell the Operating System to load the program in main memory (RAM) start executing the program instructions sequentially The OS is itself a program! It is a high-order program that controls the execution of user programs The OS can: Execute several user programs concurrently or in parallel suspend or kill a user program coordinate and synchronize user programs let them communicate and exchange data and many other things! G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 8 / 58 Declarations, functions, expressions A C program is a sequence of global declarations and definitions declarations of global variables and functions definitions of variables and functions often, declarations are implicit (the definition is an implicit declaration) Examples: int a; // declaration + definition int b = 10; // declaration + definition + init int f(int); // declaration only int f(int p) // definition { ... } int g() // declaration + definition { } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 10 / 58
  • 5. Functions The code goes inside functions There must be always at least one definition of a function called main In the hello example: hello.c int main() { printf("Hello world!n"); return 0; } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 11 / 58 Anatomy of the main function There can be another form of main function: int main(int argc, char *argv[]) { ... } main is the function name, and must be unique in a program there cannot be two functions with the same name int is the return type (will see later) between () parenthesis we have the list of parameters with their type, separated by commas: in the example above, two parameters, argc and argv between {} parenthesis, we have the function body: the code that is executed when the function is called The OS implicitly calls the main function when the program is launched the main function is also called the program entry point G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 12 / 58
  • 6. Variables and types A variable is a location in memory with a symbolic name A variable is used as temporary or permanent storage of data to perform complex computation In C, every variable must have a type Predefined types in C: int an integer number (usually 32 bits) char a ASCII character (8 bits) float floating point number, single precision (32 bits) double floating point number, double precision (64 bits) A type dictates the variable range (or domain) (from the number of bits) and the operations you can perform on a variable G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 14 / 58 Variables definition Usually, declaration and definition coincide for variables The definition consists of the type keyword followed by the name of the variable, followed by the “;” symbol Examples int a; /* an integer variable of name a */ double b; /* a double-precision floating point */ char c; /* a character */ ... a = 10; /* assignment: a now contains 10 */ b = b + 1.5; /* after assignment, b is equal to the previous value of b plus 1.5 */ c = ’a’; /* c is equal to the ASCII value of character ’a’ */ G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 15 / 58
  • 7. Constants Constants are numeric or alphabetic values that can be used in operations on variables or in functions Example: const double pi = 3.1415; /* a double precision constant */ int a = 325; /* 325 is a constant integer */ char c = ’?’; /* ’?’ is a constant character */ printf("Hello world!n"); /* "Hello world!n" is a * * constant string */ G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 16 / 58 Variable names Variable names cannot start with a number cannot contain spaces cannot contain special symbols like ’+’, ’-’, ’*’, ’/’, ’%’, etc. cannot be arbitrarily long (255 char max) cannot be equal to reserved keywords (like int, double, for, etc.) G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 17 / 58
  • 8. Variable initialization It is possible to assign an initial value to a variable during definition If you do not specify a value, the initial value of the variable is undefined It is good programming practice to always initialize a variable Many programming errors are due to programmers that forget to initialize a variable before using it int a = 0; /* the initial value is 0 */ int i; /* undefined initial value */ int b = 4; b = i + 5; /* error! the value of i is not defined! */ G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 18 / 58 Operations on variables The basic arithmetic operators are: + addition - subtraction * multiplication / division % modulus (remainder of the integer division) Notes: when division is applied to integers, the result is an integer (it truncates the decimal part) modulus can only be applied to integers multiplication, division and modulus have precedence over addition and subtraction to change precedence, you can use parenthesis G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 19 / 58
  • 9. Expressions A C program is a sequence of expressions, and expression is a combination of operators on variables, constants and functions Examples of expressions: /* definitions of variables */ int a, b; int division; int remainder; double area_circle; double radius; ... /* expressions */ a = 15; b = 6; division = a / b; remainder = a % b; radius = 2.4; area_circle = 3.14 * radius * radius; G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 20 / 58 Assignment and expressions Assigning a value to a variable is itself an expression area_circle = 3.14 * radius * radius; The above expression is composed by three elements: the operator is = the left operand must always be a variable name (cannot be another expression!) the right operand can be any expression, (in our case two multiplications) the right operand is evaluated first, and then the result is assigned to the left operand (the variable) area_circle / 3.14 = radius * radius the code above is illegal! Why? G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 21 / 58
  • 10. Assignment expressions The following expression is perfectly legal: int a, b; b = a = 5; You must read it from right to left: a=5 is first evaluated by assigning value 5 to variable a; the result of this expression is 5 then, the result is assigned to variable b (whose value after assignment is hence 5) What are the values of a and b after the following two expressions? int a, b; b = (a = 5) + 1; b = a = 5 + 1; G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 22 / 58 Formatted output To output on screen, you can use the printf library function exprintf.c /* fprintf example */ #include <stdio.h> int main() { printf ("Characters: %c %c n", ’a’, 65); printf ("Decimals: %d %ldn", 1977, 650000); printf ("Preceding with blanks: %10d n", 1977); printf ("Preceding with zeros: %010d n", 1977); printf ("Some different radixes: %d %x %o %#x %#o n", 100, 100, 100, 100, 100); printf ("floats: %4.2f %+.0e %E n", 3.1416, 3.1416, 3.1416); printf ("Width trick: %*d n", 5, 10); printf ("%s n", "A string"); return 0; } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 24 / 58
  • 11. Formatted Input To input variables from the keyboard, you can use the scanf library function exscanf.c /* scanf example */ #include <stdio.h> int main () { char str [80]; int i; printf ("Enter your family name: "); scanf ("%s",str); printf ("Enter your age: "); scanf ("%d",&i); printf ("Mr. %s , %d years old.n",str,i); printf ("Enter a hexadecimal number: "); scanf ("%x",&i); printf ("You have entered %#x (%d).n",i,i); return 0; } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 25 / 58 Exercises 1 Write a program that asks the user to enter the radius of a circle, computes the area and the circumference define variables and initialize them use scanf to input radius variable compute the values formatted input on screen 2 Write a program that asks for two integer numbers a and b, computes the quotient and the remainder, and prints them on screen G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 27 / 58
  • 12. Shortcuts It is possible to combine assignment with common operators, as follows: a += 5; // equivalent to a = a + 5; x /= 2; // equivalent to x = x / 2; y *= x + a; // equivalent to y = y * (x+a); In general var <op>= <expr>; // equivalent to var = var <op> (<expr>); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 29 / 58 Increment / decrement If you just need to increment/decrement, you can use the following shortcuts x++; // equivalent to x = x + 1; ++x; // equivalent to x = x + 1; y--; // equivalent to y = y - 1; --y; // equivalent to y = y - 1; Of course, it can only be used on variables; (a+b)++; // compiler error! cannot increment // an expression x = (a+b)++; // error again: use x = (a+b)+1; G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 30 / 58
  • 13. Pre and post-increment What is the difference between x++ and ++x? They are both expressions that can be used inside other expressions (like assignment), as follows; int a, x; x = 5; a = ++x; // what is the value of a after the assignment? The only difference is the value of the expression: x++ has the value of x before the increment; ++x has the value of x after the increment; x = 5; a = x++; // value of a is 5, b is 6 x = 5; a = ++x; // value of a is 6, b is 6 G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 31 / 58 Boolean operators In there is no boolean type Every expression with a value equal to 0 is interpreted as false Every expression with a value different from 0 is interpreted as true It is possible to use the following boolean operators: && logical and operator || logical or operator ! logical not operator It is possible to interpret integer values as booleans and vice versa int a, b, c; a = 0; b = 5; c = a && b; // after assignment, c is 0; c = a || b; // after assignment, c is 1; c = !b; // after assignment, c is 0; G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 32 / 58
  • 14. Comparison operators These operators compare numbers, giving 0 or 1 (hence a boolean value) as result < less than <= less than or equal to > greater than >= greater than or equal to == equal != not equal int a = 7; int b = 10; int c = 7; int res; res = a < b; // res is 1 res = a <= c; // res is 1 res = a < c; // res is 0 res = b == c; // res is 0 (will come back to these later) G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 33 / 58 Binary operators It is possible to do binary operations on integer variables using the following operators: & binary (bit-to-bit) and | binary (bit-to-bit) or binary (bit-to-bit) not (complement) unsigned char a = 1; // in binary: 0000 0001 unsigned char b = 2; // in binary: 0000 0010 unsigned char c = 5; // in binary: 0000 0101 unsigned char d; d = a b; // d is now 0000 0000 d = a c; // d is now 0000 0001 d = a | b; // d is now 0000 0011 d = ~a; // d is now 1111 1110 G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 34 / 58
  • 15. Execution flow Usually, instructions are executed sequentially, one after the other, until the end of the function However, in many cases we must execute alternative instructions, depending on the value of certain expressions Also, sometimes we need to repeat instructions a number of times, or until a certain condition is verified we need to control the execution flow G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 36 / 58 If statement To select alternative paths, we can use the if then else statement The general form is the following: if (expression) statement; expression must be a boolean expression; The statement can be a single code instruction, or a block of code: if (expression) { statement1; statement2; statement3; } A block is a set of statements encloses by curly braces {} G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 38 / 58
  • 16. Examples here are two example of usage of if int x; ... if (x % 2) printf(number %d is oddn, x); double a; if (a 0) { printf(a is negative!n); a = -a; printf(a is now positiven); } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 39 / 58 Complete form In its most complete form: if (expression) statement1; else statement2; Of course, both statement1 and statement2 can be blocks of statements; if (x 0) { if (y 0) printf(Northeast.n); else printf(Southeast.n); } else { if (y 0) printf(Northwest.n); else printf(Southwest.n); } G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 40 / 58
  • 17. Statements A statement can be: an expression; a if then else construct; a block of statements (recursive definition!) Expressions and statements are not the same thing! You can use expressions wherever you can use a statement You cannot use a statement where you see expression! For example, you cannot use a statement inside a if condition! But you can use another if as a statement G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 41 / 58 Statements - 2 You can write the following: if (x 0) if (y 0) printf(north eastn); else printf(south eastn); else if (y 0) printf(north westn); else printf(south westn); here if is used as a statement inside another if You cannot write the following: if (if (x 0)) ... in facts, an if condition can only be an expression! Remember: An expression has always a (numerical) value which is the result of an operation 0 is interpreted as false, any other number is interpreted as true A statement may be an expression (in which case it has a numerical value), or something else G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 42 / 58
  • 18. More on if conditions To check if variable i is between 1 and 10: if (i = 10 i= 1) ... or alternatively: if (1 = i i = 10) ... Don’t use the following: if (1 = i = 10) ... (what happens? check out ./examples/03.c_intro-examples/condition1.c) G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 43 / 58 Common mistakes One common mistake is the following: int a = 5; if (a = 0) printf(a is 0n); else printf(a is different from 0n); What does the code above print on screen? (see ./examples/03.c_intro-examples/condition2.c) The value of expression a = 0 (which is an assignment, not a comparison!) is 0, i.e. the value of a after the assignment Probably, the programmer wanted to say something else: if (a == 0) printf(a is 0n); else printf(a is different from 0n); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 44 / 58
  • 19. Loops In many cases, we need to execute the same code many times, each time on a different set of values Example: Given an integer number stored in variable a, print “number is prime” if the number is prime (divisible only by 1 and by itself) To solve the problem, we need to check the remainder of the division between a and all numbers less than a. If it is always different from 0, then the number is prime However, we do not know the value of a before program execution; how many division should we do? Solution: use the while construct G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 46 / 58 While loop The general form: while (expression) statement; As usual, statement can also be a block of statements Similar to an if, but the statement is performed iteratively while the condition is “true” (i.e. different from 0) Example: sum the first 10 numbers: int sum = 0; int i = 0; while (i 10) { sum = sum + i; i = i + 1; } printf(The sum of the first 10 numbers: %dn, sum); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 47 / 58
  • 20. Break and continue statements Sometimes we need to go out of the loop immediately, without completing the rest of the statements. To do this we can use the break statement int i = 0; while (i 10) { i++; if ((i % 5) == 0) break; printf(%d is not divisible by 5n, i); } printf(Out of the loop); Another possibility is to continue with the next iteration without complete the rest of the statements: int i = 0; while (i 10) { i++; if (i % 5 != 0) continue; printf(%d is divisible by 5n, i); } printf(Out of the loopn); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 48 / 58 Prime numbers isprime.c int main() { int k, i, flag; printf(This program tests if a number is primen); printf(Insert a number: ); scanf(%d, k); flag = 1; i = 2; while (i k) { if (k % i == 0) { printf(%d is a divisor: %d = %d x %dn, i, k, i, k/i); flag = 0; break; } i++; } printf(%d is , k); if (!flag) printf(not ); printf(primen); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 49 / 58
  • 21. Loops if then else and while constructs are all we need to program It can be proved in theoretical computer science that with one loop construct and one selection construct, the language is equivalent to a Turing Machine, the simplest and more general kind of calculator However, sometimes using only while loops can be annoying The C language provides two more loop constructs: for loops and do-while loops G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 51 / 58 For loop The most general form is the following: for(expr1; expr2; expr3) statement; expr1 is also called initialization; it is executed before entering the first loop iteration expr2 is also called condition; it is checked before every iteration; if it is false, the loop is terminated; if it is true, the iteration is performed expr3 is also called instruction; it is performed at the end of every iteration The most common usage is the following: for (i=0; i10; i++) printf(The value of i is now %dn, i); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 52 / 58
  • 22. Sum the first 10 numbers int n = 10; int i; int sum = 0; for (i=0; in; i++) sum += i; printf(The sum of the first %d numbers is %dn, n, sum); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 53 / 58 Prime numbers isprime2.c int main() { int k, i, flag; printf(This program tests if a number is primen); printf(Insert a number: ); scanf(%d, k); flag = 1; for (i=2; ik/2; i++) if (k % i == 0) { printf(%d is a divisor: %d = %d x %dn, i, k, i, k/i); flag = 0; break; } printf(%d is , k); if (!flag) printf(not ); printf(primen); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 54 / 58
  • 23. Equivalence between for and while We can always rewrite any while loop as a for loop, and vice versa for (expr1; expr2; expr3) statement; can be rewritten as: expr1; while (expr2) { statement; expr3; } On the other hand, the following while loop; while (expr) statement; can be rewritten as: for( ; expr ; ) statement; G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 55 / 58 Exercises 1 Given the following for loop, rewrite it as a while loop; int k, i=0; j=8; for (k=0; kj; k++) { i = k+j; j--; printf(i is now %dn, i); } 2 Write a program that, given an integer number in input, prints on screen all prime factors of the number, For example, given 6, prints 2, 3 given 24, prints 2, 2, 2, 3 given 150, prints 2, 3, 5, 5 etc. Suggestion: use a while loop initially G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 57 / 58
  • 24. Exercises: strange for loops Since an expression can be pretty much everything, you can write lot of strange things with for loops 1 Incrementing 2 variables with the comma operator: int i, j; for (i=0, j=0; i 5; i++, j+=2) printf( i = %d, j = %dn, i, j); What does the code above print on screen? 2 What the code below prints on screen? int i; int g=0; for (i=0; i10; g += i++); printf(%d, g); G. Lipari (Scuola Superiore Sant’Anna) The C language February 29, 2012 58 / 58