Professional Documents
Culture Documents
Computer Programming I
Computer Programming I
COMPUTER
PROGRAMMING I
COURSE OUTLINE
Introduction to problem solving methods and Algorithms
Programming language elements (Syntax, Semantics)
Variable Declaration, Data Types, Use of Operators (Arithmetic,
Assignment, Increment/Decrement, Relational, Logic, etc)
Control structures of Algorithms
Introduction to C Programming language
Structural program development in C
C program control (Control structures in C)
C functions
C Arrays
C Pointers
COURSE OUTLINE
Course Lecturer:
⚫ Dr.A. Abayomi-Alli (Coordinator)
⚫ Prof. A. S. Sodiya
INTRODUCTION TO PROGRAMMING
What is a program??? Differentiate between an Algorithm and
a Program!!!
A program is :
the implementation of an algorithm in a programming
language that can be executed by a computer.
a sequence of instructions to instruct a computer to perform
specific tasks. Every program is written in some programming
language.
It can be executed several times, every time with different inputs
Programs are commonly referred to as software. Software is
essential to a computer because it controls everything the
computer does. All of the software that we use to make our
computers useful is created by individuals working as
programmers or software developers.
Language Description
C
C++ (C-plus-plus)
C# (C-Sharp)
Pascal
Delphi
Visual Basic
WEB LANGUAGES
HTML (Hyper Text Markup Language)
XML (Extensible Markup Language)
Javascript
VBScript
PHP (Hypertext Preprocessor)
Java
ASP (Active Server Pages)
COMPILERS AND INTERPRETERS
Because the CPU understands only machine language
instructions, programs that are written in a high-level language
must be translated into machine language.
The first three phases are collectively called the frontend of the
compiler and the last three phases are collectively called the
backend. The middle part of the compiler is the intermediate
code generation
DESIRABLE PROGRAM CHARACTERISTICS
Some important characteristics are expected in programs written in any
programming language.
ASSIGNMENT:
REVISE NOTES ON ALGORITHMS (from CSC 102 class)!!!
Programming language
elements (Syntax, Semantics)
SYNTAX AND SEMANTICS OF A PROGRAMMING LANGUAGE
int
⚫ used to declare numeric program variables of integer type
⚫ whole numbers, positive and negative
⚫ keyword: int
int number;
number = 12;
BASIC DATA TYPES
float
⚫ fractional parts, positive and negative
⚫ keyword: float
float height;
height = 1.72;
double
⚫ used to declare floating point variable of higher precision or
higher range of numbers
⚫ exponential numbers, positive and negative
⚫ keyword: double
double valuebig;
valuebig = 12E-3;
BASIC DATA TYPES
char
⚫ equivalent to ‘letters’ in English language
⚫ Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
⚫ single character
⚫ keyword: char
char my_letter;
my_letter = 'U';
Others include:
Increment: a++
⚫ Example
⚫ int a=5;
⚫ a++ =6;
Modulus (remainder): %
⚫ Example:
⚫ 12%5 = 2;
ARITHMETIC OPERATORS
Assignment by addition: +=
⚫ Example:
⚫ int a=4;
⚫ a+=1; (means a=a+1) value of a becomes 5
Comparison Operators: <, > , <=, >= , != (not equal), ==, ! (logical
not), && (logical and), ||(logical or) .
⚫ Example:
⚫ int a=4, b=5;
⚫ a<b returns a true value.
Bitwise Operators: << (shift left), >>(shift right), ~(bitwise not), &
(bitwise and), |(bitwise or) ,^ (bitwise xor).
⚫ Example
⚫ int a=8;
⚫ a= a>>1; // value of a becomes 4
OPERATOR PRECEDENCE
Meaning of a + b * c ?
Is it a+(b*c) or (a+b)*c ?
All operators have precedence over each other
*, / have more precedence over +, - .
⚫ If both *, / are used, associativity comes into picture. (more on this
later)
⚫ Example :
⚫ 5+4*3 = 5+12= 17.
PRECEDENCE TABLE
Highest on top
++ -- (Postfix)
++ -- (Prefix)
* / %
+ -
<< >>
< >
&
&&
||
THE COMMA OPERATOR
The operator enables you to put more than one expression on a
single line by separating each one with a comma.
e.g int i = 10; j = 25;
CONTROL
STRUCTURES OF
ALGORITHMS
CONTROL STRUCTURES OF ALGORITHMS
What kinds of control structures are necessary in order to describe
algorithms?
The while loop enables your programs to repeat a series of statements, over and
over, as long as a certain condition has not been met. The format is:
while (condition)
{
statements;
}
CONTROL STRUCTURES OF ALGORITHMS
The For Loop: The third type of iteration. This, in its simplest
form, uses an initialisation of the variable as a starting point, a
stop condition depending on the value of the variable. The
variable is incremented on each iteration until it reaches the
required value.
The syntax is:
FOR (starting state, stopping condition, increment) Statements
ENDFOR
For example:
FOR (n = 1, n <= 4, n++)
Output n
ENDFOR
FOR LOOP Cont’d
For (initialization; stopping condition; increment/decrement)
e.g
For (j=2; j<=80; j+=5)
For (i=10; i>=1; i--)
For (j=99; j>=0; j-=11)
C is used:
● system software Compilers, Editors, embedded systems
● data compression, graphics and computational geometry, utility
programs
● databases, operating systems, device drivers, system level routines
● there are zillions of lines of C legacy code
● also used in application programs
BASICS OF C ENVIRONMENT
C systems consist of 3 parts
⚫ C development environment
⚫ Language
⚫ C Standard Library
Program edited in
Editor and stored
Phase 1 Editor Disk on disk
Preprocessor
program processes
Phase 2 Preprocessor Disk the code
Primary memory
Puts program in
memory
Phase 5 Loader
Primary memory
Takes each instruction
and executes it storing
Phase 6 CPU new data values
C COMPILERS, LINKERS, LOADERS
FEW NOTES ON C PROGRAM…
C is a Structured programming language.
C is case-sensitive
⚫ Word, word, WorD, WORD, WOrD, worD, etc are all different
variables / expressions
Eg. sum = 23 + 7
What is the value of Sum after this addition ?
THE GENERAL FORM OF A SIMPLE PROGRAM
Simple C programs have the form
directives
int main ()
{
statements
}
C uses { and } in much the same way that some other
languages use words like begin and end.
Even the simplest C programs rely on three key language
features:
⚫ Directives
⚫ Functions
⚫ Statements
DIRECTIVES
Before a C program is compiled, it is first edited by a
preprocessor.
Commands intended for the preprocessor are called directives.
Example:
#include <stdio.h>
<stdio.h> is a header containing information about C’s
standard I/O library.
Directives always begin with a # character.
By default, directives are one line long; there’s no semicolon or
other special marker at the end.
Two most common directives :
⚫ #include
⚫ #define
FUNCTIONS
Every C program consists of one or more modules called
FUNCTIONS. One of the functions must be called main where the
execution begins when the program is run.
A function is a self-contained module of code that can accomplish
some task.
A function is a sub-unit of a program that performs a specific task.
#include <stdio.h>
The main() function is always
/* The simplest C Program */ where your program starts
int main(int argc, char **argv) running.
{
printf(“Hello World\n”);
Blocks of code (“lexical
scopes”) are marked by { … }
return 0;
}
#include <stdio.h>
/* The simplest C Program */
Compilation occurs in two steps:
int main(int argc, char **argv)
Preprocess
{
printf(“Hello World\n”);
“Preprocessing” and “Compiling”
return 0;
}
__extension__ typedef unsigned long long int __dev_t; In Preprocessing, source code is “expanded” into a
__extension__ typedef unsigned int __uid_t;
__extension__ typedef unsigned int __gid_t; larger form that is simpler for the compiler to
__extension__ typedef unsigned long int __ino_t;
__extension__ typedef unsigned long long int __ino64_t; understand. Any line that starts with ‘#’ is a line that is
__extension__ typedef unsigned int __nlink_t;
__extension__ typedef long int __off_t; interpreted by the Preprocessor.
__extension__ typedef long long int __off64_t;
extern void flockfile (FILE *__stream) ;
extern int ftrylockfile (FILE *__stream) ;
extern void funlockfile (FILE *__stream) ;
int main(int argc, char **argv)
• Include files are “pasted in” (#include)
{
printf(“Hello World\n”);
• Macros are “expanded” (#define)
}
return 0;
• Comments are stripped out ( /* */ , // )
• Continued lines are joined ( \ )
#include <stdio.h>
Function Arguments
#include <stdio.h>
void main()
{
printf("Hello World \n");
}
SIMPLE C PROGRAM
Line 1: #include <stdio.h>
As part of compilation, the C compiler runs a program called the
C preprocessor. The preprocessor is able to add and remove
code from your source file.
In this case, the directive #include tells the preprocessor to
include code from the file stdio.h.
This file contains declarations for functions that the program
needs to use. A declaration for the printf function is in this
file.
Line 5: }
This closing bracket denotes the end of the program.
C PROGRAM STRUCTURE
Another example of simple program in C
#include <stdio.h>
int main()
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
return 0;
}
THE OUTPUT
The previous program will produce the following output on your
screen
I love programming
You will love it too once you know the trick
INPUT/OUTPUT FUNCTIONS
A few functions that are pre-defined in the header file <stdio.h>
such as :
⚫ printf()
⚫ scanf()
⚫ getchar() & putchar()
General format:
1.printf(“string literal”);
A sequence of any number of characters surrounded by double quotation
marks.
E.g printf(“Thank you\n”);
Thank you
THE PRINTF FUNCTION CONT…
2.printf(“format string”, variables);
Format string is a combination of text, format specifier and escape
sequence.
E.g printf (“Total sum is: %d\n”, sum);
\n is an escape sequence
moves the cursor to the new line
PLACEHOLDER / FORMAT SPECIFIER
2. THE SCANF FUNCTION
Reads data from the standard input device (usually keyboard)
and stores it in a variable.
General format:
⚫ scanf(“format string”, &variable);
E.g scanf (“%d” , &a);
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
Example : string %s %s
int age;
printf(“Enter your age:”);
scanf(“%d”, &age);
THE SCANF FUNCTION CONT…
If you want the user to enter more than one value, you serialise the
inputs.
Example:
#include <stdio.h>
int main
{
char my_char;
printf(“Please type a character:”);
my_char = getchar();
printf(“\nYou have typed this character: ”);
putchar(my_char);
return 0;
} 96
GETCHAR() AND PUTCHAR() CONT
Comments
⚫ Text surrounded by /* and */ is ignored by computer
⚫ Used to describe program
#include <stdio.h>
⚫ Preprocessor directive
Tells computer to load contents of a certain file
⚫ <stdio.h> allows standard input/output operations
int main()
⚫ Parenthesis used to indicate a function
⚫ int means that main "returns" an integer value
⚫ Braces ({ and }) indicate a block
The bodies of all functions must be contained in braces
return 0;
⚫ A way to exit a function
⚫ return 0, in this case, means that the program terminated normally
Right brace }
⚫ Indicates end of main has been reached
A SIMPLE C PROGRAM
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read an integer */
12 sum = integer1 + integer2; /* assignment of sum */
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
OUTPUT
Enter first integer
45
Enter second integer
72
Sum is 117
1 /* Using if statements, relational
2 operators, and equality operators */
3 #include <stdio.h>
4
5 int main()
6 {
7 int num1, num2;
10
11 printf( "Enter two integers, and I will tell you\n" );
12 printf( "the relationships they satisfy: " );
13 scanf( "%d%d", &num1, &num2 ); /* read two integers */
14
15 if ( num1 == num2 )
16 printf( "%d is equal to %d\n", num1, num2 );
17
18 if ( num1 != num2 )
19 printf( "%d is not equal to %d\n", num1, num2 );
20
21 if ( num1 < num2 )
22 printf( "%d is less than %d\n", num1, num2 );
23
24 if ( num1 > num2 )
25 printf( "%d is greater than %d\n", num1, num2 );
26
27 if ( num1 <= num2 )
28 printf( "%d is less than or equal to %d\n",
29 num1, num2 );
30
31 if ( num1 >= num2 )
32 printf( "%d is greater than or equal to %d\n",
33 num1, num2 );
34
35 return 0; /* indicates program ended
successfully
36 } */
Output: Number is 4
MORE EXAMPLES
#include <stdio.h>
// program reads and prints the same thing
int main()
{
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}
Rules Example
Can contain a mix of characters and numbers. H2o
However it cannot start with a number
int main ()
{
const double pi = 3.412;
double height, radius, base, volume;
#include <stdio.h>
#define pi 3.142
int main ()
{
double height, radius, base, volume;
#include <stdio.h>
int main ()
{
int num = 10;
printf(“%d”,num);
return 0;
}
MORE EXAMPLES
side1 = 4 - 1 = 3
side2 = 7 - 5 = 2
However, an array can have fewer elements than the limit e.g int
var[5] = {1,2,3,4};
-all shortages are set to 0 by default.
#define SIZE 80
int main ( )
{
char letter[SIZE] ;
int count ;
/ * read in the line */
for (count = 0; count < SIZE; ++count)
letter[count] = getchar();
/* display the line in upper case */
for (count = 0; count < SIZE; ++count)
put char ( toupper ( letter[count])) ;
}
PASSING AN ARRAY TO A FUNCTION
It is possible to pass an array to a function as an argument. When
declaring a one-dimensional array as a formal argument, the array
name is written with a pair of empty square brackets. The size of the
array is not specified within the formal argument declaration.
In this example, x will now point to y, that is, x stores y’s address, where
& is a unary operator, called the address operator, that evaluates
the address of its operand.