0% found this document useful (0 votes)
4 views17 pages

Programming 1

The document provides an overview of programming, detailing the definitions and distinctions between low-level and high-level programming languages, including machine language and assembly language. It also discusses language translators such as compilers and interpreters, as well as common programming paradigms like procedural, object-oriented, functional, and declarative programming. Additionally, it covers concepts related to programming errors, debugging, and the structure of a C program.

Uploaded by

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

Programming 1

The document provides an overview of programming, detailing the definitions and distinctions between low-level and high-level programming languages, including machine language and assembly language. It also discusses language translators such as compilers and interpreters, as well as common programming paradigms like procedural, object-oriented, functional, and declarative programming. Additionally, it covers concepts related to programming errors, debugging, and the structure of a C program.

Uploaded by

maffohermine237
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2.

Programming 1110 0001: 0011 1110

Programming is the activity of writing computer programs. A computer


b. Assembly Language
program is a set of instructions that will be followed by a computer to
Assembly language is a low-level language consisting of mnemonic codes
perform a computation. These instructions are made up of statements
and symbolic addresses corresponding to machine language instructions.
written in some languages specially designed for this purpose. These
Assembly language is the second generation of programming languages. For
languages are called programming languages.
example:
In other words, a program is an algorithm expressed in a programming
language.
LOAD R0 Number1 Load number1 in register 0
LOAD R1 Number2 Load Number2 in register 1
2.1. Programming Languages
ADD R2 R0 R1 Add register 0 and register 1 and keep result in
A programming language is a set of predefined words, symbols and rules
register 2
that are used to write computer programs. Programming languages
aregrouped intolow-level and high-level languages.
 Advantages of assembly language
o It is easier to write and understand when compared to machine
2.1.1. Low-Level Languages
language.
A low-level language is a language whose instruction set reflects the
o It can produce small program sizes
processor architecture. An instruction set is the set of bit patterns or binary
o It can produce very fast code as it allows low-level access to
codes for the machine operations that a processor has been designed to
hardware features
perform. Low-level languages include machine language and assembly
language.
 Disadvantages of assembly language
o Programs are not as easy to write and understand when compared
a. Machine Language
to high level languages.
Machine language is the computer’s language. It is the language the
o Programs are tied to specific computer hardware and can’t be
computer understands. Machine language instructions are written in binary
reused on another kind of computer.
(a series of 0s and 1s), and are directly executable by the computer. Each
o Writing programs is very time consuming, tedious, and error-prone.
machine language statement corresponds to one machine action. Machine
language is the first generation of programming languages. For example a
2.1.2. High-Level Languages
short (3 instruction) program might look like this:
High-level languages are closer to human language. They allow
programmers to write programs without having to understand the inner
0111 0001: 0000 1111
workings of the computer. One high-level language statement will generally
1001 1011: 0001 1010
be translated into several low-level language statements. They are the third
generation of programming languages. Examples are C, BASIC (Beginner’s one programming language to another without loss of original meaning.
All-purpose Symbolic Instruction Code), Pascal, Java, FORTRAN (Formula There are three types of language translators: compiler, interpreter and
Translator) and COBOL (Common Business-Oriented Language). Below is a assembler.
small code for adding two numbers in Pascal and C.
2.2.1. Assembler
Pascal C
program addition;
An assembler translates assembly language into machine language. The
#include <stdio.h>
usescrt; intmain() process is called assembling.
var number1, number2, sum: integer; { int number1, number2,
begin sum;
read(Number1); scanf(“%d”, &number1);
read(Number2); scanf(“%d”, &number2);
sum := Number1 + Number2; sum = number1 + number2;
write(sum); printf(“%d”, sum);
end. return 0;
} Program assembling

2.2.2. Compiler
A compiler translates the entire high-level program into a machine language
 Advantages of high-level languages
program. The high-level language program is called source program or
o easy to understand and write programs as they are user oriented
source code and the generated machine language program is called object
o they have built in libraries to perform routine tasks
program or object code. This process is called compilation. Some compilers
o programs can be ported to multiple hardware setups from same
convert high-level language into assembly language, then an assembler is
code
used to create the finished object code.

 Disadvantages of high-level languages


o programs may be slower than second generation languages
o may produce larger program files for same functionality as second
generation languages.
o may not allow for low level hardware access
Program compilation

2.2. Language Translators


To run a program on a computer, the program needs to be translated into  Advantages of a Compiler

the machine language of the computer on which it will run. A language o Fast in execution

translator is a computer program that translates program instructions from


o The object code produced by a compiler can be distributed or  Disadvantages of an Interpreter
executed without having to have the compiler present. o It is slow as interpretation and execution is done line by line.
o The object program can be used whenever required without the o Translation has to be done every time the program is to be executed
need of recompilation. since no object code is produced.
o For the program to run, the interpreter must be present
 Disadvantages of a Compiler
o Debugging a program is much harder. Therefore not so good at 2.3. Program Errors and Correction
finding errors 2.3.1. Syntax Errors
o When an error is found, the whole program has to be re-compiled Syntax is the set of rules that specify how the symbols of a language can be
put together to form meaningful statements. In other words, syntax defines
2.2.3. Interpreter the structure of legal statements in a language. A syntax error is an error in a
An interpreter is a computer program that translates and executes program that occurs due to the non-respect of the syntax rules of the
instructions written in a high-level language into machine language language used. A syntax error will cause a compiler/interpreter to stop trying
instructions one line at a time. The interpreter translates an instruction and to generate machine code and will not create an executable. However, a
allows it to be executed before translating the next line. If a program compiler will usually not stop at the first error it encounters but will attempt
performs a section code 1000 times, then the section is translated into to continue checking the syntax of a program right to the last line. For
machine code 1000 times since each line is interpreted and then executed. example, a misspelled key word, a missing punctuation mark or the
incorrect use of an operator is a syntax error.

2.3.2. Semantic Errors


Semantics specify the meaning of a well-formed program. A semantic error
occurs when you write a program that works, but does not do what you
intend it to do. Compilation and interpretation do not detect semantic errors.
Program interpretation
Semantic or logic errors are detected from wrong results. Something may be
syntactically correct but semantically incorrect.
 Advantages of an Interpreter
o It is good at locating errors in programs
2.3.3. Run-time Errors
o Debugging is easier since the interpreter stops when it encounters
A run-time error is an error that occurs during program execution. For
an error.
example, a run-time error may occur if division by 0 is attempted. A run-
o If an error is corrected, there is no need to retranslate the whole
time error may cause the program to stop execution, or it may be handled by
program
an error-trapping routine.
2.3.4. Debugging Some important concepts related to object oriented programming (OOP) are:
An error in a computer program is known as a bug. Debugging is the process class, object, abstraction, encapsulation, inheritance and polymorphism.
of detecting and removing bugs. Syntax errors and semantic errors are bugs.
A debugger is the software tool used for this purpose. a. Class
A class is a description of an object or a real life concept. Classes are
2.4. Programming Paradigms templates for creating objects, providing initial values for instance variables
A programming paradigm (or technique) is a fundamental style of computer (attributes) and the bodies for methods. All objects generated from the same
programming. It describes a programming language’s approach to solving a class share the same methods, but contain separate copies of the instance
problem. Paradigms differ in the concepts and abstractions used to represent variables. New objects can be created from a class by applying the new
the elements of a program and the steps that compose a computation. High operator to the name of the class.
level languages can be classified under four different paradigms: procedural,
functional, object-oriented and declarative paradigms. ClassPerson {
private:
2.4.1. Procedural Paradigm char name[20];
In the procedural/imperative paradigm, a program is a collection of char sex;
statements and procedures that affect data. Here, a program can be seen as date birthdate;
an active agent that manipulates passive objects(variables).These objects are public:
passive because they cannot initiate an action by themselves, but can only updateInfo();
receive actions from active agents. The focus in procedural programming is returnAge();
to write good functions and procedures. };
Examples of imperative languages are Pascal, C, Ada, FORTRAN, and COBOL.
The name of the class is person. It has three instance variables
2.4.2. Object Oriented Paradigm (attributes)name, sex and age, and three methods: updateInfo(),and
The object-oriented paradigm presents a program as a collection of classes returnAge(). These methods act on the instance variables when invoked.
for interacting objects. Unlike in imperative programming, object-oriented
programming deals with active objects instead of passive objects. These b. Object
objects are active because the actions to be performed on the objects are An object is an instance of a class. An object consists of a collection of
included in them (the objects). The objects need only to receive the attributes, representing the state of the object, and a collection of methods,
appropriate stimulus from outside to perform one of the actions. representing the behavior that the object is capable of performing. Attributes
Examples of object-oriented languages are C++, Java, Visual Basic and are sometimes referred to as the fields of an object. The methods are
Smalltalk. routines that are capable of accessing and manipulating the values of the
attributes of the object. Objects interact with each other by sending
messages. When a message is sent to an object, the corresponding method of }
the object is executed.
Inheritance is usually represented using an inheritance diagram.
c. Abstraction For example: if the classes Student and Teacher are derived from the
superclass Person, this is represented as:
d. Encapsulation
Encapsulation is the process of combining together the attributes and Person Person
methods of a class into a single abstract data type with a public interface and
a private implementation. The goal of encapsulation is to protect the
Student Teache
implementation from the users of the object. It ensures that all access to the
r
internal representation of the object pass through the class methods, which
act as an "interface" to the object. This is done by making properties and There are two types of Inheritance: multiple inheritance and multilevel
methods “private.” inheritance.

e. Inheritance  Multiple inheritance is when a derived class inherits features from


Inheritance is the derivation of one class from another so that the attributes more than one superclass. It is illustrated as follows:
and methods of the derived class are part of the definition of the initial class.
The initial class is often called the base class, parent class or superclass while Base class 1 Base class 2
thederived class is often referred to as the child class or sub-class. The
subclass usually contains all the attributes and methods of the superclass Derived class
plus some of its own.
For example: the class Student inheriting from the class person will have all
the attributes and methods of Person plus the following:  Multi-level inheritance is when a class inherits from a class which is
itself inherited from another class. It is illustrated as follows:
Class Student extends Person {
private Base class
int admNumber;
int level; Derived class
public 1
changeLevel(int newLevel) {
Derived class
level=newLevel;
2
}
defined by Greek mathematicians and later developed into first-order
predicate calculus. The point of logic programming is to bring the style of
f. Polymorphism: mathematical logic to computer programming. An example of a declarative
Polymorphism is the use of different methods, each with the same name, programming language is PROLOG (programming logic).
which are associated with different object types. In other words, it is the
ability for different objects to respond to the same message in different, These facts are given:
class-specific ways. Polymorphic methods are used which have one name but human (John)
different implementations for different classes. mortal (human)
Assume you have a “shape” superclass. This class has a method called “area”
which returns the area of the shape. Polymorphism allows you to make The user asks the following question:
subclasses like “circle,” “square,” and “triangle” which inherit the “area” ?-mortal (John)
method, but each subclass would return the correct value even though they
have different formulas to calculate their areas. The program answers yes.

2.4.3. Functional Paradigm 2.5. C Programming


In functional (applicative) programming, a program is a collection of C is a high-level programming language developed by Dennis Ritchie and
function definitions. Lambda calculus forms the basis of almost all Brian Kernighan at Bell Labs in the mid-1970s. Although originally designed
functional programming languages. Lambda calculus is the use of lambda as a systems programming language, C has proved to be a powerful and
expressions to define functions. A lambda expression is a formula that flexible language that can be used for a variety of applications, from
defines a function. For example: f ( x )=x +2 business programs to engineering.
Examples of functional languages are Haskell, LISP, ML and Scheme. The first major program written in C was the UNIX operating system, and for
many years C was considered to be inextricably linked with UNIX. Now,
Sum function in Haskell however, C is an important language independent of UNIX.
C is a particularly popular language for personal computer programmers
add : :(∫ ,∫ )→∫ ¿ because it is relatively small - it requires less memory than other languages.
add ( x , y )=x + y
2.5.1. Basic Structure of a C Program
A C program is made up of the following components:
2.4.4. Declarative Paradigm  Processor directive
In declarative (logic) programming, a program is a collection of facts and  Declaration of variables
rules involving relational expressions. Declarative paradigm uses the  Declaration of functions
principle of logical reasoning to answer queries. It is based on formal logic  Function main()
 Definition of functions
#define identifier expression
a. The Preprocessor Directive
A preprocessor directive is a statement that begins with the # symbol. It Where
instructs the compiler to include C preprocessors such as header files and o Identifier specifies the macro name to which a value will be
symbolic constants before compiling the C program. There are two assigned
categories of preprocessor directives: the include directive and the define o Expression specifies the value that is assigned to the identifier. It
directive. may be a constant value, a string or an arithmetic expression.

 The Include Directive For example:


An “include directive” is used to include a header file. A header file is a #define Pi 3.14
library file that contains declarations for a special group of functions that #define City Limbe
can be used in the main body of the program. A header file must be included
at the beginning of a program, if its functions are to be used in the program. b. Declaration of Variables
The extension of a header file is ".h". A program may contain many header A variable is a memory location reserved to contain a value that may change
files. The general syntax to include a header file at the beginning of a during the execution of the program. Variables are used for storing input
program is: data or values generated as result of processing. Variables are characterized
by their name, type and scope.
#include <name of header file>
 Variable Names
For example: A variable’s name or identifier in C can be anything from a single letter to a
#include <stdio.h> word. However, it must begin with a letter or the underscore character but
#include <math.h> the other characters in the name can be chosen from the following sets:
a ..z (any letter from a to z)
The file “stdio.h” contains standard input and output functions that are used A .. Z (any letter from A to Z)
to get input (scanf) and print output (printf). The file “math.h” contains math 0 .. 9 (any digit from 0 to 9)
functions used for mathematic calculations. _ (the underscore character)

 The Define Directive Examples of valid variable identifiers are: x, total, area_of_circle, x1, _a and
The “define directive” is used to define a symbolic constant which is assigned aX.
a value that will remain constant during the execution of the program. Its
general syntax is:
Remark! C is case sensitive, so the identifiers sum and SUM are different. o It provides the compiler with a list of the variables in a convenient
Same for total and Total. All key words must be in lower case. place so that it can cross check names and types for any errors.

 Variable Types Some basic C types are:


Every variable has a type. The type of the variable specifies what sort of data
will be stored in it. The type of a variable is specified during its declaration. Type Description
To declare a variable in C, one writes the type followed by the variable name 1. char a single ASCII character
or identifier. int standard integers
2.
The general syntax for declaring a variable is: (usually 32 bits)
3. long int (long) long integers
[Type] [Name of variable] float standard floating point
4.
or real numbers
For example: long float long floating point
5.
int age; (double) numbers
float area; 6. unsigned int positive short integers
int sum = 0; unsigned float positive standard
inti,j=2; 7.
floating point numbers
8. unsigned long positive long integers
o int specifies that the variables age and sum are integers while float
unsigned positive long floating
specifies that the variable area is a floating point (real or decimal) 9.
double point numbers
number.
o int sum=0 indicates that variables can be assigned values when they
are declared. This is called initialization. Therefore, one can
 Scope of a Variable
initialize a variable at the time of declaration.
The scope of a variable describes where in the program the variable can be
o i and j are integers with j initialized at 2.
legally used. Based on its scope, a variable can be global or local.
A global variable is a variable that can be recognized anywhere in the
Variable declaration serves two purposes:
program. Global variables are declared before the function main().
o It gives the compiler precise information about the amount of
A local variable is a variable that has meaning only within a particular
memory that will have to be given over to a variable when a
function or other program unit. Local variables can be declared anywhere
program is finally run and what sort of operations will have to be
following the opening brace ({) of a block. The name of a local variable can
used on it.
be used in another block elsewhere in the program, where it will refer to an Remark! The use of 'void' or 'int' before the function main() is optional. If it
entirely different variable. is not specified, the compiler assumes it is int.

c. The Function main( )  The body of the function main() is made up of program statements
The function main() indicates the beginning of the actual C program. It is the which represent instructions to be executed by the computer. An
point at which execution of program is started. When a C program is instruction may be an input/output statement, an arithmetic
executed, the execution control goes directly to the function main(). Every C statement, a control statement, a simple assignment statement or
program must have a function main(). The general syntax is: any other statement.

int main()
A basic C program looks like this:
{declaration of local variables;
program statements;
#include <header.h> #include <stdio.h>
return 0;
#define symbolic constant
}
Global declarations int main()
void main() {
 The keyword “int” is used before the main() function to indicate the { local declarations printf(“Welcome to the world of
type of the value that is returned by the main() function. By definition, program instructions; C!”);
a function may accept no, one or more inputs and returns no or a } return 0;
single value. 'int' means that the program will return an integer value 2.5.2. Input/Output Statements
after its execution. The word “void” can be used in the place of “int” to
indicate that the program will not return any value. a. The scanf Function
It is good practice to always return a value because the operating scanf (print-formatted) is used to interpret characters input to the computer
system uses the return value to determine whether the program has and to store the interpretation in the specified variable(s).
been executed successfully or not.
Example:
 The body of the main() function must be enclosed in braces (or curly scanf("%d", &x);
brackets { }). These braces are called delimiters. The left brace
indicates the start of the body of the function whereas the matching This statement reads a decimal integer from the keyboard and stores the
right brace indicates the end of the body of the function. Braces are value in the memory address of the variable x.
also used to indicate the beginning and ending of block (compound) In the statement,
statements.  %d is a conversion specifier and specifies that the variable to be readis
of type integer. Other conversion specifiers used in C are %f for
floating point numbers, %c for characters and %s for strings.
c Character
 &gives the address of something in memory. That is, it generates a d Decimal integer
pointer to the [Link] arguments to scanfmust be pointers f Normal floating point
(addresses), hence the need for &. s String
Scientific notation floating
b. The printf Function e
point
printf(print-formatted) is used to display information on the screen.
Examples:
Example: scanf(“%s”, &Name);
printf("The radius is %f cm",x); printf(“Name: %s”, Name);
scanf("%d %d",&x,&y);
in the statement, printf("The sum of %d and %d = %d",x,y,z);
 “The radius is %f cm” is the control string. The text in between the
double quotes will be displayed except the conversion specifier %f. d. Character Input/Output
getchar and putchar are used for the input and output of single characters
 x is the variable to be printed. The value of x will be printed where the respectively.
conversion specifier is placed in the control string. getchar() returns an int which is either EOF (indicating end-of-file) or the
next character in the standard input stream
Many conversion specifications can be used in a control string. In this case, putchar(c) puts the character c on the standard output stream
the programmer has to ensure that both the number of conversion
specifications and the number of variables to be printed are the same and, of #include<stdio.h>
the correct type specified. main()
{ char ch;
Example: ch=getchar();
printf(“The sum of %d and %d is %d”, x, y, x+y). printf(“%c”,ch);
}
If x=2 and y=3, then what will be displayed on the screen is: The sum of 2
and 3 is 5 2.5.3. Operators and Expressions
An operator is something which takes one or more values and does
c. Common Conversion Specifiers something useful with those values to produce a result. C has different types
of operators which can be arithmetic, relational, logical, assignment
Character Form of output operators etc.
An expression is simply the name for any string of operators, variables and c. Logical Operators
numbers. Logical operators are used to combine logical values.

a. Arithmetic Operators Operato Descriptio Example


Arithmetic operators are used for arithmetic calculations. r n
1. ¿∧¿ Logical (a>b) && (a>C)
Operato Description AND
r 2. ¿∨¿ Logical OR If ((a ==0) || (a ==1)), printf(“a!=1”);
1. +¿ Addition 3. ! LogicalNOT If found == 1 (true), !(found) == 0 (false)
2. −¿ Subtraction (Negation)
3. ¿ Multiplication 4. & Bitwise 4 & 5 = 0100 & 0101 = 0100 = 4
4. ¿ Division AND

5. Remainder after 5. | Bitwise OR 4 | 5 = 0100 | 0101 = 0101 = 5


%
division(modulo 6. ^ Bitwise 3 ^ 9 = 0011 ^ 1001 = 1010 = 10
arithmetic) XOR

b. Relational Operators Remark! Bitwise operators allow manipulation of the actual bits held in
Relational operators are used for comparisons. Expressions that use these each byte of a variable. Other bitwise operators are:
operators produce a true or false value when they are evaluated.
 Right shift (>>) – binary division by 2
E.g. if a=¿ 0010111 then a >>¿ 0001011.
Opera Description Example
Also, a>>2 = 0000101
tor
 Left shift (<<) – binary multiplication by 2
1. == Equal to If a == 2 and b== 5; a == b evaluates to FALSE
If a=¿ 0010111 then a <<¿ 0010110 .
2. < Less than a < b evaluates to TRUE
Also, a << 2 = 1011100
3. > Greater than a > 5 evaluates to FALSE
 One’s complement (~)
Less than or b <= 5 evaluates to TRUE
4. <=
equal to
Greater or a >= 5 evaluates to FALSE
5. >= d. Assignment Operators
equal to
Assignment is the process of storing a value in a variable. The assignment
6. != Not equal to a != b evaluates to TRUE
operator is the equal sign (=).
bitwise XOR
For example:
pi=3.14 e. Increment and Decrement Operators
sum=∑ +1 Increment and decrement operators give a shorthand method of adding and
subtracting 1 from an object respectively.

The variable pi is assigned the value 3.14 and the variable sum is
++ Increment a ++≡ a=a+1
incremented by 1.
-- Decrement b-- ≡ b=b−1
C has different types of assignment operators.
Operat Description Example These operators can be prefix or postfix. With the prefix form the variable is

or changed before the value of the expression in which it appears is evaluated,


and with the postfix form the variable is modified afterwards.
1. = assign c=2
2. += Assign with a=a+b ≡ a +=b b=3; b=3;
add a=b ++ +6 ; /* a = 9, b = 4 */ a=¿ ++b+6 ; /* a = 10, b = 4 */
3. -= Assign with a=a−b ≡ a -=b
subtract
2.5.4. Control Flow Statements
4. *= Assign with a=a∗b ≡ a -=b
Control flow statementsmake it possible to make decisions, to perform tasks
multiply
repeatedly or to jump from one section of code to another. C control flow
5. /= Assign with a=a/b ≡ a /=b statements are If statement, switch statement, while statement, do … while
divide
statement, for statement and jump statements.
6. %= Assign with a=a % b ≡ a %=b
remainder
a. The IFStatement
7. >>= Assign with a>>= b The IFstatement is a decision-making statement that is used to evaluate an
right shift
expression and then take one of two possible actions depending on the
8. <<= Assign with a<<= b validity of the [Link] IF statement has two forms.
left shift
9. &= Assign with a=a∧b ≡ a&=b Syntax:if(expression)
bitwise AND
statement(s);
10. |= Assign with a=a∨b ≡ a |=b
bitwise OR and
11. ^= Assign with a=ab ≡ a ^=b
if (condition)
{  if (a == 1 && b == 2)
statement(s); This expression is TRUE if a is 0 ANDb is 1. If one is NOT TRUE, the whole
} expression is evaluated to FALSE. In other words, a must equal 0 and b
else equal 2, for the expression to be TRUE.
{
statement(s) C Fun!
} Shakespeare must have been disappointed to learnthat,
whatever the value of a variable tobe, the result of the
question tobe || !tobe, isalwaystrue. Fortunately, thisis not a
In the first form, if the expression specified in the if statement evaluates to
true, the statements inside the if-block are executed and then the control gets
transferred to the statement immediately after the if-block. b. Nested IF
In the second form, the else part is required only if a certain sequence of It is also possible to embed or to nest IF statements one within the other.
instructions needs to be executed if the expression evaluates to false. Nesting is useful in situations where one of several different courses of
action need to be selected.
scanf(“%d”,&b);
if (b>0)
Example:
printf(“Number %d is positive”,b);
#include<stdio.h>
else
int main()
printf(“Number %d is negative”,b);
{ int a, b;
scanf(“%d %d ”, &a,&b);
 The expression is always enclosed within brackets. if(a>b)
 If statement(s) is a single statement, the curly brackets can be omitted {
as in the example above though it is good practice to always enclose printf("%d is greater.", a);
them with curly brackets. }
else
Sometimes we may want to evaluate more than one thing in an expression. if(a==b)
This can be done in C by using the logic operators AND and OR. {
printf("%d and %d are the same: ", a,b);
For example: }
 if (a==0 || b==1) else
This expression is TRUE if a is 0 OR b is 1. It is also true ifa=0 andb=1. {
printf("%d is greater.", b); #include<stdio.h>
} int main()
return 0; { int a, b; char op;
} printf("Enter two integers: ");
scanf(“%d %d”, &a, &b);
c. SWITCH Statement printf("Enter an operator: ");
A switch statement is used for multiple way selections that will branch into scanf("%c", &op);
different code segments based on the value of a variable. switch(op)
{
Syntax:switch(variable) case+: printf("%d + %d = %d ", a, b, a+b); break;
{ case-: printf("("%d - %d = %d ", a, b, a-b); break;
Case value1 : code segment1; break; case*: printf("("%d * %d = %d ", a, b, a*b); break;
Case value2 :code segment2; break; case/: printf("%d / %d = %f", a, b, a/b"); break;
… default: printf("Error!");
Case valueN : code segment N; break; }
default: statement(s); return 0;
} }

If the value of the variable equals ‘value1’, code segment1 is executed. Remark! If you need to select among a large group of values, a switch
Otherwise, if it equals value2, code segment2 is executed and so on. statement will run much faster than a set of nested IFs.
The statement break is used after every case in order to prevent execution The switch differs from the IF in that switch can only test for equality,
from continuing into the code segment of the next case without even whereas IF can evaluate any type of Boolean expression.
checking its value.
For example, supposing a switch statement has five cases and the value of d. WHILE Statement
the third case matches the value of expression. If no break statement were The While statement or while loop is an iteration statement. Iteration
present at the end of the third case, all the cases after case 3 would also get statements are used to execute a particular set of instructions repeatedly
executed along with case 3. If break is present only the required case is until a particular condition is met or for a fixed number of iterations.
selected and executed; after which the control gets transferred to the
next statement immediately after the switch statement. There is no break Syntax:while (condition)
after defaultbecause after the default case the control will either way get {
transferred to the next statement immediately after switch. statements;
}
The do-while statement evaluates the condition at the end of the loop after
The statement or statements are only executed if the expression is true (non- executing the block of statements at least once. If the condition is true the
zero). After every execution of the statements, the expression is evaluated loop continues, else it terminates after the first iteration.
again and the process repeats if it is true.
Syntax:do {
Example: statements to be executed;
inti=1; } while(expression);
while(i<=10)
{ Remark!
printf(“%d”, i);  Pay attention to the semicolon which ends the do-while statement.
i++;  The difference between while and do-while is that the while loop is an
} entry-controlled loop - it tests the condition at the beginning of the
This code will loop 10 times writing the numbers 1 to 10. loop and will not execute even once if the condition is false, whereas
the do-while loop is an exit-controlled loop - it tests the condition at
Example: A program that counts the number of blank spaces in a line of text. the end of the loop after completing the first iteration.

#include <stdio.h> Example: A program to print the sum of the digits in a number.
int main()
{ charch; short count = 0; #include<stdio.h>
printf("Type in a line of text\n"); int main()
while((ch = getchar()) != '\n') { int n, a,sum=0;
{ printf("Enter a number:");
if(ch == '') scanf("%d", &n);
count++; do{
} a =n%10;
printf("Number of spaces = %d\n",count); sum=sum+a;
return 0; n=n/10;
} } while(n>0);
printf("Sum of the digits = %d",sum);
e. DO… WHILE Statement return 0;
}
A practical use of the do-while loop is in an interactive menu-driven scanf(“%d”,&b);
program where the menu is presented at least once and then depending
upon the choice of the user, the menu is displayed again or the session is for (i=1;i<=b;i++)
terminated. Consider the same example that we saw in switch-case. Without prod=prod+a;
using an iteration statement like do-while, the user can choose any option
from the menu only once. Moreover, if a wrong choice is entered by mistake printf(“%d”,prod);
the user doesn’t have the option of entering his choice again. Both these return 0;
faults can be corrected by using the do-while loop. }

f. FOR Statement 2.5.5. Arrays


The FOR statement or the FOR loop repeatedly executes a set of instructions An array isa collection of data items of the same type that are given a single
that comprise the body of the loop until a particular condition is satisfied. name (identifier) and distinguished by numbers (subscripts).In simple terms,
an array is a list of elements of the same type. When an array is created
Syntax: for(initialization; termination; increment/decrement;) (declared), its size (dimension) and the type of its elements are specified.
{ Arrays can be one dimensional or multidimensional.
statements to be executed;
} a. One-Dimensional Arrays
One-dimensional arrays are declared using a single index (subscript).
 The initialization expression initializes the looping index which For example:
controls the looping action. The initialization expression is executed int A[10], char Name[10], int vect[20]
only once, when the loop begins.
 The termination expression represents a condition that must be true int A[10] creates an array called “A” of 10 integers. The elements of array A
for the loop to continue execution. are referenced as:
 The increment/decrement expression is executed after very iteration A[0], A[1], [2], … A[8], A[9]
to update the value of the looping index.
Where A[0] is the first element in the array, A[1] the second element, A[2] the
Example: A program to multiply two numbers by successive additions. third element and A[9] the last element.

#include <stdio.h> Values can be assigned to the array as if each element were a separate
int main() variable.
{ int a, b, i, prod=0; A[0] =3; A[1] =1; A[2] =0; … A[9] =-5
scanf(“%d”,&a);
A loop can as well be used.
For example:
int main()
{ int i, n=10, A[n]
i=0;
while(i<=n)
{
printf(“Enter element at position %d”, i);
scanf(“%d”,&A[i]);
i++;
}
return 0;
}

To display the individual elements of the array A, we can proceed as follows.


printf(“%d”, A[0]); //prints the first element of the array.
printf(“%d”, A[1]); //prints the second element of the array.
printf(“%d”, A[2]); //prints the third element of the array.

printf(“%d”, A[n-1]); //prints the last element of the array.

You might also like