Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

C Programming 2

The document discusses various C instructions including arithmetic operations, type conversions, control flow instructions like if/else, loops, and switch statements. It provides examples and explanations of how each instruction works in C.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Programming 2

The document discusses various C instructions including arithmetic operations, type conversions, control flow instructions like if/else, loops, and switch statements. It provides examples and explanations of how each instruction works in C.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Getting Started with C

Type declaration
C provides
id a wide
id range off types. Th
The most common are

There are also several variants on these types.


Getting Started with C
C Instructions
Arithmetic: to perform arithmetic operation between
constants and variables
• Consist of variable name on the LHS side of ‘= ‘ variable names
and constants connected by arithmetic operarions
• +, ‐, *, /, %
• Integer
I t mode,
d Real
R l mode
d and
d Mi
Mix mode
d
Getting Started with C
C Instructions
• Integer float conversions
• int
int‐intint,
intint, real
real‐realreal,
realreal, int
int‐realreal
realreal
• Type conversion in Assigments
• Value of the expressin is promoted or demoted depending
on the type of variable on LHS
• Hierarchy of operations
• The ppriorityy or p
precedence in which the operations
p in an
arithmetic statements are performed
• */%
+‐
=
Getting Started with C
C Instructions
• Hierarchy of operations
• The priority or precedence in which the operations in an
arithmetic statements are performed
• */%
+‐
=
• parenthesis can be used change the precedence
• SSame or equall priority
i it operators
t are performed
f d as they
th
are appeared
Getting Started with C
C Instructions
• Control Instructions
• Specify the order in which the various instructions in a
program are to be executed
• Determine the ‘flow
flow of control
control’
• Sequence control instruction
• Selection/Decision
• Repetitions/loop
p / p
• Case
Getting Started with C
C Instructions‐ Selection/Decision
• The if statement
• The if statement controls conditional branching. The body of an
if statement is executed if the value of the expression is
nonzero..
• Syntax
if (conditional expression )
statement
• In this form of syntax, if expression is true (nonzero), statement
i executed.
is t d If expression
i iis false,
f l statement
t t t is
i ignored.
i d
Getting Started with C
C Instructions
• Syntax
if (conditional expression )
statement
• Relational operators
• ==, >, <, >=, <=, !=
• Logical operators
• && ‐ logical AND,
• || ‐ logical OR
• ! – logical NOT
Getting Started with C
C Instructions
• The if – else statement
• The if – else statement controls conditional branching. The
body of an if statement is executed if the value of the
expression is nonzero, otherwise the body of else
statement is executed .
• Syntax
if (conditional expression )
statement ;
else
l
statement ;
Getting Started with C
C Instructions

• Forms of if‐else • if (condition)


statement;
• if (condition) else
l {
statement; if (condition)
else statement;
statement; else (condition) Nested if
• if (condition) statement;
statement; …….
else if (condition) }
statement;
else
statement;
…….
Getting Started with C
C Instructions
• Hierarchy of Logical operators
!
*/%
+‐
< > <= >=
== !=
&&
||
=
Getting Started with C
C Instructions
• Ex1 • Ex2
void main(){ void main(){
int I; int I;
printf(“Enter a value”); printf(“Enter a value”);
scanf(“%d”,&i); scanf(“%d”,&i);

if(i=5) if(i= =5);


printf(“You entered 5”); printf(“You entered 5”);
else
printf(“you entered }
something other than 5”);
}
Getting Started with C
C Instructions
• Conditional operators “?” And “:” (ternary operators)
A fore shorthand of if‐then‐else
Syntax:
expr1?expr2:expr3
• if expr1 is true then expr2 will be returned otherwise expr3
will be returned

• Example
• int a,b;
scanf(“%d”,&a);
f(“%d” & )
b=(a>=10?5:15);
Getting Started with C
C Instructions
• Loop control structures
• Repeating a segment of the program either a specified
number of times or until a given condition is met.
• for
• while
• do ‐ while
Getting Started with C
C Instructions: Loop control structures
• for Statement
• Allows the programmer to execute a block of code for a
specified number of times
• The for loop works well where the number of iterations of
the loop is known
• The head of the loop consists of three parts separated by
semicolons
• Syntax
S t
• for (initial‐statement; condition; iteration‐statement)
body‐statement;
Getting Started with C
C Instructions: Loop control structures
• for Statement
• The head of the loop consists of three parts separated by
semicolons
• Syntax
• for (initial‐statement; condition; iteration‐statement)
body statement;
body‐statement;
• The first is run before the loop is entered. This is usually the initialisation of
the loop variable. In most cases setting loop counter to initial value
• The second is a test, the loop is exited when this returns false.
• The third is a statement to be run every time the loop body is completed.
This is usually an increment/decrement of the loop counter.
Getting Started with C
C Instructions: Loop control structures Shorthand operators
• for Statement Increment operator: ++
Decrement operator: ‐ ‐
• Example:
xample: Post‐increment: i++;;
Pre‐increment ++i;
• for(i=1; i<=10; i=i+1)
printf(“\n%d”
printf( \n%d , i); Oper: Short: Expr:
+= X+=2; X=X+2;
• for(i=10; i>=1; i=i‐1) ‐= X‐=2; X=X‐2;
printf(“\n%d”
printf( \n%d , i); *
*= X* 2
X*=2; X X*2
X=X*2;
/= X/=2; X=X/2;
• Nested loops %= X%=2 X=X%2;

• Loop within the body of a loop


Getting Started with C
C Instructions: Loop control structures
• while Statement
• The loop keeps repeating an action until an associated test
returns false.
• Useful when the programmer does not know in advance
how many times the loop will be repeated
• while( condition)
body‐statement;
• Warning
W i
• Initialize the condition’s variable before loop header
• To avoid infinite loop make sure to have a statements that changes
while condition within the body
Getting Started with C
C Instructions: Loop control structures
The do while Loop
• Very similar to the while loop except that the test occurs at the end of the
loop body
• Guarantees that the loop is executed at least once before continuing
• Used where data is to be read and verified
do
body‐statement;
while( condition)

Example

do {
printf("Enter 0 to terminate :");
scanf("%d", &input_value);
} while (input_value != 0)
Getting Started with C
C Instructions: Loop control structures
The switch Statement
• Another form of the multi way decision.
decision
• Can only be used in certain cases where;
• Only one variable is tested, all branches must depend on the value of
that variable.
• The variable must be an integral type. (int, long, short or char).
• Each possible value of the variable can control a single branch

• A default branch may optionally be used to trap all unspecified


cases.
Getting Started with C
C Instructions: Loop control structures
The switch Statement
Syntax
switch (variable) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐
d f lt
default:
statement(s);
break;
}
Getting Started with C
C Instructions: Loop control structures
The switch Statement
Example:
Write a program to read a grade value and print the
relevant massage as follows
A – Excellent
B – good
C – Fair
D – Poor
E, F – Very poor
Getting Started with C
C Instructions:
break and continue
• break inside a switch causes to go to the end of the switch
• Inside a for or while causes to loop exit
• continue, only valid inside a loop, causes to go to the top of the
loop
p
Getting Started with C
C Instructions:
Array:
• A collection of homogeneous elements stored in a set of
consecutive memory locations
• Traditionally fixed, static size specified at compile time
• Each item in the arrayy is called an element and accessed byy its
index. Indices start with 0
0 1 2 3 4 5 6 7 8
A

A[0] A[1] [ ]
A[8]
Getting Started with C
C Instructions:
Array:
• Declaration:
• <datatype> arrayName[size];
• int marks[9];
• marks[0]=50;
k [0] 50
• marks[1]=65;
0 1 2 3 4 5 6 7 8
marks
50 65
marks[0] marks[8]
marks[1]
Getting Started with C
C Instructions:
Array: Character arrays (strings)
• Strings are arrays of characters
• The special character ‘\0’ (NULL) is used to indicate the end of
the string
• Example
char
h name[40];
[40] name
0 1 2 3
name[0]='S'; S a m \0
name[1]='a';
name[2]='m';
name[3]='\0';
Getting Started with C
C Instructions:
Array: Character arrays (strings)
String manipulation using string.h

strcp (str1 str2)


strcpy(str1,str2) Cop str2 into str1
Copy
strcat(str1,str2) Concatenate str1 onto end of the str2
strcmp(str1,str2)
p( , ) Compare
p str1 with str2 and returns 0 if equal,
q ,
otherwise nonzero
strlen(str1) Returns the length of str1
Getting Started with C
C Instructions:
Array: Character arrays (strings)
Reading strings: fgets
Syntax:
y fgets(str,sizeof(str),stdin);
fg ( , f( ), );
Including end of line character read into the array str
Getting Started with C
C Instructions:
Array: Multiple Dimentional Arrays
A
Array can have
h more than
th one di
dimension
i
<dataType > arrayName[d1][d2]
Syntax: fgets(str,sizeof(str),stdin);
C allows the programmer to use as many dimensions as needed
Initializing
1 D : int x[5] = {5,3,4,2,1};
1‐D {5 3 4 2 1} / int x[ ] = {5 {5,3,4,2,1};
3 4 2 1}
char name[5]=“Sam”; / char name[ ] = “Sam”;
char name[5] = {{‘S’,
S , ‘a’,
a , ‘m’,
m , ‘\0’};
\0 };
2‐D : int y[2][4]={ {2,4,6,4}, {6,7,2,1} };
Getting Started with C
C Instructions:
Reading and Printing Numbers

Integer type
t pe Con ersion
Conversion Si e in Bytes
Size B tes
Signed short %h 2
Signed
g int %d 2 or 4
Signed long int %ld 4
Unsigned short int %H 2
Unsigned int %u 2 or 4
unsigned long int %lu 4
Getting Started with C
C Instructions:
Reading and Printing Numbers
Float type Conversion Size in Bytes
float %f 4
double %lf 8
Long double %L 8

Hexadecimal and octal

Hexa %0x
Octal %o
V i bl Scopes
Variable S and
d Functions
F ti
Scope and Class
Scope: The area of the program where the variable is valid
Global variables: A variable which is valid everywhere in the
program. Its scope is the whole program
Local variables: The scope of a local variable is limited to the
block where it is declared. A block is a section of code
enclosed in { }
• possible to declare local variables with same names as
global (That hides the global variable to that block)
Variable Scopes and Functions
Scope and Class
Class: It tells the compiler where to store the data, such as on the
stack or on the heap
Class of a variable may either permanent or temporary
Global variables are permanent , and are created and initialized
before the program starts. (in heap)
Temporary (automatic) variables are allocated from Stack at the
beginning of the block. All local variables are temporary unless
th are static
they t ti
Example: count number of visits to a function
Variable Scopes and Functions
Functions
 A group ( unit) of commonly used code that can be used
repeatedly ‐‐ Reuse is one of the main reasons for having a
function. E.g. printf()

 A subroutine that takes the control of the main program and


return back.
 The main() function: A special functions that is called at the
beginning of the program. All the other functions directly or
i di t called
indirect ll d from
f main()
i ()
Variable Scopes and Functions
Functions
Functions are declared like variables
returnType functionName([parameters])
Function prototype
a declaration of a function that omits the function body but
does specify the function's name, arity, argument types and
return type.
In a prototype, argument names are optional,
F ti d
Function definition
fi iti
Specifies what a function does, a function prototype can be
thought of as specifying its interface
interface.
Variable Scopes and Functions
Functions
Parameter Passing
The arguments passed to function can be of two types namely
Values passed
Reference or Address passed

Parameter by values: Values passed


When a value is passed to a function,
function a copy of that value gets
made in the stack.
E
Example
l : printSquare(int
i tS (i t x);
)
Pointers
Memory and Variables
 Computer memory holds data of all kinds like floats, ints, …
 Each byte of memory is identified by an integer.
 These integers increase sequentially as you move up through
memory.
 it as a bunch of numbered boxes, where each box holds a byte
of data.
data The number that represents each box is called its
address.
 Not all data types use just a byte depending on the system
they use one or more bytes. (Use the sizeof() operator to
determine how many bytes of memory a certain type uses)
 Pointers
P i t are theth address
dd off d
data
t
o An int can be 10, a pointer can be the address of data
Pointers
Memoryy and Variables
 Getting the address of a data?
 use the address‐of operator (ampersand: “&”) to find the
address of the data.
 Example:
int x=12;
printf(“address of x is %p”,&x);

You might also like