EE171
Introduction to Computers &
Programming for Engineers
Lecture 3:
Introduction to Computer Programming
1
Computer Programming?
Algorithm
Errors in Programming
Introduction to C Programming
2
Useful Links
https://www.studytonight.com/c/
https://www.javatpoint.com/c-programming-language-tutorial
3
Useful Apps (Android)
C4droid
CppDroid-C/C++ IDE
Mobile C (C/C++ Compiler)
4
Computer Programming
5
Computer program is a formally designed set of
instructions written to be executed by the computer to
perform a particular task.
Computer programming is the process of designing,
writing and testing a set of computer instructions which
performs a certain task.
Program Development Phases
6
Design Phase: To create an ordered sequence of
steps that describe a solution of the problem.
• This sequence of steps is called an algorithm.
Implementation Phase: Writing instructions using a
specific computer language.
• Translating an algorithm into a computer program
Program Development Life Cycle
7
Computer Programming?
Program Algorithm
Errors in Programming
Introduction to C Programming
8
Program Algorithm
9
Algorithm is a finite set of steps defining the solution of a
particular problem or task.
Algorithm is not a computer program
Need not to belong to one particular language
An algorithm is usually expressed in English-like language
called Pseudocode or in the form of Flowchart.
Write an algorithm to determine a student’s final grade
and indicate whether it is a PASS or FAIL. The final
grade is calculated as the average of four scores. The
pass-mark is 50.
10
Advantages of using Algorithm
11
Provides the core solution to a given problem.
The core solution can be implemented on a computer system
using any programming language of user’s choice.
Helps identification and removal of logical errors in a program.
Facilitates analysis to find out the most efficient solution to a
given problem.
Flowcharts
12
A flowchart is the graphical representation of an
algorithm, often used in the design phase to work out
the logical flow of a program.
Visual way to represent the information flow
Makes a program logic more clear
Make testing and debugging easy
13
Write an algorithm and a flowchart to determine a student’s
final grade and indicate whether it is a PASS or FAIL. The final
grade is calculated as the average of four scores.
14
Algorithm vs Flowchart vs Program
15
Computer Programming?
Program Algorithm
Errors in Programming
Introduction to C Programming
16
Errors in Computer Programming
17
Errors are very common in computer programming,
especially during development phase.
Common errors experienced by programmers are:
• Syntax errors
• Runtime errors
• Logical errors
18
Syntax Errors
19
Also called compile time errors
They are caused by violating the grammar/syntax of the
language.
Must be corrected before the program can run
Examples of syntax errors are:
• Using a variable without declaration
• Forgetting semicolon at the end of a statement
• Invalid variables names due to ‘typos’
Runtime Errors
20
Runtime errors occurs as the program is executed
When there are no syntax errors, but the program can’t
complete execution
Example: Divide by zero, Invalid input data
Logical Errors
21
The program completes execution, but delivers
incorrect results
Logical errors can be the hardest to track down
Technically the program is correct, but the results won’t
be what you expected.
Example: Using a wrong arithmetic/logical operator
Computer Programming?
Program Algorithm
Errors in Programming
Introduction to Programming using C
22
Introduction to Programming using C
23
C is a procedural/structured programming language
Efficiency: intended for applications where assembly
language had traditionally been used.
Mainly C Language is used for desktop applications and
system software.
Systems that require fast and direct access to hardware
Systems with limited resources (power, memory)
Applications of C language
24
Key Concepts of C language
25
Identifiers,Variables and Constants
Keywords in C
Variables in C
Data Types in C
Operators in C
Basic Structure of a C program
Identifiers in C
26
Identifiers are distinct names given to program elements
such as constants, variables and functions
RULES:
Identifier name must start with either an alphabet or underscore (_)
Identifier name may consists of alphabets, underscore and digits
The upper case and lower case letters are treated as distinct, i.e. identifiers
are case-sensitive.
Identifier name should not be a predefined keyword
Keywords in C
27
Keywords are predefined (reserved words) have special
meaning to the C compiler.
C has 32 keywords
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
28
Variables in C
29
A variable can be considered as a name given to the location
in memory.
The term variable is used to denote any value that is referred
to a name instead of explicit value.
A variable is able to hold different values during execution of
a program, where as a constant is restricted to just one value.
Any variable must be declared before being used
Variables Declaration in C
30
When you create a variable, you have to specify the data type
during the declaration.
int age;
You can also initialize a variable during declaration
int age = 37;
Rules for Naming Variables
31
Variable name must begin with a letter or underscore.
A variable name can contain alphabetical letters, digits and the
underscore character.
The variable name should not be a C keyword.
Variables are case sensitive
Blanks are not allowed within a variable name.
Variables should be declared in the C program before use.
Constants in C
32
Constants refer to fixed values that the program may not
alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer,
floating, character, or a string.
Constants are like variables, except that their value never
changes during execution once defined.
Constants in C…
33
A constant is declared similarly to variables, except it is
prepended with the const keyword
const int AGE = 37;
Another way to define constants is by using define keyword:
#define AGE 37
Operators in C
34
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.
Operators are used in a program to manipulate data and variables.
The data items that operators act upon are called operands.
Some operators require two operands, while others act upon only one
operand.
The operators are classified into unary, binary and ternary depending
on whether they operate on one, two or three operands respectively.
Operators in C…
35
C has four classes of operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bit-wise Operators
In addition, C has some special operators:
• Increment & Decrement Operators
• Conditional Operators
• Compound Assignment Operators, etc.
Arithmetic Operators
36
There are five Arithmetic Operators in C
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Module division
Relational Operators
37
Relational Operators are symbols that are used to test the relationship
between two variables or between a variable and a constant.
Operator Description
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to
== Equal to
!= Not equal to
Logical Operators
38
Logical Operators are symbols that are used to combine or
negate expressions containing relational operators.
Operator Description
&& AND
|| OR
! NOT EQUAL
Bitwise Operators
39
These operators work only with int and char datatypes and cannot be
used with float and double type.
Operator Description
~ Bitwise NOT
| Bitwise OR
& Bitwise AND
^ Bitwise Exclusive OR (XOR)
>> Right Shift
<< Left Shift
Unary Operators
40
Operator Name Example
- Unary minus -a
++ Increment a++ or ++a
-- Decrement a-- or --a
& Address of Operator &number
Compound Assignment Operators
41
C has a set of shorthand operators, that simplifies the coding of a
certain type of assignment statements.
Statement Equivalent Statement
a += b a=a+b
a -= b a=a–b
a *= b a=a*b
a %= b a=a%b
Conditional/Ternary Operator
42
C provides a peculiar operator ? : which is useful in reducing
the complexity of the code.
It is the only operator in C that works with 3 operands
The general format is A ? B : C;
In the above conditional expression, A is evaluated first.
If the value of A is (TRUE), then the value returned will be B.
If the value of A is (FALSE), then the value returned will be C.
Operators Precedence
43
Operators precedence determines how multiple operators are
evaluated in a single expression
The operators of the higher level of precedence are evaluated first.
What will be the value of c on the statements below?
int a, b, c;
a = 2;
b = 4;
c = b + a * a / b - a;
Operators Precedence
44
In the order from less precedence to more precedence
• = assignment operator
• + and - binary operators
• * and / operators
• + and - unary operators
Operators also have an associativity rule, which is always left
to right
Parentheses have higher priority over anything else.
Basic Structure of a C Program
45
1. /* Program for printing a message */ 1. Comment line: Comments provide
clarification to the source code.
2. # include <stdio.h>
2. # include <stdio.h>: Tells the compiler to read
3. int main( ) the file stdio.h and include its contents in this
file/program
4. {
3. int main( ):The start of the main program.
5. printf(“Good night”);
4. {: Represents the beginning of the program.
6. }
5. printf(); Function to print the output on screen.
6. }: Represents the end of the program.
Rules to write a C Program
46
C is case-sensitive
All statements must end with semicolon.
A statement can be written in one line or it can split into multiple lines.
Braces must always match upon pairs, i.e., every opening brace {must have a
matching closing brace }.
Every complete C program must have the main( ) function.
Comments cannot be nested. E.g.: /* Welcome to C/* programming*/ */
A comment can be split into more than one line.
Get used to errors in programming
Input and Output Statements
47
Computer programs involve data input and output
For standard input and output operations, we use scanf() and
printf() functions respectively.
They are inbuilt library functions found in stdio.h
scanf() function is used to take input from the keyboard
printf() function is used to display output to the screen
Input and Output Statements…
48
We have to include “stdio.h” library file to make use of these
functions
The general syntax is:
printf(“formatted string”, list of arguments);
scanf(“formatted string”, list of arguments);
List of arguments depends on the number of format specifiers
printf() Function
49
#include <stdio.h>
int main() {
printf(“My name is James”); My name is James
}
printf() Function…
50
#include <stdio.h>
int main() {
printf(“My name is James \n”); My name is James
printf(“I like sunset”); I like sunset
}
Escape Sequence in C…
51
Escape
Meaning Description
Sequence
\n New line Shifts the cursor to the new line
\t Horizontal tab Shifts the cursor a single tab space on the same line
\a Alarm/Beep Generates a beep sound to the user
\r Carriage return Shifts the cursor to the beginning of the same line
\\ Backslash Displays backslash
\” Double quotes Displays double quotes
Escape Sequence in C…
52
#include <stdio.h>
int main() {
printf(“We need to \“chase\” our dreams \n”);
printf(“Sun is hot \t Earth is round”);
}
We need to “chase” our dreams
Sun is hot Earth is round
Format Specifiers in C
53
Format Specifier Description
%d Signed integer
%u Unsigned Integer
%c Character
%s String of characters
%f Floating point number
%x Hexadecimal integer
%o Octal number
%% Percentage sign
Write a C program that defines integer variable
and displays its value to the screen.
#include <stdio.h>
int main() { The value z is 16
int z = 16;
printf(“The value of z is %d”, z);
}
54
Write a C program that defines two integer
variables and displays their values to the screen.
#include <stdio.h>
int main()
{
int x = 16, y = 25;
printf(“Values of x and y are %d and %d”, x, y);
}
The values of x and y are 16 and 25
55
#include <stdio.h>
int main() {
int A = 45;
printf(“Value of a is %d”, a);
printf(“Value of a in Hexadecimal is %x”, a);
}
Value of A is 45
Value of A in Hexadecimal is 2D
56
#include <stdio.h>
int main() {
float B = 12.675;
printf(“Value of B is %f”, B);
printf(“Value of B is %0.2f”, B);
printf(“Value of B is %0.0f”, B);
}
Value of B is 12.675000
Value of B is 12.68
Value of B is 13
57
scanf( ) Function
58
The scanf( ) function is a built-in C function that allows a
program to get input data from the keyboard.
Examples: scanf(“%d”, &a);
scanf(“%d %c %f”, &a, &b, &c);
In printf() we pass a value of a variable
In scanf() we pass an address of a variable
Write a C program that prompts the user to enter an integer
variable and the program should display the value of that
integer to the screen.
#include <stdio.h>
int main() {
int number; Enter any number: 57
printf(“Enter any number: "); The number entered is 57
scanf(“%d”, &number);
printf(“The number entered is %d”, number);
}
59
What will happen if we ignore the address operator
(&) in the scanf() function????
#include <stdio.h>
int main() {
int number;
printf(“Enter any number: ");
?????????
scanf(“%d”, number);
printf(“The number entered is %d”, number);
}
60
Write a C program that prompts the user to enter any number. The
program should then calculate, and display the square of that number
#include <stdio.h>
int main() {
int number, square;
Enter an integer: 7
printf(“Enter an number: "); The square of n is 49
scanf(“%d”, &number);
square = number*number;
printf(“The square of n is %d”, square);
}
61
To Do List
Install a compiler for C programming language
Recommended compiler - codeblocks
Found at http://www.codeblocks.org/
Download, Install and Get familiar with it.
62