20
PROGRAMMING Introduction Students Guide In partnership with

1. Introduction Original - To Print

Embed Size (px)

Citation preview

Page 1: 1. Introduction Original - To Print

PROGRAMMING Introduction

Students Guide

In partnership with

Page 2: 1. Introduction Original - To Print

Introduction to Programming

Page I

SLANA Technology Learning Centre

Preface

Youth unemployment is high in Sri Lanka’s rural regions, and the disadvantaged youth

population has difficulty in accessing the required knowledge and training which will allow them

to break the existing cycle of poverty to build a better life for themselves. As of 2015, the field of

programming is flourishing on a global scale; nevertheless in rural areas of Sri Lanka, youth have

little to no access to learn programming.

‘Learn the Code that Builds Your World’ project was conceptualized by Sri Lanka Anti

Narcotics Association to address this important issue. This project aims to disseminate

programming knowledge and practical training to youth who previously would not have had the

opportunity to gain access to such teachings; with the ultimate goal of the beneficiaries to

become more employable at the end of their learning experience. One important aspect of this

project’s success is collaborating with relevant organizations, institutes, and schools that identify

apt students and help SLANA disseminate the coding curriculum.

SLANA has been very fortunate to be able to be sponsored by World Bank, Microsoft,

and Sarvodya Fusion to start our Learn the Code that Builds Your World program in Maskeliya

with Tea Leaf Vision being our first collaborative partner.

Page 3: 1. Introduction Original - To Print

Introduction to Programming

Page II

SLANA Technology Learning Centre

Introduction

Who Is This Book Aimed At?

This book is best suited for beginners. It is intended for anyone who so

far has not engaged seriously in programming and would like to begin doing it.

This book starts from scratch and introduces you step by step into the

fundamentals of programming. It won’t teach you on absolutely everything you

might need for becoming a software engineer and working at a software company,

but it will lay the groundwork on which to build up technological knowledge and

skills, and through them you will be able to turn programming into your

profession.

If you’ve never written a computer program, don’t worry. There is always

a first time. In this book we will teach you how to program from scratch. We

do not expect any previous knowledge or abilities. All you need are some basic

computer literacy and a desire to take up programming. The rest you will learn

from:

Programming with C# (Basic Guide)

Programming with C# (Advance Guide)

Web Designing with HTML (Basic Guide)

Page 4: 1. Introduction Original - To Print

Introduction to Programming

Page III

SLANA Technology Learning Centre

Table of Contents

Chapter 1

Introduction to Programming ........................................................................................ 1 What is Programming ?

What is Program ?

Understanding What a Programming is ?

Component of a Program

How a Program Choose Which Action is Perform

Chapter 2

Core Aspects of Programming ....................................................................................... 5 Programming Data Types

Chapter 3

Variables in Programming ............................................................................................. 7 Variable Initialization

Chapter 4

Naming Conventions of Variables ................................................................................. 8 Benefits

Read Ability

Length of Identifiers

Chapter 5

Operator Precedence ..................................................................................................... 10

Chapter 6

Flow Charts and Control Structures ........................................................................... 11

Psuedo Code

Flow Char Symbols

Conditional Statements

Loop structure / iterative structure

Exercises ................................................................................................................................ 14

References .............................................................................................................................. 16

Page 5: 1. Introduction Original - To Print

Introduction to Programming

Page 1

SLANA Technology Learning Centre

Chapter 1 Introduction to Programming

What is programming?

Programming has become a very popular subject that is being discussed globally. It is a

skill that anyone who has a basic understanding of computers can learn, regardless of age. And

one of the reasons why programming is making such big waves, is because once a person has the

skills of programming, it can be used in almost any field in the world.

Putting it in the simplest definition is, programming is writing a program; and writing a

program is a series of commands is given to the computer by you. So the commands you write,

the computer runs.

A programmer writes an instruction in a programming language. A complier then turns

that into 1’s and 0’s which the computer can understand.

People have „written programs‟ to:

Help cure diseases in patients

Helping save endangered animals

Making self driving cars

Designing robots

Making games, movies (Angry birds, Temple Run, Rio, …)

Making websites, apps (Facebook, Google Maps, Wikipedia)

All these programs seem very different to each other, but interestingly in almost every

program, almost every programmer uses the same basic concepts.

Learning the basics to programming is relatively easy, however relatively easy; however

from basic concepts to writing a useful program is not an easy task.

Figure 1.1

Page 6: 1. Introduction Original - To Print

Introduction to Programming

Page 2

SLANA Technology Learning Centre

Figure 1.2

What is a program?

Many people reading this book will already know what a program is, or at the very least

have used a computer program before. When you are emailing, visiting websites, chatting, etc,

you are using programs. A program can known as the output, and what your set of instructions is

ultimately trying to achieve.

Understanding what a program is

A program can be broken into smaller components. Let’s take the example of a book to

help you understand what that means. A book is made of chapters, paragraphs, sentences, words,

and at the very end letters and punctuation. Like such, a program can be broken down into smaller

and smaller components.

Component of a program

One such component is called a STATEMENT. In our example of the book, a

SENTENCE is to a BOOK, what a STATEMENT is to a PROGRAM. A statement is also

referred to as A LINE OF CODE.

A line of code on its own has its own structure and purpose but on its own, without other

line of codes/statements, it isn’t that meaningful.

The example below shows a simple program which is created of a few simple lines of code.

#include <stdio.h>

void main(){

printf(“SLANA”);

}

Figure 1.3

Page 7: 1. Introduction Original - To Print

Introduction to Programming

Page 3

SLANA Technology Learning Centre

How a program chooses which action to perform

First, it is important to know that a program is read from top to bottom, from left to right.

But when conditions come into play, running a program becomes more complex.

Programming Languages

Now you know what a simple program is. Let’s learn about programming languages.

Programming languages are important because it decides what syntax you use to write

programs. What this means is, look at the example above, the programming language uses curly

brackets“{ }”but if you are using different programming language you may have to use key

words like begin and end to represent the scope of the code.

In the example in Figure 1.3, the word “printf” is used to output the “SLANA”, but

other programming languages may use the words like “echo”, “write” … instead.

There are other aspects that programming languages define, but we will stop here for the

basics. There are many programming languages, but luckily although some of them can be very

different from each other, most have similarities which make learning other languages easier once

you learn one programming language.

Each programming language is used to do a specific type of program. Like you would not

go into the program Microsoft Word to paint a picture, similarly some programming languages

are best suited for specific types of programs.

Examples:

PHP is used for web based and database applications.

To create an application, Visual Basic is a good language to use.

Glimpse at the different programming languages

To give you a taste of the differences, here are the lines of codes for one simple program

which outputs the phrase “Hello World”

In C#:

public class HelloWorld

{

public static void main(string[] args)

{

Console.WriteLine(“Hello World!\n”);

}

}

Page 8: 1. Introduction Original - To Print

Introduction to Programming

Page 4

SLANA Technology Learning Centre

In C:

In Perl:

In Java:

In Pascal:

#include <stdio.h>

int main() {

printf("Hello World!\n");

return 0;

}

#!/usr/bin/perl

print "Hello World!\n";

public class HelloWorld

{

public static void main(string[] args)

{

System.out.println("Hello world!");

}

}

Program HelloWorld;

begin

writeln('Hello World');

end

Page 9: 1. Introduction Original - To Print

Introduction to Programming

Page 5

SLANA Technology Learning Centre

Table 2.1

Chapter 2 Core Aspects of Programming

There are three core aspects in programming

1) Input : Deal with data from various sources

2) Process : Determine what action to perform on the data received.

3) Output : Perform the appropriate action.

These core aspects also reflect in a lot of our day to day life activities as well.

Example:

When you take money out of the ATM machine

1. Input : First you enter the card, and then type in the

pin number.

2. Process : The program collects this information and

sees if it is correct

3. Output : If it is not correct,

It will display an error message and prompt

user to enter pin number again.

Once the entered data is correct, the program will move on to the next stage of asking

what type of account you have. And so on, a program deals with the data given to it, and then

decides what action to perform on the data that has been received, and finally performs the action.

Programming Data Types

Programs deal with several data types.

Let’s look at the data types with examples

Example Data Type

A person’s name like“Sandun” String

Number of cars Integer

Temperature Float / Decimal

Answering a true or false question in an exam Boolean

Figure 2.1

String : "A string is enclosed in quotes"

Integer : 0, 1, 5, 1000, -25, -12, ...

Float : 2.25, 3.333333, 5.1, 2.0, …

Boolean : true or false

Page 10: 1. Introduction Original - To Print

Introduction to Programming

Page 6

SLANA Technology Learning Centre

The first line data type is a String. It is enclosed with the double quotes. (“ ”)

Second and third line data types are Numbers

Fourth line data type is Boolean.

Important Tip!

Anything that is inside “ ” is a string.

So if you see “1.141”, what is the data type?

It is NOT a number, but a string. Similarly if

you see “true”, this is NOT a Boolean but it’s

a STRING.

Data type is important because it helps you

understand what you can or cannot do

with your data!

Page 11: 1. Introduction Original - To Print

Introduction to Programming

Page 7

SLANA Technology Learning Centre

Chapter 3 Variables in Programming

When we need to label our data to be used later in the program, we need to get help of

variables.

Variable Initialization

Example:

The variable email is holding “[email protected]” value while executing the program

which is contained the above line of code.

Important Tip!

Variable names are case sensitive in most

programming languages, and this means that the

variables: name, Name, and NAME are all different

variables.

Therefore in programming it is a good practice to

not use upper case and lower case differences to

differentiate between variables.

String email = “[email protected]”;

<data type><name of the variable> = <value to be hold>;

Page 12: 1. Introduction Original - To Print

Introduction to Programming

Page 8

SLANA Technology Learning Centre

Chapter 4 Naming Conventions of Variables

In computer programming, a naming convention is a set of rules for choosing the

character sequence to be used for identifiers which denote variables, types, functions, and other

entities in source code and documentation.

Benefits

Following the same coding conventions gives several benefits.

Some of which are:

Your code will have a consistent look, so that readers can better focus on content, not

layout.

Readers understand your code more quickly because they can make assumptions based

on previous experience.

You can copy, change, and maintain the code more easily.

You help ensure that your code demonstrates "best practices" for Visual Basic

Readability

Wisely chosen identifiers make it easier for developers to understand what the system is

doing and how to make other necessary changes.

For example, although the statement:

Is technically correct; what the purpose of that statement is not very clear.

Instead of that statement:

One can immediately understand the meaning of the source code as long as they are familiar

with the context of the statement.

Naming convention rules varies depending on context and languages. However there are

several elements in naming conventions that influence all most all commonly used naming

conventions.

One such element is the length of identifiers.

a = b * c;

weekly pay = hours_worked * pay_rate;

Page 13: 1. Introduction Original - To Print

Introduction to Programming

Page 9

SLANA Technology Learning Centre

Length of identifiers

Fundamental elements of all naming conventions are the rules related to identifier‟s

length (i.e., the finite number of individual characters allowed in an identifier).

Some considerations:

Shorter identifiers may be preferred as more practical, because they are easier to type.

Extremely short identifiers (such as 'i' or 'j') are very difficult to hard to detect using

automated search tools.

Longer identifiers may be preferred because short identifiers because they are relatively

easier to understand.

Very long identifiers maybe considered too messy to read

It is an open research issue whether some programmers prefer shorter identifiers because

they are easier to type, or think up, than longer identifiers, or because in many situations a longer

identifier simply clutters the visible code and provides little additional benefit.

Page 14: 1. Introduction Original - To Print

Introduction to Programming

Page 10

SLANA Technology Learning Centre

Table 7.1

Chapter 5 Operator Precedence

Operator Precedence is a rule used to clarify which procedures should be performed first

in a given mathematical expression.

The order of operations are,

This order is for many C- Style languages

Operator Description

1 () [] -> . Function call, scope, array/member access

2 ! ~ - + * & ++x --x (most) unary operations

3 * / % Multiplication, division, modulo

4 + - Addition and subtraction

5 << >> Bitwise shift left and right

6 < <= > >= Comparisons: less-than, ...

7 == != Comparisons: equal and not equal

8 & Bitwise AND

9 ^ Bitwise exclusive OR (XOR)

10 | Bitwise inclusive (normal) OR

11 && Logical AND

12 || Logical OR

13 = += -

= *= /= %= &= |= ^= <<= >>=

Conditional expression (ternary) and

assignment operators

14 , Comma operator

Page 15: 1. Introduction Original - To Print

Introduction to Programming

Page 11

SLANA Technology Learning Centre

Chapter 6 Flow Charts and Control Structures

We can represent the process of a program simply by using Flow Charts.

Pseudo code

Flow charts can be represented by using Pseudo Code.

Flow Charts Symbols

Example for Flow Chart and Pseudo code:

Figure 6.1 Figure 6.2

Table6.1

Page 16: 1. Introduction Original - To Print

Introduction to Programming

Page 12

SLANA Technology Learning Centre

Conditional Statements

Conditional statements perform different actions depending on whether a programmer

specified Boolean condition evaluates to be true or false.

If – then construct

The if-then construct is common across many programming languages. Although the

syntax varies quite a bit from language to language, the basic structure looks like follows,

Loop structure / Iterative structure

In a loop structure, the program asks a question, and if the answer requires an action, it is

performed and the original question is asked again until the answer is such that the action is no

longer required.

For example, a program written to compute a company’s weekly payroll for each

individual employee will begin by computing the wages of one employee and continue

performing that action in a loop until there are no more employee wages to be computed, and only

then will the program move on to its next action. Each pass through the loop is called iteration.

Loops constitute one of the most basic and powerful programming concepts.

Different Looping Structures:

1. For Loop

2. While Loop

for(<initial value>;<condition>;<way to iterate>){

}

<initial value>

while(<condition>){

<way to iterate>

}

IF (boolean condition) THEN

(Consequent)

ELSE

(alternative)

END IF

Page 17: 1. Introduction Original - To Print

Introduction to Programming

Page 13

SLANA Technology Learning Centre

3. Do While Loop

How to represent loops using Flow Charts and Pseudo codes:

Flow Chart:

Pseudo Code:

<initial value>

do{

<way to iterate>

}while(<condition>)

BEGIN

j = -4 // variable declaration

WHILE j < = 0

print j // output

j = j +1 // statements

END WHILE

END // end of the program

Repetition / loop (for /while)

Figure 6.3

Start

Initial value, j=-4

j<=0?

Print j

j= j + 1

Stop

False (F)

True (T)

Page 18: 1. Introduction Original - To Print

Introduction to Programming

Page 14

SLANA Technology Learning Centre

Exercises Select the correct answer

1. What will be output when you will execute following code? using System;

void main(){ int a=5,b=10,c=1; if(a<b&&b>c){ Console.WriteLine("SLANA"); } else{ break; } }

Select the correct answer:

A. SLANA

B. It will print nothing

C. Run time error

D. Compilation error

E. None of the above

2. What will be output when you will execute following code? using System; void main(){ int x=1; if(5>x--) Console.WriteLine(x); else Console.WriteLine("The Shawshank Redemption"); }

Select the correct answer:

A. 0

B. The Shawshank Redemption

C. Run time error

D. 1

E. 2

3. What will be output when you will execute following code? using System;

void main(){ int a=100; if(a>10) Console.WriteLine("Kumar Sangakkara"); else if(a>20) Console.WriteLine("M.E.K Hussey"); else if(a>30) Console.WriteLine("A.B. de villiers"); }

Page 19: 1. Introduction Original - To Print

Introduction to Programming

Page 15

SLANA Technology Learning Centre

Select the correct answer:

A. Kumar Sangakkara

B. A.B. de Villiers

C. Kumar Sangakkara M.E.K Hussey A.B. de Villiers

D. Compilation error: More than one

conditions are true

E. None of the above

4. What will be output when you will execute following code? using System;

void main(){ int m=5,n=10,q=20; if(q/n*m>=0) Console.WriteLine("William Gates"); else Console.WriteLine(" Warren Buffet"); Console.WriteLine(" Carlos Slim Helu"); }

Select the correct answer:

A. William Gates

B. Warren Buffet

Carlos Slim Helu

C. Run time error

D. Compilation error

E. None of the above

5. What will be output when you will execute following c code? using System; void main(){ int a=5,b=10; if(++a==6||b++==10) Console.WriteLine(a);

Console.WriteLine(b); else Console.WriteLine("John Terry"); }

Select the correct answer:

A. 5

10

B. 6

11

C. 6

10

D. 5

11

E. John Terry

Page 20: 1. Introduction Original - To Print

Introduction to Programming

Page 16

SLANA Technology Learning Centre

References

Quinstreet Enterprise. [ONLINE] Available at: http://www.webopedia.com/.

[Last Accessed 2014 December 19]

Tech Target (1999).[ONLINE] Available at: http://whatis.techtarget.com/.

[Last Accessed 2014 December 23].

Wikiversity. [ONLINE] Available at: http://en.wikiversity.org/wiki/.

[Last Accessed 2014 December 29].

Tutorials Point.[ONLINE] Available at: http://www.tutorialspoint.com/.

[Last Accessed 2015January15].