100% found this document useful (1 vote)
8 views82 pages

Scs101 - Introduction Computer Programming

The document provides an introduction to computer programming, outlining key concepts such as programming languages, algorithms, and the program development process. It discusses various programming paradigms, including low-level and high-level languages, and introduces Integrated Development Environments (IDEs) used for coding. Additionally, it covers the structure of a C program, including its components, compilation, execution, and the importance of tokens and identifiers.

Uploaded by

cpine0223
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
100% found this document useful (1 vote)
8 views82 pages

Scs101 - Introduction Computer Programming

The document provides an introduction to computer programming, outlining key concepts such as programming languages, algorithms, and the program development process. It discusses various programming paradigms, including low-level and high-level languages, and introduces Integrated Development Environments (IDEs) used for coding. Additionally, it covers the structure of a C program, including its components, compilation, execution, and the importance of tokens and identifiers.

Uploaded by

cpine0223
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/ 82

Unit Title:

INTRODUCTION
COMPUTER
PROGRAMMING
Department: COMPUTER SCIENCE
Lecturer’s Name: Dr. Tirus Muya
Email: [email protected]
Contact: 0721913790
Computer Programming introduction

 Computer Programming is the process of developing and


implementing various sets of instructions to enable a computer to
do a certain task.
 Programs are written to solve problems or perform tasks on a
computer.
 Programmers translate the solutions or tasks into a language the
computer
can understand.
 Pseudocode is a computer programming language that resembles
plain English that cannot be compiled or executed, but explains a
resolution to a problem.
 An algorithm is a list of instructions, procedures, or formulas used to
solve a problem
 The source code consists of the programming statements that are
created by a programmer with a text editor or a visual programming
 Machine language is the only language a computer is capable of
understanding.
 A compiler is a special program that processes statements written in a
particular programming language and turns them into machine
language or "code" that a computer's processor uses.
 After you write a program, your source language statements are
compiled into machine code that is stored as an executable file.
 Debugger is A special program used to find errors (bugs) in other
programs. A debugger allows a programmer to stop a program at any
point and examine and change the values of variables.
 Compiler and interpreter are used to convert the high level language
into machine level language.
 The program written in high level language is known as source program
and the corresponding machine level language program is called as
object program.
 Graphical User Interface (GUI) is a graphical (rather than purely
textual) user interface to a computer. Elements of a GUI include
Programming Language Generations

 1GL or first-generation language was (and still is) machine language or the
level of instructions and data that the processor is actually given to work on.
 2GL or second-generation language is assembler (sometimes called
"assembly") language.
 3GL or third-generation language is a "high-level" programming language,
such as PL/I, C, or Java. A compiler converts the statements of a specific high-
level programming language into machine language.
 4GL or fourth-generation language is designed to be closer to natural
language than a 3GL language. Languages for accessing databases are often
described as 4GLs.
 5GL or fifth-generation language is programming that uses a visual or
graphical development interface to create source language that is usually
compiled with a 3GL or 4GL language compiler.
 Microsoft, Borland, IBM, and other companies make 5GL visual programming
products for developing applications in Java, for example.
 Visual programming allows you to easily envision object-oriented
Programming paradigms /Languages

1. Machine code (Machine language)

 Machine code, also known as machine language,is the elemental language of


computers,comprising a long sequence of binary digital zeros and ones (bits).
 Sometimes referred to as machine code or object code, machine language is a
collection of binary digits or bits that the computer reads and interprets.
 Machine language is the only language a computer is capable of understanding.

2. Assembly Language
 Sometimes referred to as assembly or ASL, assembly language is a low-level programming language used to
interface with computer hardware.
 Assembly language uses structured commands as substitutions for numbers allowing humans to read the code
easier than looking at binary
 Although easier to read than binary, assembly language is a difficult language and is usually substituted for a
higher language such as C.
Programming paradigms /Languages
3. Low-level Languages

 Low-level languages have the advantage that they can be written to


take advantage of any peculiarities in the architecture of the central
processing unit (CPU).
 Thus, a program written in a low-level language can be extremely
efficient, making optimum use of both computer memory and
processing time.

 However, to write a low-level program takes a substantial amount of


time, as well as a clear understanding of the inner workings of the
processor
itself.
 Therefore, low-level programming is typically used only for very small
programs, or for segments of code that are highly critical and must
run as efficiently as possible.
Programming paradigms /Languages
4. High-level Languages

 High-level languages permit faster development of large


programs.

 The final program as executed by the computer is not as


efficient, but the savings in programmer time generally far
outweigh the inefficiencies of the finished product.

 This is because the cost of writing a program is nearly constant


for each line of code, regardless of the language.

 Thus, a high-level language where each line of code translates


to 1-0 machine instructions costs only one tenth as much in
program development as a low-level language where each line
of code represents only a single machine instruction.
Integrated Development Environment (IDE)

 An IDE or Integrated Development Environment is a software program that is


designed to help programmers and developers build software. Most IDEs include:
a source code editor, a compiler, build automation tools and a debugger
 The process of editing, compiling, running, and debugging programs is often
managed by a single integrated application known as an Integrated Development
Environment, or IDE for short.
 An IDE is a windows-based program that allows us to easily manage large
software programs, edit files in windows, and compile, link, run, and debug
programs
 Under Windows, Microsoft Visual Studio is a good example of a
popular IDE
C Install IDE
 An IDE (Integrated Development Environment) is used to edit AND compile the
code.

 Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free
and can be used to edit and debug C code.

 Note: Web-based IDE's can work as well, but functionality is limited.

 We will use Code::Blocks in our tutorial, which we believe is a good place to start.

 You can find the latest version of Codeblocks at http://www.codeblocks.org/.


 Download the mingw-setup.exe file, which will install the text editor with a
compiler.
Program Development Process
 The program development life cycle is a set of steps or phases
that are used to develop a program in any programming
language.
 Generally, program development life cycle contains 6 phases,
they are as follows….
1) Problem Definition
2) Problem Analysis
3) Algorithm Development
4) Coding & Documentation
5) Testing & Debugging
6) Maintenance
Program Development Process
1. Problem Definition
 In this phase, problem statement is defined and the boundaries of the problem. In this phase we need to understand the
problem statement, what is our requirement, what should be the output of the problem solution. These are defined in this
first phase of the program development life cycle.
2. Problem Analysis
 In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means we gather the
required resources to solve the problem defined in the problem definition phase. We also determine the bounds of the
solution.
3. Algorithm Development
 During this phase, we develop a step by step procedure to solve the problem using the specification given in the previous
phase. This phase is very important for program development. That means we write the solution in step by step
statements.
4. Coding & Documentation
 This phase uses a programming language to write or implement actual programming instructions for the steps defined in
the previous phase. In this phase, we construct actual program. That means we write the program to solve the given
problem using programming languages like C, C++, Java etc.,
5. Testing & Debugging
 During this phase, we check whether the code written in previous step is solving the specified problem or not. That means
we test the program whether it is solving the problem for various input data values or not. We also test that whether it is
providing the desired output or not.
6. Maintenance
 During this phase, the program is actively used by the users. If any enhancements found in this phase, all the phases are to
be repeated again to make the enhancements. That means in this phase, the solution (program) is used by the end user. If
Program Development Process
Design Strategies
Top-Down Strategy
 The top-down strategy uses the modular approach to develop the design of a system.
 It is called so because it starts from the top or the highest-level module and moves
towards the lowest level modules.
 In this technique, the highest-level module or main module for developing the software
is identified.
 The main module is divided into several smaller and simpler submodules or segments
based on the task performed by each module. Then, each submodule is further
subdivided into several submodules of next lower level. This process of dividing each
module into several submodules continues until the lowest level modules, which cannot
be further subdivided, are not identified.
Design Strategies cont…..
Bottom-Up Strategy
 Bottom-Up Strategy follows the modular approach to develop the design of the system.
 It is called so because it starts from the bottom or the most basic level modules and
moves towards the highest level modules.
 In this technique, The modules at the most basic or the lowest level are identified.
 These modules are then grouped together based on the function performed by each
module to form the next higher-level modules.
 Then, these modules are further combined to form the next higher-level modules.
 This process of grouping several simpler modules to form higher level modules continues
until the main module of system development process is achieved.
Flow Charts

 A flowchart is a formalized graphic representation of a logic sequence, work or manufacturing


process, organization chart, or similar formalized structure.
 The purpose of a flow chart is to provide people with a common language or reference point
when dealing with a project or process.
 Flowcharts use simple geometric symbols and arrows to define relationships.

Terminal Decision /
(Start or Stop Process to be
Compariso
of program performed
n
flow) Operation

Input / Output
Direction
operation
Example of a
Flow chart
Problem: Find the total /average of two numbers
Assignments: Draw flow chart of each problem
1. Input the length L and the breadth B, calculate and output the area of a
rectangle.
2. User inputs radius and flowchart calculates and shows the area of a circle
3. Print the number from 1 to 100 (Hint: use a counter & loop)
4. Enter 20 marks and print their average.
5. Ask a person for a number between 1 and 100, ask again if they give you a
number outside that range
6. Input 40 marks. Count and print how many marks are below 50.
7. Input M and print the square of M if it is between 1 and 10.
8. Input a mark. Calculate and output a student's grade;
80 < A <= 100
60 < B <= 80
40 < C <= 60
0 <= U <= 40
Format of a C program

 Preprocessor directive
 Functions
 Variables
 Statements & Expressions
 Comments
Example
/* First C program: Hello World */ Comment
#include <stdio.h> //Preprocessor directive

int main() //Main function


{//start of the body of the program
printf("Hello, World! \n"); //prompts print out on
display
return 0; // terminates the main() function
} //end of the body of the program
Format of a C program
Comments
 Comments are ignored by the compiler. Comments and do not have any effect on the
behaviour of the program.
 The programmer can use them to include short explanations or observations within the
source code itself. In this case, the line is a brief description of what our program is.
 Types of comments /*…………………*/ block comment
Compiler directive
#include <stdio.h>
 The #include directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file. The header file stdio.h should be included at
the beginning of all programs that use input/output statements.
 The stdio.h (standard input output header file) contains definition & declaration of system
defined function such as printf( ), scanf( ) etc.
 Lines beginning with a hash sign (#) are directives for the preprocessor. In this case the
directive #include <iostream> tells the preprocessor to include the stdio.h standard file.
This specific file includes the declarations of the basic standard input-output library in C,
and it is included because its functionality is going to be used later in the program.
int main ()
 This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined
before or after it – the instructions contained within this function's definition will always be the
first ones to be executed in any C program.
The Body
 The body of the main function enclosed in braces ({}). What is contained within these braces is
what the function does when it is executed.
printf("Hello, World! \n");
 printf(...) is a function available in C which causes the message "Hello, World!" to be displayed on
the screen.
 printf(...) represents the standard output stream in C, and the meaning of the entire statement is
to insert a sequence of characters into the standard output stream (which usually is the screen).
 Scanf (...) represents the standard input stream in C.
 scanf() function used to read value or prompt user to enter value
return 0;
 The return statement causes the main function to finish. return may be followed by a return code
(in our example is followed by the return code 0). A return code of 0 for the main function is
generally interpreted as the program worked as expected without any errors during its execution.
Compile and Execute C Program
 1. Open a text editor and add the above-mentioned code.
 2. Save the file as hello.c
 3. Open a command prompt and go to the directory where you
have saved the file.
 4. Type gcc hello.c and press enter to compile your code.
 5. If there are no errors in your code, the command prompt will
take you to the next line and would generate a.out executable file.
 6. Now, type a.out to execute your program.
 7. You will see the output "Hello World" printed on the screen.
Tokens in C

 A C program consists of various tokens and a token is either a keyword,


an identifier, a constant, a string literal, or a symbol.
 For example, the following C statement consists of five tokens –
printf("Hello, World! \n");
Semicolons
 In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the end
of one logical entity.
 Given below are two different statements -
 printf("Hello, World! \n");
 return 0;
 Comments are like helping text in your C program and they are ignored
by the compiler. They start with /* and terminate with the characters */ as
shown below -
 /* my first program in C */
Identifiers

 Identifiers are user defined word used to name of entities like


variables, arrays, functions, structures etc.
Rules for naming identifiers are:
a) name should only consists of alphabets (both upper and
lower case), digits and underscore (_) sign.
b) first characters should be alphabet or underscore
c) name should not be a keyword
d) since C is a case sensitive, the upper case and lower case
considered differently, for example code, Code, CODE etc. are
different identifiers.
e) identifiers are generally given in some meaningful name such
as value, net_salary, age, data etc
Keyword or reserved word
 There are certain words reserved and predefined for doing
specific task, these words are known as reserved word or
keywords.
 These reserved words may not be used as constants or
variables or any other identifier names.
 Are written in lower case or small letter.
 These keywords can't be used as a variable name as it
assigned with fixed meaning.
 Some examples are int, short, signed,unsigned,
default, volatile, float, long, double, break, continue,
typedef, static,do, for, union, return, while, do,
extern, register, enum, case, goto, struct,char,
auto, const etc.
Data Types

 Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The value of a variable can be changed any time.
 The type of a variable determines how much space it occupies in storage and how
the bit pattern stored is interpreted.
 C has the following 4 types of data types
 Basic Types:
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
 Enumerated types:
They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
 The type void:
The type specifier void indicates that no value is available.
 Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types,
and (e) Function types.

VARIABLES
A variable is a name given to a storage area that our programs can manipulate.
 All the variables must be declared prior to use in a program
 When a variable is given a value, that value is actually placed in the memory space assigned
to the variable.
 All variables must be declared before they can be used.
 Declaration purposes:
 It associates a type and an identifier (or name) with the variable
 it allows the compiler to decide how much storage space to allocate for storage of the value
associated with the identifier and to assign an address for each depending with type.
 The syntax to declare a new variable is to write the specifier of the desired data type (like int,
bool, float...) followed by a valid variable identifier. For example:
 int x; //declares a variable of type int with the identifier x
 Float myage; // declares a variable of type float with the identifier myage
 Once declared, the variables x and myage can be used within the rest of their scope in the
program.
 To declare more than one variable of the same type, can be declared all of them in a single
statement by separating their identifiers with commas. For example:
Example
// operating with variables
#include <stdio.h>
int main ()
{
int a, b; // declaring variables:
int result; // declaring variables:
a = 5; // process:
b = 2; // process:
a = a + 1; // process:
result = a - b; // process:
printf("Result %d \n",result);// print out the result:
return 0; // terminate the program:
 }
C – printf and scanf
1. printf() is used to display the output and scanf() is used to read the inputs.
2. printf() and scanf() functions are declared in “stdio.h” header le in C library.
3. All syntax in C language including printf() and scanf() functions are case sensitive.
 Use printf() function with %d format specifies to display the value of an integer
variable.
 Ampersand (&)is used before variable name in scanf() statement
 & variable name is used to point to the variable.
Example of format specifies
 %c is used to display character
 %f for float variable
 %s for string variable
 %lf for double
 %x for hexadecimal variable
 \n got replaced by a newline
 A C program consists of various tokens and a token is either a keyword, an
Example of format specifies

#include <stdio.h>
int main()
{
int number = 45;
char character= 'Y';
char charstring[20]= "cprogramming";
float gravity = 9.8;
double pi=3.142;
printf("number is %d\n", number);
printf("character is %c\n", character);
printf("charstring is %s\n", charstring);
printf("float is %f\n", gravity);
printf("double is %lf\n", pi);
return 0;
}
Operator
 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations
 C++ is rich in built-in operators and are mainly keywords
 Generally, there are six type of operators:
 Arithmetical operators
 Relational operators,
 Logical operators,
 Assignment operators,
 Conditional operators,
Arithmetic operators ( +, -, *, /, % )

Arithmetical operators are used to performs an arithmetic


(numeric) operation
Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

Modulus or remainder % is the operation that gives the remainder of a division of two
values. For example, if we write:
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11 between
3.
Relational operators
 The relational operators are used to test the relation between two values.
 All relational operators are binary operators and therefore require two
operands.
A relational expression returns zero when the relation is false and a non-zero
when it is true.
Operator Meaning Example
Returns TRUE if first value is smaller than second value otherwise 10 < 5 is
<
returns FALSE FALSE
Returns TRUE if first value is larger than second value otherwise returns 10 > 5 is
>
FALSE TRUE
Returns TRUE if first value is smaller than or equal to second value 10 <= 5 is
<=
otherwise returns FALSE FALSE
Returns TRUE if first value is larger than or equal to second value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE
Logical operators ( !, &&, || )
 The Operator ! is the C++ operator to perform the Boolean operation NOT,
 It produces false if its operand is true and true if its operand is false.
 Basically, it returns the opposite Boolean value of evaluating its operand

Expression Meaning
!(5 == 5) evaluates to false because the
expression at its right (5 == 5)
is true.
!(6 <= 4) evaluates to true because (6 <=
4) would be false.
!true evaluates to false
!false evaluates to true
Logical operators ( AND i.e &&, || i.e
 OR)
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
 The operator && corresponds with Boolean logical operation AND.
 This operation results true if both its two operands are true, and false
otherwise
 The operator || corresponds with Boolean logical operation OR.
 This operation results true if either one of its two operands is true, thus
being false only when both operands are false themselves.
a b a && b a b a||b
true true true true true true
true false false true false true
false false false false true true

false false false false false false


Assignment operators
 The assignment operator '=' is used for assigning a variable to a value.
 This operator takes the expression on its right-hand-side and places it into the variable on
its left-hand-side.

Operator Example Equivalent to

+= A+=2 A=A+2

-= A-=2 A=A- 2

%= A % =2 A=A%2

/= A /= 2 A=A/2

*= A *= 2 A=A*2
Increment and Decrement Operators
 incrementing and decrementing the value of a variable by 1
 Increment and decrement operators each have two forms, pre and
post
 In Prefix form first variable is first incremented/decremented, then
evaluated
 In Postfix form first variable is first evaluated, then incremented /
decremented.

 The syntax of the increment operator is:


 Pre-increment: ++variable
 Post-increment: variable++
 The syntax of the decrement operator is:
 Pre-decrement: ––variable
Typecasting

 Typecasting is the concept of converting the value of one


type into another type. For example, you might have a
float that you need to use in a function that requires an
integer.
Implicit conversion
 The compiler automatically converts one type into
another type the user has no control
Explicit conversion
 The C++ language have ways to give you back control.
This can be done with what is called an explicit
conversion.
int i;
float f = 3.14;
i = (int) f;
Placeholder : is a symbol beginning with % in a format string that
indicates where to display the output value.

Place holder Variable Function use


type
%c Char Printf / scanf

% d or % i Int Printf / scanf

%f Float Printf

%lf double Scanf


Errors in a program are called bugs and the process of correcting them is called debugging the
program.When the compiler detects an error, the computer displays an error message, which
indicates what mistake you have made and the likely cause of the error. Three kinds of errors can
occur:
SYNTAX ERROR
Occurs when your code violates one or more programming rules of C and is detected by the
compiler as its attempts to translate your program.
RUN – TIME ERRORS
Are detected and displayed by the computer during the execution of a program. It occurs when the
program directs the computer to perform an illegal operation such as dividing a number by zero.
Eg. Int first, second;
Double temp,ans ;
Printf ( “Enter two integers \ n”);
Scanf ( “% d % d ”, & first, & second );
Temp = second / first;
Ans = first / temp;
Printf ( “ The result is % 3f\ n “, ans);
Undetected Errors.
Many execution errors may not prevent a C program from running to completion, but
may simply lead to incorrect results.

LOGIC/SEMANTICS ERRORS
Occurs when a program follows a faulty algorithm. The only sign of a logic error may be
an incorrect output.
Eg. Omitting & in the scan f
Eg. Enter two values and find their sums
Scan f ( “ % d % d ”, first, second);
Control Structures
Control structures allows to control the flow of program’s execution based on certain
conditions C supports following basic control structures:
 Conditional structure
 if and if else statements
 Iteration structures (loops)
 The while loop
 The do while loop
 The for loop
 The selective structure
 switch statement
 Jump statements
 The break statement
 The continue statement
 The goto statement
if and if else statements

 An if statement consists of a Boolean expression followed by one or


more statements.
 Where condition is the expression that is being evaluated.
 If this condition is true, statement is executed.
 If it is false, statement is ignored (not executed) and
 the program continues right after this conditional structure.
Syntax
If (boolean_expression)
{
/* statement(s) will execute if
the boolean expression is true */
}
if - else statement

 An if statement can be followed by an optional else statement,


which executes when the Boolean expression is false.
 If the Boolean expression evaluates to true, then the if block will be
executed,
 otherwise, the else block will be executed.

Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
Example
#include <stdio.h>
int main()
{
/* local variable definition */
int x = 100;
/* check the boolean condition */
if (x == 100)
{
printf("print value %d\n", x );
}
return 0;
}
If else // Program to evaluate a wage

#include <stdio.h> // calculate wage


int main() if (hours_worked <= limit)
{ wage = hours_worked * hourly_rate;
const float limit = else
40.0,overtime_factor = 1.5; wage = (limit + (hours_worked - limit)
float hourly_rate, // hourly rate of pay * overtime_factor)* hourly_rate;
hours_worked, // hours worked // Output wage
wage; // final wage printf("Wage for ",&hours_worked);
// Enter hours worked and hourly rate printf(" hours at ",&hourly_rate);
printf(" wage %f",wage);
printf("Enter hours worked: ");
scanf("%f", &hours_worked); return 0;
printf("Enter hourly_rate: ") ; }
scanf("%f", &hourly_rate) ;
if...else if...else Statement
 This chain is evaluated from the top and, if a }
particular if-conditional is TRUE,
 then its statement is executed and the chain is
else if( boolean_expression
terminated. 3)
 On the other hand, if the conditional is FALSE, the { /* Executes when the
next if-conditional is tested.
boolean expression 3 is true */
 If all the conditionals evaluate to FALSE, then the
final else statement is executed as a default. }
Syntax else
if(boolean_expression 1) { /* executes when the none of the
above condition is true */
{ /* Executes when the
boolean expression 1 is true */ }
}
Modify the wage
else if( boolean_expression
2)
program to include
{ /* Executes when the
boolean expression 2 is true */ commission
Nested if Statements
 nest if-else statements, which means you can use one if or else
if statement inside another if or else if statement(s).
The syntax for a nested if statement is as follows

if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
switch Statement
 A switch statement allows a variable to be tested for equality against a list of values.
 Each value is called a case, and the variable being switched on is checked for each switch case.
The following rules apply to a switch statement:
 The expression used in a switch statement must have an integral or enumerated type,
 You can have any number of case statements within a switch.
 Each case is followed by the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch.
 The default case can be used for performing a task when none of the cases is true. No break is
needed in the default case.
syntax
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
Example
// Program to evaluate grade printf("You passed\n" );
#include <stdio.h> break;
case 'F' :
int main () { printf("Better try again\n" );
break;
/* local variable definition */ default :
char grade = 'B'; printf("Invalid grade\n" );
}
switch(grade) {
case 'A' : printf("Your grade is %c\n", grade );
printf("Excellent!\n" );
break; return 0;
case 'B' :
case 'C' :
printf("Well done\n" ); Convert the if...else if...else
break; Statement switch statements
case 'D' :
Switch vs if else

switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
break; else {
default: cout << "value of x
cout << "value of x unknown"; unknown" }
}
Iteration structures (loops)

 Loops have as purpose to repeat a statement a certain number of


times or while a condition is fulfilled.
 A loop statement allows us to execute a statement or group of
statements multiple times.

 The while loop


 The do while loop
 The for loop
The for loop
 A for loop is a repetition control structure that allows programmer to
efficiently write a loop that needs to execute a specific number of times.
 It works in the following way:
 1. initialization is executed. Generally it is an initial value setting for a counter
variable. This is executed only once.
 2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
 3. statement is executed. As usual, it can be either a single statement or a block
enclosed in braces { }.
 4. finally, whatever is specified in the increase field is executed and the loop gets
back to step
 The syntax

for ( initialization ; condition; increment )


{
statement(s);
}
Example
// countdown using a for loop

#include <stdio.h>
int main ()
{ int n;
for (n=10; n>0; n--) {
printf(" %d ", n);
}
printf("FIRE!\n");

return 0;
}
The while loop
 executes a target statement as long as a given condition is true.
 functionality is simply to repeat statement while the condition
set in expression is true.

while(condition)
{
statement(s);
}
Example
// additional using while
#include <stdio.h>
1. User assigns a value to n
2. The while condition is checked (n>0).
At this point there are two posibilities:
int main () { * condition is true: statement is executed
/* local variable definition */ (to step 3)
int a = 10; * condition is false: ignore statement and
/* while loop execution */
continue after it (to step 5)
3. Execute statement: cout << n << ", ";
while( a < 20 ) {
--n; (prints the value of n on the screen
printf("value of a: %d\n", a); and decreases n by 1)
a++; 4. End of block. Return automatically to
} step 2
return 0; 5. Continue the program right after the
block: print FIRE! and end program.
}
The do-while loop
 Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in checks its condition at the bottom of the loop.
 A do...while loop is similar to a while loop, except the fact that it is guaranteed
to execute at least one time.
 The conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
 If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again.
 This process repeats until the given condition becomes false.

 The syntax of a do...while loop


do
{
statement(s);

}while( condition );
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

return 0;
}
Nested Loops loop inside another
Theloop
syntax for a nested for loop statement }
for ( init; condition; increment ) statement(s);
{ }
for ( init; condition; increment )
{ The syntax for a nested do...while loop
statement
statement(s);
}
do
statement(s);
{
}
statement(s);
do
The syntax for a nested while loop statement
{
while(condition)
statement(s);
{
}while( condition );
while(condition)
{statement(s);
Nested for loop
// nested for loop to find the prime numbers from 2 to 100
#include <stdio.h>
int main () {
/* local variable definition */
int i, j;
for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)


if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
BREAK STATEMENT IN C

 The break statement in C #include <stdio.h>


programming has the following two int main () {
usages
 When a break statement is
encountered inside a loop, the /* local variable definition
loop is immediately terminated */ int a = 10;
and the program control resumes /* while loop execution */
at the next statement following
the loop. while( a < 20 ) {
 It can be used to terminate a case printf("value of a:
in the switch statement . %d\n", a);
 using nested loops, the break a++;
statement stop the execution of the If( a > 15) {
innermost loop and start executing /* terminate the loop
the next line of code after the block. using break statement */

break;
}
}
return 0;
CONTINUE STATEMENT IN C
 Works somewhat like the break statement.
 Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code
in between.
 For the for loop, continue statement causes the
conditional test and increment portions of the loop to
execute.
 For the while and do...while loops, continue statement
causes the program control to pass to the conditional
tests.
Syntax
 The syntax for a continue statement in C is as follows
-continue;
C FUNCTIONS

 A function is a group of statements that together perform a task. Every C program has at least one
function,which is main function.
 A function is known with various names like a method or a sub-routine or a procedure etc.
 Functions are used to provide modularity to a program. Creating an application using function
makes it easier to understand, edit, check errors etc.
Syntax of Function/Defining a Function
return-type function-name (parameters)
{
// function-body
}
 return-type : suggests what the function will return. It can be int, char, some pointer or even a class
object.
 There can be functions which does not return anything, they are mentioned with void.
 Function Name : is the name of the function, using the function name it is called.
 Parameters : are variables to hold values of arguments passed while function is called. When a
function is invoked, you pass a value to the parameter. This value is referred to as actual parameter
or argument.
 A function may or may not contain parameter list.
Declaring, Defining and Calling Function
 Function declaration, is done to tell the compiler
about the existence of the function.
printf( "Max value is : %d\n", ret );
 A function declaration has the following parts -
return 0;
return_type function_name( parameter list );
}
 Function's return type, its name & parameter list is
/* function returning the max between two numbers */
mentioned.
 int max(int num1, int num2) /* function definition*/
Function body is written in its definition.
{
#include <stdio.h>
/* local variable declaration */
/* function declaration */
int result;
int max(int num1, int num2);
int main () {
if (num1 > num2)
/* local variable definition */
result = num1;
int a = 100;
else
int b = 200;
result = num2;
int ret;
/* calling a function to get max value */
return result;
ret = max(a, b);
}
Calling Function
 To use a function, it must be called or invoked.
 When a program calls a function, program control is transferred to the called function
 While creating a C function, you give a definition of what the function has to do
 A called function performs defined task and when it’s return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main function
 To call a function, you simply need to pass the required parameters along with function name, and if function
returns a value, then you can store returned value.
ret = max(a, b);
 Functions are called by their names. If the function is without argument, it can be called directly using its
name.
 But for functions with arguments, we have two ways to call them,
 1. Call by Value
This method copies the actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
 2. Call by Reference
 This method copies the reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.
Call by Value
 In this calling technique we pass the values of swap(a, b);
arguments which are stored or copied into the
printf("After swap, value of a : %d\n", a );
formal parameters of functions.

printf("After swap, value of b : %d\n", b );
Hence, the original values are unchanged only
the parameters inside function changes. return 0;
Calling the function swap by passing actual }
values as in the following example – it will produce the following result -
#include <stdio.h>  Before swap, value of a :100
/* function declaration */  Before swap, value of b :200
void swap(int x, int y);  After swap, value of a :100
int main () {  After swap, value of b :200
/* local variable definition */
int a = 100;  So the variable inside main() doesn’t change
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
Call by reference
 In this we pass the address of the variable as
arguments.
 In this case the formal parameter can be taken as a
/* function definition to swap the
reference or a pointer, values */
 in both the case they will change the values of the
original variable.
void swap(int *x, int *y) /* declare the
 The call by reference method of passing arguments
function parameters as pointer types
to a function copies the address of an argument into */
the formal parameter.
 The address is used to access the actual argument
{
used in the call.
int temp;
 It means the changes made to the parameter affect
the passed argument. temp = *x; /* save the value at
 To pass a value by reference, argument pointers are address x */
passed to the functions just like any other value.
 So accordingly you need to declare the function
*x = *y; /* put y into x */
parameters as pointer types as in the following
function swap,
*y = temp; /* put temp into y */
 which exchanges the values of the two integer return;
variables pointed to, by their arguments.
}
Calling the function swap by passing values by reference
#include <stdio.h> */
/* function declaration */ swap(&a, &b);
void swap(int *x, int *y);
printf("After swap, value of a : %d\n", a );
int main () { printf("After swap, value of b : %d\n", b );
/* local variable definition */
int a = 100; return 0;
int b = 200; }
printf("Before swap, value of a : %d\n", a ); Produce the following result -
printf("Before swap, value of b : %d\n", b ); Before swap, value of a :100
Before swap, value of b :200
/* calling a function to swap the values. After swap, value of a :200
* &a indicates pointer to a ie. address of After swap, value of b :100
variable a and
It shows that the change has reflected outside the
* &b indicates pointer to b ie. address of function as well, unlike call by value where the
variable b. changes do not reflect outside the function.
Arrays in C
 An array is a data structure which allows a collective name to be given to a group of
elements which all have the same type.
 An individual element of an array is identified by its own unique index (or subscript).
 C provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
 An array can be thought of as a collection of numbered boxes each containing one data
item.
 The number associated with the box is the index of the item.
 The index must be an integer and indicates the position of the element in the array.
 Thus the elements of an array are ordered by the index.
Declaration of Arrays

 To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows -
type arrayName [ arraySize ];
 This is called a single-dimension array.
 The arraySize must be an integer constant greater than zero and type can be any
valid C++ data type.
 For example data on the average temperature over the year in Britain for each of
the last 100 years could be stored in an array declared as follows:
float annual_temp[100];
 This declaration will cause the compiler to allocate space for 100 consecutive float
variables in memory.
 The number of elements in an array must be fixed at compile time.
 It is best to make the array size a constant and then, if required, the program can
be changed to handle a different size of array by changing the value of the
constant,
Initialisation of arrays
 An array can be initialised in a similar manner as variables.
 The initial values are given as a list enclosed in curly brackets.
 For example initialising an array to hold the first few prime numbers could be
written as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

int primes[] = {1, 2, 3, 5, 7, 11, 13};


 Note that the array has not been given a size, the compiler will make it large
enough to hold the number of elements in the list.
 In this case primes would be allocated space for seven elements.
 If the array is given a size then this size must be greater than or equal to the
number of elements in the initialisation list. For example:
int primes[10] = {1, 2, 3, 5, 7};
 The compiler would reserve space for a ten element array but would only initialise
the first five elements.
Accessing Array Elements
 Given the declaration float annual_temp[100]; of a 100 element array the compiler
reserves space for 100 consecutive floating point values and accesses these values using
an index/subscript that takes values from 0 to 99.
 The first element in an array in C++ always has the index 0, and if the array has n
elements the last element will have the index n-1.
 An array element is accessed by writing the identifier of the array followed by the
subscript/index in square brackets.
 Thus to set the 15th element of the array above to 1.5 the following assignment is used:
annual_temp[14] = 1.5;
 An element is accessed by indexing the array name.
 This is done by placing the index of the element within square brackets after the name of
the array.
 For example -
double salary = balance[9];
 The above statement will take 10th element from the array and assign the value to salary
variable.
Example of Declaration, assignment and accessing arrays -

# #include <stdio.h> }
int main () { return 0;
}
int n[ 10 ]; /* n is an array of 10 integers */ Output
int i,j;  Element[0] = 100
 Element[1] = 101
/* initialize elements of array n to 0 */  Element[2] = 102
for ( i = 0; i < 10; i++ ) {  Element[3] = 103
n[ i ] = i + 100; /* set element at location i to i  Element[4] = 104
+ 100 */  Element[5] = 105
}  Element[6] = 106
/* output each array element's value */  Element[7] = 107
for (j = 0; j < 10; j++ ) {  Element[8] = 108
printf("Element[%d] = %d\n", j, n[j] );  Element[9] = 109
C MULTI-DIMENSIONAL ARRAYS; Two-Dimensional Arrays
 C programming language allows multidimensional arrays. Here is the general form of a
multidimensional
 array declaration - type name[size1][size2]...[sizeN];
 For example, the following declaration creates a three dimensional integer array - int threedim[5]
[10][4];
 The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of
size x,y, you would write something as follows -
type arrayName [ x ][ y ];
 two-dimensional array can be think as a table, which will have x number of rows and y number of
columns.
 A 2-dimensional array a, which contains three rows and four columns can be shown as below –

 Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
Initializing & Accessing Two-Dimensional Arrays
Initializing Two-Dimensional Arrays
 Multidimensional arrays may be initialized by specifying bracketed values for each row.
 Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
 The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example -
 int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
 An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the
 array. For example - int val = a[2][3];
 The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram.
Example
#include <stdio.h> When the above code is compiled and executed, it
produces the following result -
a[0][0]: 0
int main () {
a[0][1]: 0
a[1][0]: 1
/* an array with 5 rows and 2 columns*/
a[1][1]: 2
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},
{4,8}}; a[2][0]: 2
int i, j; a[2][1]: 4
/* output each array element's value */ a[3][0]: 3
for ( i = 0; i < 5; i++ ) { a[3][1]: 6
a[4][0]: 4
for ( j = 0; j < 2; j++ ) { a[4][1]: 8
printf("a[%d][%d] = %d\n", i,j, a[i][j] ); As explained above, you can have arrays with any
number of dimensions, although it is likely that
}
most of the arrays you create will be of one or two
} dimensions.
return 0;}
C – ARRAY OF STRINGS
 Strings are actually one-dimensional array of characters terminated by a null character '\
0'.
 Thus a null terminated string contains the characters that comprise the string followed by
a null.
 The following declaration and initialization create a string consisting of the word "Hello".
 To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."
 char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 char greeting[] = "Hello"; you do not place the null character at the end of a string
constant.
 The C compiler automatically places the '\0' at the end of the string when it initializes the
array.
 Following is the memory presentation of the above defined string in C/C++ -
Example

#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result -
Greeting message: Hello
C - POINTERS
 A pointer is a variable whose value is the address Consider the following example, which prints the
of another variable, i.e., direct address of the address of the variables defined
memory location.
#include <stdio.h>
 A pointer must be declared before using it to store
int main ()
any variable address.
{
Syntax Declaration
int var1;
type *var-name;
char var2[10];
int *ip; /* pointer to an integer */
printf("Address of var1 variable: %x\n", &var1 );
double *dp; /* pointer to a double */
printf("Address of var2 variable: %x\n", &var2 );
float *fp; /* pointer to a float */
return 0;
char *ch /* pointer to a character */
 The asterisk * is being used to designate a }
variable as a pointer  When the above code is compiled and executed, it

 Every variable is a memory location and every produces the following result -
memory location has its address defined which Address of var1 variable: 22fe4c
 can be accessed using ampersand & operator, Address of var2 variable: 22fe40
which denotes an address in memory.
How to Use Pointers?
 a pointer variable, assign the address of a ip = &var; /* store address of var in pointer
variable to a pointer
variable*/
 Finally access the value at the address
available in the pointer variable. printf("Address of var variable: %x\n", &var );
 This is done by using unary operator * /* address stored in pointer variable */
that returns the value of the variable
located at the address specified by its printf("Address stored in ip variable: %x\n", ip );
operand.
 /* access the value using the pointer */
The following example makes use of these
operations printf("Value of *ip variable: %d\n", *ip );

return 0;
#include <stdio.h>
}
int main ()
 Address of var variable: bffd8b3c
{
 Address stored in ip variable: bffd8b3c
int var = 20; /* actual variable declaration */
 Value of *ip variable: 20

You might also like