C Programming LECTURE August 19 2019 NEW 1A
C Programming LECTURE August 19 2019 NEW 1A
Characteristics of Computers:
Perfect accuracy
Infinite patience
Flawless memory
Unimaginable speed
Program –g a set of instructions for a computer to follow(execute).
Software – the collection of programs used by a computer.
Hardware – the physical machines that make up a computer installation.
Input Output
Device Device
Figure: A Typical Computer Installation
Monitor
Keyboard (Display
screen)
CPU
Floppy Disk / Printer
Flash disk Main
Memory
Tape
Drive
2 Kinds of Algorithms:
1. Partial algorithm – an algorithm that might not end.
Example: Computerized airline reservation/ticketing systems, Automated teller machines (ATMs)
2. Total algorithm – an algorithm that is guaranteed to end.
Machine language – the native language of a computer, programs written in this language consists of zeros and ones.
Compiler – a program that translates a high level language to a machine language.
Source program – the input program to a compiler.
Object code or Object program – translated program, output of the compiler.
Operating System – the main systems program on a computer which controls and manages all other programs.
Examples: Windows 95, 98, 2000, NT, Unix, Linux
Flowchart
Flowchart – a diagram representing the logical sequence in which a combination of steps or operations is to be
performed. It is the blueprint of a program.
– a two-dimensional representation of an algorithm; the predefined graphic symbols of a flowchart are used to
indicate the various operations and the flow of control.
Program Data
Computer
Output
Input “Data”
Program of Program
Compiler
Computer
Machine language
program
Computer
Output of
Program
2 Phases of Program Design Process:
1. Problem solving phase – its result is an algorithm for solving the problem.
2. Implementation phase – its result is a working program.
Start
Problem
definition
Coding
Algorithm algorithm
design as a program
Desktop Testing
testing
Working
program
Iterative Enhancement – the process of first designing a simple working (correct) program and then adding features and
refinements later.
Syntax of a programming language – the rules on how to construct a statement/instruction. Refers to the spelling and
grammar of a programming language. Format of programming constructs.
Semantics – refers to the meaning of programming constructs (program statements).
Origin of the C Programming Language
BCPL - older language developed by Martin Richards
B - invented by Ken Thompson
C - invented by Dennis Ritchie in 1970s which was implemented first in Unix operating system at Bells laboratory.
ANSI C - the standard C language created in 1983. ANSI is acronym for American National Standards Institute.
Turbo C - fully implements the ANSI C.
C language - considered as a middle-level language which means that it combines elements of high-level language
with the functionalism of assembly language (low-level language).
- allows the manipulation of bits, bytes, and memory addresses.
- has only 32 keywords (27 original from Ritchie and Kernighan plus 5 from ANSI committee).
- a structured language which means it compartmentalize code and data. Compartmentalization is the
language's ability to section off and hide from the rest of the program all information and instructions
necessary to perform a specific task.
Note: Each header file contains definitions of predefined or built-in functions belonging to that header file.
2 Types of Variables:
1. Global variable – a variable whose scope is the entire program. Any function in the program have
access to it.
2. Local variable - a variable whose scope is only the function where it is declared. No other function in the program
have access to it except the function that declares it.
Constant - a programming object whose value is fixed.
Identifiers – the names used to reference variables, constants, functions, labels, and other user-defined objects.
- A valid identifier consists of letters, digits, underscore and starts with a letter.
Data Type – a type or category of data. Each variable can hold only one type of data.
const int a;
const int a = 5;
Conversion Specifications:
%d - print as decimal integer
%6d - print as decimal integer, 6 char wide
%f - print as floating point
%6f - print as floating point, 6 chars wide
%.2f - print as floating point, 2 chars after decimal pt.
%6.2f - print as floating point, 6 chars wide & 2 chars after decimal pt.
Escape Sequences:
\a -alert (bell) character
\b - backspace
\n - newline
\r - carriage return
\t - horizontal tab
\\ - backslash
\? - question mark
\' - single quote
\" - double quote
\000 - octal number
\xhh - hexadecimal number
char fname[10];
gets(fname);
scanf(“%s”,fname);
fname=&fname[0]
PRINTF Format Specifiers: %char
Char Format (displays…)
c single char
d decimal
i signed decimal integer
e scientific notation, with exponent
f decimal floating point, without exponent
g uses %e or %f, whichever is shorter, trailing zeros, decimal point will not be displayed.
o octal without leading zero
s string
u unsigned decimal integer
x hexadecimal integer, without leading 0x
% % itself
p pointer
Flag Meaning
- data item is left-justified
+ sign for signed numerical data item
0 causes leading zeros to appear instead of leading blanks
blank space
blank space will precede each positive signed numerical data item
# causes octal and hexadecimal data items to be preceded by 0 or 0x respectively(with o- or x-type conversion)
# causes a decimal point to be present in all floating-pt numbers, even if data item is a whole no. (with e-, f-, or g-
type conversion)
Prefix Meaning
digits minimum field-width
.digits number of digits printed at the right of the decimal pt. (precision)
h short data item
l long data item (long int, long unsigned int or double)
L long data item (long double)
Prefix Meaning
digits maximum field-width
* value assignment is suppressed
H short data item (short int, or short unsigned int)
l long data item (long int, long unsigned int or double)
L long data item (long double)
Array - an identifier that refers to a collection of data items whose subscript starts with zero.
ex. char A[10];
3 Classes of Statements in C:
1. expression statement - an expression followed by a semicolon.
2. compound statement - consists of statement enclosed in { }.
3. control statement - used to create special features such as logical tests, loops, and branches.
Constant Declaration
Syntax: #define <identifier> <value>
ex.
#define Max 20
#define True 1
#define False 0
#define ans 'y'
#define str "jack"
Note: It doesn't end in semicolon since constant declaration is not part of C, a separate C preprocessor translate these lines
to machine language.
<Exercises>
<Exercises>
Type Conversion
Syntax: (data type) expression
- the type of the expression is changed to data type.
<Exercises>
Unary Operators:
1. - negative (sign)
2. -- decrement - decrease the operand by1.
3. ++ increment
Note: decrement/increment - if the operator precedes the operand then the value is altered first before it's used,
otherwise, the value is used first before it's altered.
4. sizeof returns the size of its operand in bytes,
operand may be a cast or an expression.
Note:
--x = pre-decrement
x-- = post-decrement
++x = pre-increment
x++ = post-increment
<Exercises>
int x,y;
x=5;
y = x--; // x=4 , y =5
printf(“x=%d, y=%d”,x,y);
Relational Operators
< , <= , > , >= , == , !=
Logical Operators
&& , || , !
Assignment Statements:
1. Single Assignment:
Syntax: <identifier> = <expression>
Y = x + 5;
Area = 3.14 * r * r;
2. Multiple Assignment: assignment is right to left.
Syntax: <identifier 1> = <identifier 2>=…=<identifier n>= <expression>
Example: x=y= 3.45;
x= y=z=0;
x=3.45;
y=3.45;
a=b=c=d=1;
3. Syntax: <expression 1> <operator>= <expression2> Shorthand assignment statement
Example: x += 2 equiv. x=x+2
i += 1 equiv. i=i+1
x *= -2 * (y+z)/3; => x = x * (-2 * (y+z)/3 );
Compound Operators:
x += y => x = x+y;
x -= y => x = x -y;
x *= y => x = x* y;
x /= y => x = x / y
x %= y => x = x % y;
x = x + y * z;
x += y*z
x = x * y + z;
Conditional Operator ?:
Syntax: <boolean expression1> ? <expression2> : <expression3> equiv to if-else statement
Bitwise Operators:
Operator Meaning
& Bitwise AND
| Bitwise Inclusive OR
^ Bitwise Exclusive OR
~ Bitwise 1's complement
&= Compound bitwise AND assignment
|= Compound bitwise Inclusive OR assignment
^= Compound bitwise Exclusive OR assignment
<< Bitwise left shift
>> Bitwise right shift
<<= Compound bitwise left shift assignment
>>= Compound bitwise right shift assignment
Conditional Statements/Expressions:
Branching Mechanism
1. if statement/ one-way branching statement
Syntax: if (boolean expr/ ) <stmt/compound stmt>
else
<stmt/compound stmt>
Switch Statement:
- equivalent to case statement in Pascal language.
Syntax:
switch (ordinal-expr)
{
case const-expr : statements
case const-expr : statements
…...
default : statements
}
scanf(“%d”,&shape);
switch (shape)
{
case 1: …
….
break;
case 2 …
….
break;
case 3: …
….
break;
case 4 …
….
break;
default: …
….
break;
Loop - a programming mechanism or a way of executing a set of 0 or more statements finite times.
EXAMPLES:
x =1; sum =0;
while (x <= 10)
{
sum = sum + x;
x++;
}
printf(“\n sum of 1 to 10 is equal to %d”, sum);
X=1
X=2
X=3
X=4
X=5
equivalent to:
expr1;
while (<expr2>)
{
stmt 1;
stmt2;
:
expr3;
}
Note:
1) Expr1 - initialization, 0 or more statements separated by comma
2) Expr2 - 0 or 1 conditional expression
3) Expr3 - update , 0 or more statements
4) if expr2 is omitted, the condition is always TRUE, and so resulting to infinite loop.
Function Declaration/Definition:
Syntax: <return_type> <function name> (formal parameter list)
{
local declarations;
statements;
}
Function Call:
Syntax: <function name>(actual parameter list)
Return Statement
- causes an immediate exit from the function.
- used to return a value.
exit() – a predefined function using the stdlib.h header file which causes immediate termination of the entire program.
Syntax: exit(status) , where status=0 if termination is normal.
*- a unary operator that returns "the value of the located at the address that follows…".
Structure – a collection of variables of any data type that are referenced under one name, providing a convenient
means of keeping related information together.
- also called a conglomerate (heterogeneous) data type.
Example:
#include <stdio.h>
struct person
{
char name[10];
int age;
char gender;
float money;
};
struct person p;
Structure of structure (nested structure) – a structure with at least one field/element a structure.
Union – a memory location that is shared by several variables that are of different types.
typedef – use to define a new data type name for an existing type.
Syntax: typedef <existing data type> <new name>;
Enumeration – a set of named integer constants that specifies all the legal values that a variable of its type can have.
Syntax: enum <tag/type name> { namelist } <variable list – optional>;
enum <tag/type name> <variable list>;