0% found this document useful (0 votes)
8 views43 pages

Lecture 3

Programming

Uploaded by

oabile.tubutubu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views43 pages

Lecture 3

Programming

Uploaded by

oabile.tubutubu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

TRANSFORMING

OPPORTUNITY
ACROSS SUB-SAHARAN
AFRICA
Introduction to Lecturer: Ms. Onalethata Matlhape
Programming BSc (Hons) Software Engineering
MEng Computer Engineering
Languages
Introduction to STRUCTURED
Programming PROGRAMMING
Languages USING C
LECTURE OUTLINE

• Overview of the C language syntax, structure, and tools


• Data types, variables, operators, and expressions
• Control structures: decision-making (if, switch) and
iteration (for, while, do-while)
• Modular programming with functions and parameter
passing
History of C Language

• Developed at AT&T’s Bell Laboratories of USA in 1972

• Designed and written by a man named Dennis Ritchie

• Most of its principles and ideas were taken from the earlier language B,

BCPL and CPL

• Languages before C are PL/I, ALGOL, FORTRAN, Pascal, APL, B


Importance of C

• General purpose language but normally used for system programming

• Robust due to rich set of built in functions and operators for writing complex

program

• C is highly portable i.e. platform independent

• Can add our own functions to C library


What is C used for?

Systems programming:
• OSes, like Linux
• microcontrollers: automobiles and airplanes
• embedded processors: phones, portable electronics, etc.
• DSP processors: digital audio and TV systems
• ...
Editing C code

• .c extension
• Editable directly
Compiling a program

• gcc (included with most Linux distributions): compiler


• .o extension
o omitted for common programs like gcc
Example: Compile and Run the Program

C compilation consists of four stages:


1. Preprocessing (.i files)
2. Compilation (.s files)
3. Assembly (.o files)
4. Linking (Executable)
Using gdb
Some useful commands:
• break linenumber – create breakpoint at specified line
• break file:linenumber – create breakpoint at line in file
• run – run program
• c – continue execution
• next – execute next line
• step – execute next line or step into function
• quit – quit gdb
• print expression – print current value of the specified expression
• help command – in-program help
The IDE – all-in-one solution

• Popular IDEs: Eclipse (CDT), Microsoft Visual C++ (Express Edition), KDevelop, Xcode, . . .
• Integrated editor with compiler, debugger
• Very convenient for larger programs
Structure of C program

• A C program is divided into different


sections. There are six main sections
to a basic c program.
• The six sections are,
• Documentation
• Link
• Definition
• Global Declarations
• Main functions
• Subprograms
Documentation Section

• The documentation section is the part of the program where the


programmer gives the details associated with the program. He usually
gives the name of the program, the details of the author and other details
like the time of coding and description. It gives anyone reading the code the
overview of the code.

• Example

• /* File Name: Helloworld.c


• Author: Onnie Maths
• date: 09/08/2024
• */
Link Section
• This part of the code is used to declare all the header files that will be used in the program. This leads to the
compiler being told to link the header files to the system libraries.
• Example
• #include<stdio.h>

Definition Section
• In this section, we define different constants. The keyword define is used in this part.
• #define PI=3.14

Global Declaration Section


• This part of the code is the part where the global variables are declared. All the global variable used are
declared in this part. The user-defined functions are also declared in this part of the code.
float b;
int a=7;
Main Function Section
Every C-programs needs to have the main function. Each main function contains 2 parts. A declaration part and an
Execution part. The declaration part is the part where all the variables are declared. The execution part begins with the
curly brackets and ends with the curly close bracket. Both the declaration and execution part are inside the curly
braces.
int main(void)
{
int a=10;
printf(" %d", a);
return 0;
}

Sub Program Section


All the user-defined functions are defined in this section of the program.
int add(int a, int b)
{
return a+b;
}
Header Files
In C language, header files contain the set of predefined standard library functions. The “#include” preprocessing
directive is used to include the header files with “.h” extension in the program.

• Here is the table that displays some of the header files in C language,

Header Files Description


1. stdio.h Input/Output functions
2. conio.h Console Input/Output functions
3. stdlib.h General utility functions
4. math.h Mathematics functions
5. string.h String functions
6. ctype.h Character handling functions
7. time.h Date and time functions
8. float.h Limits of float types
9. limits.h Size of basic types
Our First C Program

• #include <stdio.h> // Includes the standard I/O library


• // The main function is the entry point of the program
• int main() {
• // Print to the console
• printf("Hello, World!\n");
• return 0; // Indicate successful execution
• }
Our First C Program

• #include <stdio.h>
• int main() {
• char name[50];
• // Ask for user input
• printf("Enter your name: ");
• scanf("%s", name);
• // Greet the user
• printf("Hello, %s!\n", name);
• return 0; }
Data Concepts

• Character Set
• Tokens
• Keywords
• Identifiers
• Variables
• Constants
• Datatypes
• C Operators
• Arithmetic Operators
C Character Set

• A character denotes any alphabet, digit or special symbol used


to represent information.
• Alphabets A,B,…..,Y,Z a,b,……,y,z
• Digits 0,1,2, 3,4,5,6, 7,8,9
• Special symbols ~‘!@#%^&*()_-+=| \{} [ ]:; "'<>,.?/
Tokens

• Smallest individual units are known as C tokens.


• Six Types are
1. Keywords:- float, int, while
2. Identifiers: - name of variables and functions
3. Constants: -15.5, 10
4. Strings: - “Abc”, “year”
5. Special Symbols: - {}, @,
6. Operators: - +,-,*,/
Keywords

• Keywords are the words whose


meaning has already been
explained to the C compiler.
• The following names are reserved
by the C language. Their meaning is
already defined, and they cannot be
re-defined.
• Identifiers refer to the names of variables, functions and arrays, these are user-defined names
• Constants fixed values that do not change during the execution of a program.
• Variables is a data name that used to store a data value. Value stored in a variable may change
during program execution.
• Data types
• The datatype determines what kinds of values a variable can store and what kind of operations
can be performed on variables.
• Every variable used in a program must have a data type
• Two types of data types Primary and Secondary
• Primary Data Types : - integer, float, character
Declaring Variable

Variable Declaration
• Every variable in C must be declared before using it in program
• Variables are declared at the start of body of function of main function
• Declaration tells the compiler what the variable name is.
• It specifies what type of data value the variable will hold and what kind of operations can be
performed on variables.
• The syntax is : - data_typen ame_of_variable
• E.g. int number, amount, balance; for declaring integer type variables
• E.g. float percent; for declaring float type variables
• E.g. char grade; for declaring char type variables
Variable Initialization :- Means assigning an initial value to variable.
E.g. int num = 1 ; // Variable Declaration and Initialization
Declaring Variable as Constants (const):- E.g. const int class_size = 40;
• keeps value of variable constant throughout program
Variable names

• Naming rules:
• Variable names can contain letters,digits and _Variable names should start with letters.
• Keywords (e.g., for,while etc.) cannot be used as variable names
• Variable names are case sensitive. int x; int X declares two different variables.

• Pop quiz (correct/incorrect):


• int money$owed; (incorrect: cannot contain $)
• int total_count (correct)
• int score2 (correct)
• int 2ndscore (incorrect: must start with a letter)
• int long (incorrect: cannot use keyword)
Declarations

• The general format for a declaration is type variable-name


[=value].Examples:
• char x; /∗ uninitialized ∗/
• char x=’A’;/∗ intialized to ’A’∗/
• char x=’A’,y=’B’;/∗multiple variables initialized ∗/
• char x=y=’Z’;/∗multiple initializations ∗/
Data types and sizes

C has a small family of datatypes.


• Numeric (int,float,double)
• Character (char)
• User defined (struct,union)
Numeric data types

• Depending on the precision and range required, you can use one of the
following datatypes. signed unsigned

• The unsigned version has roughly double the range of its signed counterparts.
• Signed and unsigned characters differ only when used in arithmetic
expressions.
Constants
• Constants are literal/fixed values assigned to variables or used
directly in expressions.
Constants (contd.)
C Operators
1. Arithmetic
2. Logical
3. Assignment
4. Relational
5. Increment And Decrement
6. Conditional
7. Bit Wise
8. Special
Arithmetic Operators
The basic operators for performing arithmetic:
9. + addition
10.- subtraction
11.* multiplication
12. / division
Operators

• Arithmetic: +, -, *, /, %

• Relational: ==, !=, >, <, >=, <=

• Logical: &&, ||, !

Expressions:

Combine variables and operators:

int sum = a + b * c;
Relational Operators

• Relational operators compare two operands to produce a ’boolean’


result. In C any non-zero value (1 by convention) is considered to be
’true’ and 0 is considered to be false.
Relational Operators

• Testing equality is one of the most commonly used relational


operator.

• Note that the "==" equality operator is different from the "=", assignment
operator.
• Note that the "==" operator on float variables is tricky because of finite
precision.
Logical operators

• Short circuit: The evaluation of an expression is discontinued if the


value of a conditional expression can be determined early. Be careful of
any side effects in the code. Examples:
• (3==3) || ((c=getchar())==’y’). The second expression is not evaluated.
• (0) && ((x=x+1)>0) . The second expression is not evaluated.
Increment and decrement operators

Increment and decrement are common arithmetic operation. C


provides two short cuts for the same.
Postfix
• x++ is a short cut for x=x+1
• x−− is a short cut for x=x−1
• y=x++ is a short cut for y=x;x=x+1. x is evaluated before
it is incremented.
• y=x−− is a short cut for y=x;x=x−1. x is evaluated before it
is decremented.
Increment and decrement operators

Prefix: ++x is a short cut for x=x+1


• x is a short cut for x=x 1
−− −

• y=++x is a short cut for x=x+1;y=x;. x is evaluated

after it is incremented.
• y=−−x is a short cut for x=x−1;y=x;. x is evaluated

after it is decremented.
Assignment Operators

Another common expression type found while programming in C is of


the type var = var (op) expr
• x=x+1
• x=x∗10
• x=x/2

C provides compact assignment operators that can be used instead.


• x+=1 /∗is the same as x=x+1∗/
• x−=1 /∗is the same as x=x−1∗/
• x∗=10 /∗is the same as x=x∗10 ∗/
• x/=2 /∗ is the same as x=x/2
• x%=2 /∗is the same as x=x%2
Conditional Expression
A common pattern in C (and in most programming) languages is the following:
if ( cond )
x=<expra >;
else
x=<exprb >;
C provides syntactic sugar to express the same using the ternary operator ’?:’

Notice how the ternary operator makes the code shorter and easier to understand
(syntactic sugar).
Expression

• Expression - An expression in a programming language is a combination of values,


variables, operators, and functions

• int x,y,z;
• Expressions: x=y∗2+z∗3;
Suppose x and y are variables
• x+y, x-y, x*y, x/y, x%y: binary arithmetic
• A simple statement:

y = x+3∗x/(y−4);
• Numeric literals like 3 or 4 valid in expressions
• Semicolon ends statement (not newline)
Order of operations
Order of operations
Summary

• Overview of the C language syntax, structure, and tools


• Data types, variables, operators, and expressions
• Control structures: decision-making (if, switch) and iteration
(for, while, do-while)
• Modular programming with functions and parameter passing
Thank you Onalethata
Matlhape

www.bothouniversity.com

You might also like