Top Banner
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1
34

Program

Jan 10, 2016

Download

Documents

dougal

Program. A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. Programming Fundamentals I. BSCS Semester1. Diagrammatic Representation of Program Execution Process. Execution of C Program. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Program

Program

A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.

1

Page 2: Program

Programming Fundamentals I

BSCS Semester1

2

Page 3: Program

Diagrammatic Representation of Program Execution Process

3

Page 4: Program

Execution of C Program

Preprocessing Using a Preprocessor program to convert C source code in expanded source code. "#includes"

and "#defines" statements will be processed and replaced actually source codes in this step. Compilation Using a Compiler program to convert C expanded source to assembly source code. Assembly Using a Assembler program to convert assembly source code to object code. Linking Using a Linker program to convert object code to executable code. Multiple units of object codes

are linked to together in this step. Loading Using a Loader program to load the executable code into CPU for execution.

http://www.ustudy.in/node/10273

4

Page 5: Program

Structure of C Program

#include<stdio.h>#include<conio.h>

void main( )

{

printf(“Welcome to Computer Scientists”); getch();}

Program Body

main function

Starting point of program execution

Preprocessor Directives

Header FileTo include header files in our program

Contains built-in-functions. These are also called pre-defined or already developed

functions

File name(standard input output )

h stands for header file

Function Name

Return type of main function. It is used

to determines whether the program is executed

successfully or not. Void means nothing

Parenthesis shows function. It is used to pass parameters/arguments

Body Begin

Body End

printf stands for print function. It will print the output on the monitor

Angle or pointed brackets

String or message to be displayed on monitor. It must be enclosed in double quotes(“ “)

Each statement must end with semicolon. A statement without

semicolon generates syntax error.

1

2

3

Get character function. It get a

character at runtime. But we use it to stay screen to see output 5

Page 6: Program

Simple Steps to write and run a program in C.

1. Go to this path C:\TC\BIN then double click on short to open C language.

2. Now save your program by choosing a meaningful program file name. e.g. welcome.c is a file name for a program that will display welcome message at runtime.

3. Now write your program as explained in the previous slide. (translation of algorithm to a c program).

6

Page 7: Program

4. Press Alt+F9 key to compile program. If your program is error free then following screen will appear:

7

Page 8: Program

5. Now press Ctrl+F9 key to run the program. Following screen shows the output of the program:

Now press enter to go back to the source code of the program

8

Page 9: Program

Now see the following sample program.

9

Page 10: Program

Formatted Input Statement scanf() The scanf function allows you to accept input from standard in, which for us is generally the

keyboard.

Syntax:      scanf(”control string”, &variable01, &variable02, …);

Example:        scanf(”%d”, &number);

E.g. Program #include <stdio.h> int main() { int a, b, c; printf("Enter the first value:"); scanf("%d", &a); printf("Enter the second value:"); scanf("%d", &b); c = a + b; printf("%d + %d = %d\n", a, b, c); return 0; } http://computer.howstuffworks.com/c6.htm

10

Page 11: Program

Printf() : ( Output function ) It displays information on screen. It returns the number of characters printed. It displays the text you put inside the double quotes. It requires the backslash character(escape sequence) to display some special characters. It can display variables by using the % conversion character. Printf format: a string argument followed by any additional arguments.                                    Syntax :          printf("control string",list);            where control string gives the format of data to be displayed, list contains the list of

variables, constants, array names to be printed. The general form is                      %w.p data type                           where % - conversion specification indicator                                      w - width of output data(optional)                                      p - Number of digits after decimal point or number of characters to to

displayed from a string                                      data type - type of output data or conversion character Printing Integer Numbers : The general format of control string to output an integer is       %wd       where w - width of output data(optional)                 d - conversion character for integer

Formatted Output Statement

11

Page 12: Program

Rules : If there is no width then the output number will be printed as such. If the output number width is greater than the width specified then it will be printed in full

irrespective of the width. The number printed is right justified. This can be changed by left by placing a minus sign after %

character. If the width specified is greater than the width of the output number, then the unused position is

left blank. The unused leading blanks in the output can be made to zero by placing a zero before the width

w. To print numbers with + or - sign, the sign should be placed before the variable. Example : Assume x=2000; Format                                               Output printf("%d",x);                                    2000   // Rule 1 printf("%3d",x);                                  2000   // Rule 2 printf("%5d",x)                                      2000     // Rule 4 printf("%-5d",x);                                2000        // Rule 3 printf("%07d",x);                               0002000     // Rule 5 printf("%4d",-x);                                -2000    // Rule 6

12

Page 13: Program

Printing Real Numbers : The general format of control string to output a real number is                  %w.p f or e where  w - width of output data(optional)  p - number of digits after decimal point f - conversion character for floating point without exponent e - conversion character for floating point with exponent Rules : If no decimal place count(p) is placed, the default is 6 places. If a number contains more than 6 decimal places, the result will be rounded to 6 places. The integer part of a number is right justified and the decimal part is left justified. By placing a - sign after % character the integer part can be made to left justified. To print a number with + or - sign the sign should be placed before the variable. Example : Assume x=123.4678; Format                                               Output printf("%8.4f",x);                                123.4678 printf("%f",x);                                      123.467800  printf("%e",x);                                     1.234678e+02 printf("%-8.2f",x);                                123.47  (left justified) Printing strings : The general format of control string to output a string is          %w.ps where   w - width of the string(optional) p - number of characters to be printed from the beginning s - conversion character for string

13

Page 14: Program

Rules : If the width of the string is greater than the width specified, the string will be printed in full. The output is right justified. By placing a - sign after % character it can be changed to left justified. Example : Assume college="mspvl"; Format                                               Output printf("%s",college);                           mspvl printf("%10s",college);                       mspvl printf("%3s",college);                         mspvl printf("%5.2s",college);                     ms

14

Page 15: Program

Another Sample Program

Program:#include<stdio h>void main(){ int number;printf(”Enter an integer: \n”); //prompt messagescanf(”%d”, &number); //read messageprintf(”The number you entered is: %d”, number);getch();} Output:    Enter an integer:    25    The number you entered is: 25Rules:• The ampersand symbol, &, is very important.•It’s an operator specifying the variable name’s address. •Omitting it, might result into unexpected results.•We dont use ampersand(&) symbol in front of the string_name.

15

Page 16: Program

16

Page 17: Program

17

Page 18: Program

Comments

Non - executable statements

Comments are used for program documentation

Two formats

Single Line Comments Multi Lines Comments

// This program is used to show the Welcome Message.

/*This program is used to show the square of even numbers from 10 to 100.*/

18

Page 19: Program

TokensTokens are individual words and punctuation marks in passage of text. In C, program the smallest individual units are known as C Tokens. C has Six types of Tokens. The Tokens are shown in figure. C programs are written using these tokens and the syntax of the language.

19

Page 20: Program

20

Page 21: Program

General form of a C++ program

// Program description

#include directives

int main()

{

constant declarations

variable declarations

executable statements

return 0;

} 21

Page 22: Program

C++ compiler directives

The #include directive tells the compiler to include some already existing C++ code in your program.

The included file is then linked with the program.

There are two forms of #include statements: #include <iostream> //for pre-defined files

#include "my_lib.h" //for user-defined files

22

Page 23: Program

C++ keywords

Each keyword has a predefined purpose in the language.

Do not use keywords as variable and constant names!!

Exmples: bool, break, case, char, const, continue, do, default, double, else, extern, false, float, for, if, int, long, namespace,

return, short, static, struct, switch, typedef, true, unsigned, void, while etc etc..

23

Page 24: Program

C++ identifiers Variable: Location in memory where value can be stored An identifier is a name for a variable, constant, function, etc.

Series of characters (letters, digits, underscores) Cannot begin with digit Are Case sensitive Cannot have special characters in them.

Examples of valid identifiers: First_name, age, y2000, y2k

Examples of invalid identifiers: 2000y, X=Y, J-20,

~Ricky,*Michael

Identifiers are case-sensitive. For example: Hello, hello, WHOAMI, WhoAmI, whoami are unique identifiers.

http://www.ustudy.in/node/289724

Page 25: Program

Programming Style

C++ is a free-format language, which means that: Extra blanks (spaces) or tabs before or after identifiers/operators are ignored. Blank lines are ignored by the compiler just like comments. Code can be indented in any way. There can be more than one statement on a single line. A single statement can continue over several lines.In order to improve the readability of your program, use the following conventions: Start the program with a header that tells what the program does. Use meaningful variable names. Document each variable declaration with a comment telling what the variable is

used for. Place each executable statement on a single line. A segment of code is a sequence of executable statements that belong

together. Use blank lines to separate different segments of code. Document each segment of code with a comment telling what the segment

does.

25

Page 26: Program

Variables

As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:

int b; This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:

b = 5; You can use the value in b by saying something like: printf("%d", b); In C, there are several standard types for variables: int - integer (whole number) values float - floating point values char - single character values (such as "m" or "Z") We will see examples of these other types as we go along.

26

Page 27: Program

Alphabets from A to Z or a to z The digits from 0 to 9 Underscore(_) can be used The first character of an identifier can not be a digit The name of an identifier can not be a reserve word No space allowed in the name of identifier

Rules to Declare an Identifier (variable)

Valid Name:A

Student_Name_Fname

Pi

Inalid Name:$Sum //special ch.

6StName // 1st letter digitF name // no space allowed

int // reserve word

27

Page 28: Program

Syntax

Data-Type Space Variable-Name(Indentifier);e.g.

int frstNumber;char choice;float divide;long output;

Identifier (variable) Declaration

Data-Type Space Variable-Name(Indentifier) = Value;e.g.

int frstNumber=10;char choice=‘y’;float divide=0.0;

Syntax

Identifier (variable) Initialization

28

Page 29: Program

How many bytes I am eating?

integer data

short 2 bytes

int 2 bytes(16 bit system)

4 bytes (32 bit system)

long 4 bytes

Floating point data

float 4 bytes

double 8 bytes

long double 10 bytes

Character char 1 byte

Boolean bool 1 byte29

Page 30: Program

Assignment Operator (=)

= (assignment operator) Assigns value to variable Binary operator (two operands) Example:

sum = variable1 + variable2;

30

Page 31: Program

Memory Concepts

Variable names Correspond to actual locations in computer's

memory Every variable has name, type, size and value When new value placed into variable, overwrites

previous value

31

Page 32: Program

Memory Concepts

cin >> first; Assume user entered 45

cin >> second; Assume user entered 72

sum = first + second;

first 45

first 45

second 72

first 45

second 72

sum 117

IdentifierVariable

32

Page 33: Program

Arithmetic Rules of operator precedence

Operators in parentheses evaluated first Nested/embedded parentheses

Operators in innermost pair first

Multiplication, division, modulus applied next Operators applied from left to right

Addition, subtraction applied last Operators applied from left to right

Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

*, /, or % Multiplication Division Modulus

Evaluated second. If there are several, they re evaluated left to right.

+ or - Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

33

Page 34: Program

34

Thank You

New Computer Scientists