introduction to algorithms and flowchart

Upload: abdullah-al-suleimani

Post on 14-Apr-2018

248 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Introduction to Algorithms and Flowchart

    1/48

    ECT, Department of Engineering1

    Higher College of TechnologyDepartment of Engineering

    Electrical, Computer and Telecommunications Section

    Course Title: Computer Programming for Engineering

    Course Code: EECP1290

    Level: Diploma (First year)

  • 7/27/2019 Introduction to Algorithms and Flowchart

    2/48

    ECT, Department of Engineering2

    Chapter 1:

    Introduction to Algorithms and Flowchart

  • 7/27/2019 Introduction to Algorithms and Flowchart

    3/48

    ECT, Department of Engineering3

    Computer is an electronic machine which performs computational and logical procedures as per

    the requirements of the user. Requirements of users are communicated to computer by the help

    of programs/software. Writing program and software is a pure engineering activity and all

    engineering products need a design to be prepared before going for actual implementation. For

    every program/software we always need to prepare a design, which is called algorithm.

    1.1. Algorithm

    Algorithm is the logical steps used to process the input data in order to produce the required

    information and results. In other words, it is a step by step procedure.

    1.2. Algorithms characteristics:

    1) It should be clear and consists of definite serial steps guiding to the required

    output/result.

    2) It should be valid for all problems of the same type.

    The design of an algorithm to solve a specific problem needs high knowledge and big practical

    experience and good background about the details of the problem to be solved. For one problem

    as there can be multiple solutions, so there can be multiple algorithms for a problem.

    1.3. Tools to describe algorithms:

    1) Pseudocode- Using the words and linguistic expressions, mathematical relations and

    equations.

    2) Flowchartsdiagrammatic representation showing the control flow of the algorithm.

  • 7/27/2019 Introduction to Algorithms and Flowchart

    4/48

    ECT, Department of Engineering4

    1.4. Flowcharts

    A flowchart is a graphical representation of an algorithm and is very helpful in understanding the

    algorithm. Once the flowchart is drawn, it becomes easy to write the program in any high level

    language.

    Flowcharts are usually drawn using some standard symbols. Following are some basic symbols:

    Purpose ShapeStart or End of the algorithm

    Processing or some computation

    Input or output operation

    Conditions, Decision making and branching

    Connector or joining of two flows of algorithm

    Basic Guidelines for drawing Flowcharts:

    Following are some guidelines for drawing flowcharts:

    a. Before drawing a flowchart, It is better to do the following tasks.

    1. Identify the inputs and the outputs

    2. Identify the Processing in form of steps.

    3. Draw the flowchart

    b. The direction of flow of flowchart should be from left to right or top to bottom.

    c. Only one flow line should Enter/Exit from a process.

    or

  • 7/27/2019 Introduction to Algorithms and Flowchart

    5/48

    ECT, Department of Engineering5

    d. Only one flow line should Enter a decision symbol, but two flow lines, one for each

    possible answer (Yes and NO), should Exit from decision symbol.

    e. Only one flow line will exit from Start and 1 will enter in End of algorithm.

    f. Multiple flows can be joined to 1 flow using Connector symbol

    g. It is useful to test the validity of the flowchart by passing through it with a simple test

    data.

    1.5. Examples of flowcharts and algorithms:

    Problem 1:Write an algorithm and draw the flowchart for finding the average of two numbers

    Algorithm:

    Input:two numbers x and y

    Output:the average of x and y

    Steps:

    1. input x

    2. input y

    3. sum = x + y

    4. average = sum /2

    5. output average

    YesNo

    Start

    End

    START

    In ut x and

    sum = x + y

    average = sum/2

    Output average

    END

  • 7/27/2019 Introduction to Algorithms and Flowchart

    6/48

    ECT, Department of Engineering6

    Problem 2:Write an algorithm and draw the flowchart to compute a maximum of two numbers

    Algorithm:

    Input:two numbers N1 and N2

    Output:the Max number

    Steps:

    1. Input N1,N2

    2. if N1 > N2 go to step 3,otherwise go to step 4

    3. Max=N1, go to step 5

    4. Max=N2

    5. Output Max

    Problem 3:Write an algorithm to print Even numbers from 1 to 50.

    Algorithm:

    Input:Not required

    Output:Even numbers from 1- 50

    Steps:

    1. Counter = 2

    2. Repeat Steps 3 and 4 While Counter N2

    Max=N2

    No Yes

    START

    Counter=Counter+2

    Output

    Counter

    END

    Counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    7/48

    ECT, Department of Engineering7

    Exercise Problems

    1. Write algorithms to find the area of a rectangle, triangle and square and draw the

    flowcharts for each.

    2. Draw a flowchart to calculate displacement, S = Vit + at2

    3. Draw flowchart to find the sum and average of three numbers N1, N2, N3.

    4. Draw flowchart to solve the following problem:

    IF X > 0 S = 3X+2

    IF X = 30 Hot

    Temperature >= 25 and Temperature < 30 Moderate

    Temperature < 25 Pleasant

  • 7/27/2019 Introduction to Algorithms and Flowchart

    8/48

    ECT, Department of Engineering8

    Chapter 2

    Introduction to C Programming Language

  • 7/27/2019 Introduction to Algorithms and Flowchart

    9/48

    ECT, Department of Engineering9

    Programming in any language requires learning 2 major parameters.

    1. Syntax of Programming language.Grammar or rules of language for writing instructions

    2. SemanticsLogics / problem solving ability or skills for doing programming

    2.1. Basics of C Programming Language

    The C programming language is a computer programming language developed in the early

    1970s by Ken Thompson and Dennis Ritchie foruse on the UNIX operating system.

    C is popular for its efficiency, and is the most common programming language for writing

    system software, device drivers, interfacing devices with computer, microprocessor and

    microcontroller programming etc.

    2.2. What is a Program?

    A program is a set of instructions written in a computer programming language to solve a

    particular problem

    Programming not only needs knowledge of syntax of some programming language but it also

    establishes analytical and problem solving abilities.

    A Program consists of data and instructions.

    For example:

    Vi = 100

    t = 5 Data

    a = 60

    Displacement = Vi * t + 0.5*a*(t*t) Instructions

    Area = 2 * 3.14 * r

    Proper steps to do Programming

    1. Understand the problem by:

    Defining the outputs

    Defining the inputs

    Defining the relationships between I/O for identifying required processing.

  • 7/27/2019 Introduction to Algorithms and Flowchart

    10/48

    ECT, Department of Engineering10

    2. Develop algorithm and draw Flowchart

    3. Write the program in a computer language i.e. C using some IDE e.g. Turbo C ++.

    4. Test and debug the program.

    5. Run the program, input data, and get the results from the computer.

    2.3. Compiler

    Programming languages are like English language with some defined set of keywords and

    syntax, but it is not directly understandable by the computer machine. As Computer is a digital

    machine so it understands only language of 1s and 0s called machine language. So the program

    code written in C language is required to be converted in machine language (0s and 1s) so that

    computer can understand and perform that functionality. This Conversion/translation from Clanguage to Machine language is done using software called Compiler.

    The IDE which we will use in this course for programming Turbo C has a compiler to perform

    this conversion.

    2.4. Structure of a C program

    Any C program will have a look like this:

    # include

    void main (){

    /* Create variables

    Input instructions

    Processing instructions

    Output instructions */

    }

    1. #include

    This is a pre-processor directive. It is an instruction to the compiler. It tells the C compiler to

    include the contents of a file, in this case the system file stdio.h. This is a library definition file

    for all Input Output functions of C Language. Some other important library files are: conio.h,

    math.h etc

  • 7/27/2019 Introduction to Algorithms and Flowchart

    11/48

    ECT, Department of Engineering11

    2. main():

    main is a keyword in C language and it is the function which will be executed first always when

    you will run the program. Every program should have a main function otherwise it will not

    execute.

    3. { }

    Next, there is a curly bracket also called braces ("{ }"). Within these brackets will be the main

    program body (Instructions of the main function).

    4. Comments

    Comments in C are enclosed by /* .. comments .. */. Comments can go to multiple lines, just it is

    required to put /* symbol in the start and */ at the end.

    Whatever is written within comments symbol is not considered by the compiler as part of

    program so compiler will not also try to convert it to machine language.

    It is a good programming practice to put comments in your program for some explanation of the

    instructions. It will help you and other people who will read your program later on in

    understanding the code.

    How to use data in C Programs:

    2.5. Variables: memory places to store data

    Computer machines cant process data until it is not stored in the memory of the computer. It is

    exactly like a Calculator where first we input numbers, which Calculator stores in its memory

    and then when we define operation to be performed on that data, calculator take/access data from

    memory and perform operation.

    In Computers data is stored in a memory location which is identified as a variable. The reason of

    calling it variable is that, we can store any value in it.

    For example for calculating displacement we need to store data of Initial Velocity (Vi), Time (t)

    and Acceleration (a) in the memory.

    Vi = 100

    t = 5.2

    a = 60

  • 7/27/2019 Introduction to Algorithms and Flowchart

    12/48

    ECT, Department of Engineering12

    2.6. Data Types:

    We have to store different type of data including whole numbers, decimal numbers, text etc. So

    we need for each type of data different type of Variables.

    Data Types in C language:

    Following are the major data types used in C language for storing different types of data.

    Data type Type of data stored Size in memory (Bytes)

    char Store 1 letter/character, e.g. A, H, c, 2 etc 1 byte / 8 bits

    int whole numbers, e.g. 1 , 23, 1230 etc 2 bytes / 16 bits

    float floating point numbers (upto 7 digit precision)e.g. 3.12, 5.2 etc

    4 bytes / 32 bits

    double Bigger floating point numbers with moreprecision (15 digit)

    8 bytes / 64 bits

    Variables Declaration and Naming:

    In C language Variables are always declared at the start of the program. The syntax for declaring

    a Variable is:

    Method 1: Data type Variable Name = Initial Value ; int n1 = 13;

    Method 2: Data type Variable Name ; int n1;

    Method 3: Data type Variable 1 name, variable 2 name ; int n1, n2, sum;

    Examples:float Vi = 100.4;

    char choice;

    double S, Vi, a, t ;

  • 7/27/2019 Introduction to Algorithms and Flowchart

    13/48

    ECT, Department of Engineering13

    Variable Naming:

    For naming the variables we must need to follow certain rules including:

    1. The variable names in C can only be started with a character or an underscore ( _ ).

    2. Keywords of C language cant be used as a Variable name. E.g. we learnt data types. The

    names of data types are keywords, so they cant be the name of variables. Important

    keywords are:

    int, float, double, char, long, main, return, case, switch, do, static, else, for, while etc.

    3. Space is not allowed in the variable names.

    4. Special characters / symbols e.g. &, @, $ etc are not allowed in variable names.

    5. In one program 2 variables cant have the same name. But C language is a Case sensitive

    language, means VELOCITY is different from Velocity. So we can have 2 variables with

    same name but different case.

    Examples:

    Variable Name Status

    Value1

    1value value_1

    Value#1

    _1value

    Long

    long

    Return

    return

    area(a)

    id-number

    _id

  • 7/27/2019 Introduction to Algorithms and Flowchart

    14/48

    ECT, Department of Engineering14

    2.7. Input & Output in C language Programs:

    In C language we dont need to worry that how in our program we will take input from user

    using Keyboard and how we will output (display) out results on the Monitor. These

    functionalities are provided already (built in) in C language. We just need to know two things:

    1. Which function we have to use and how.

    2. The function we are using is in which Library.

    Now for Input and Output we are using:

    Requirement Function Name Library / Header file

    Output/Display on Monitor Printf stdio.h

    Input from Keyboard scanf stdio.h

    Printf function (for Output):

    Syntax:

    printf( Constant String & format specifiers, variable/expressions);

    - Constant String will be any string which you exactly want to display on the monitor as

    written in printf statement.

    - Format specifiers are used to specify that we want to display the value of a variable or

    result of an expression. It is written always with % symbol followed by a letter depending

    on the data type of variable to be printed.

    Format specifiers:

    Format Specifier Data Type

    %c char

    %d int%f float

    %lf double

  • 7/27/2019 Introduction to Algorithms and Flowchart

    15/48

    ECT, Department of Engineering15

    Examples:

    1. printf ("I am a student of HCT in Engineering department"); //String output

    Float gpa = 3.2;

    2. printf ("%f",gpa);

    3. printf ("My GPA in Programming = %f", gpa);

    Example 1

    Write a program that add two integers 30 and10 ?

    #include

    void main()

    { int n1, n2, sum;

    n1 = 30;

    n2 = 10;

    sum = n1 + n2;

    printf("Sum result of %d and %d = %d", n1, n2, sum);

    }

    Example 2

    #includevoid main()

    {

    int num = 100;

    float fnum = 3.14;

    double dnum = 166.3456;

    char ch = 'A';

    printf(%d -- %f -- %lf -- %c, num, fnum, dnum, ch);

    }

    Special Control Characters

    Sum result of 30 and 10 = 40

    100 -- 3.14166.3456 -- A

  • 7/27/2019 Introduction to Algorithms and Flowchart

    16/48

    ECT, Department of Engineering16

    Control characters are written with a backslash character \ followed in printf statement inside the

    String symbols " ".

    Following are two control characters used commonly.

    Control Character Purpose\n For New line

    \t For Tab (Creating space)

    Example 1

    # include

    void main(){

    printf(" I am studying in Diploma (First Year)\n " );

    printf(" in Engineering department of\tHCT");

    }

    scanf function (for Input from User)

    scanf is the input function which gets input from the keyboard.

    Syntax:

    scanf ("format specifiers (with % symbols)", &variable1, &variable2, ..);

    Within String " ", only format specifiers of the variables which will be input will be written, and

    in second part the names of the variables which will be input will be written with & (address

    operator) symbol.

    Example:

    int a, b;

    scanf("%d%d", &a, &b);

    I am studying in Diploma (First Year)

    in Engineering department of HCT

  • 7/27/2019 Introduction to Algorithms and Flowchart

    17/48

    ECT, Department of Engineering17

    Example:

    Write a program that reads 2 integer numbers and print their sum?

    # include

    void main(){

    int num1,num2,sum;

    printf("Enter First Number:\t");

    scanf("%d",&num1 );

    printf("Enter Second Number:\t");

    scanf("%d",&num2);

    sum=num1+num2;

    printf(Sum\t=\t%d,sum);

    }

    Enter First Number: 15

    Enter Second Number: 25

    Sum = 40

  • 7/27/2019 Introduction to Algorithms and Flowchart

    18/48

    ECT, Department of Engineering18

    Exercise Questions

    1. We want to write a program to Input & store the marks of 5 courses and then calculate

    GPA of each course and Semester GPA. After calculation display the Marks, GPA and

    SGPA. Now keeping in mind all these answer following questions.

    a. How many and which type of variables are required for above program?

    b. Write a Valid variable name for each variable which you will use in this program.

    c. Do we need to use scanf function in this program and where?

    d. Do we need to use printf function in this program and where?

    2. Write programs to find the area of:

    a. Circle

    b. Triangle

    c. Square

    d. Rectangle

    3. Give 10 examples of Variable names which are Valid and 10 Invalid variable names.

  • 7/27/2019 Introduction to Algorithms and Flowchart

    19/48

    ECT, Department of Engineering19

    Chapter 3

    Operators and Expressions

  • 7/27/2019 Introduction to Algorithms and Flowchart

    20/48

    ECT, Department of Engineering20

    As in C language all different type of processing and computations can be done so there are

    different types of Operators are available also. Following are the major types of Operators used

    in C language:

    1. Assignment operators

    2. Arithmetic operators

    3. Relational operators

    4. Logical operators

    5. Increment & decrement operators

    3.1. Assignment Operator (=)

    = symbol in C language is not equal to, instead it is called Assignment operator.

    Its functionality is to assign/put the value mentioned on Right hand side (RHS) in to the variable

    mentioned on Left hand side (LHS).

    For example:

    x = 6.5; /* 6.5 will be assigned to the variable named x */

    y = x * 2; /* value of x will be multiplied with 2 and result will be put into variable y */

    z = y; /* whatever is the value of y will be assigned to z */

    Here it is important to remember that on LHS only a variable can come, while on RHS we can

    write a variable, a constant or an expression.

    3.2. Arithmetic Operators

    Operator Purpose

    + Addition- Subtraction

    * Multiplication

    / Integer Division

    % Modulus/Remainder

  • 7/27/2019 Introduction to Algorithms and Flowchart

    21/48

    ECT, Department of Engineering21

    Arithmetic Expressions

    Algebraic expression C language expression

    3x +2x+1 3*x*x+2*x+1

    Vit+1/2at Vi*t+0.5*a*t*t

    r 3.14*r*r

    Precedence of Operators

    Operators Precedence

    ( ) Highest

    * / %

    + - Lowest

    In Arithmetic expression if there are multiple operators of same precedence than evaluation will

    be done from left to right always.

    Examples

    Expression Result

    10 + 10 * 5 60

    5 * 3 + 6 / 3 17

    4/2*2+3*2+1 11

    10-4+2 8

    11%3*2+3*0 4

    3.3. Relational Operators

    These operate check certain relation between numbers (int, float or double) and returns result in

    the form of 1 (True) or 0 (False).

    Operator Name Example Result

    < Less than 10 < 12 1 (True)

    > Greater than 13 > 13 0 (False)

    = 12 1 (True)== Equal to 13 == 12 0 (False)

    != Not equal to 13 != 12 1 (True)

  • 7/27/2019 Introduction to Algorithms and Flowchart

    22/48

    ECT, Department of Engineering22

    3.4. Logical operators

    Logical operators are used commonly in C language for combining multiple relational

    expressions.

    Following are the Logical operators:

    Operator Name Rules Example Result

    && AND

    1 && 1 = 1

    10 >= 8 && 5 < 5 01 && 0 = 0

    0 && 1 = 0

    0 && 0 = 0

    || OR

    1 || 1 = 1

    10 >= 8 || 5 < 5 11 || 0 = 1

    0 || 1 = 1

    0 || 0 = 0

    ! NOT !1 = 0 !(10 >= 10) 0!0 = 1

    3.5. Increment (++) & decrement (--) operators

    These are special operators used in C language.

    Operator Name Usage Example Result

    ++ Increment (Add 1 in currentvalue of variable)

    Postfix int X = 2, Y;Y = X++;

    Value of X at theend will be 3 and

    Y will be 2.Prefix int X = 2, Y;

    Y = ++X;Value of X at theend will be 3 andY will be 3.

    - -Decrement (Subtract 1 from

    current value of variable)

    Postfix int X = 2, Y;Y = X--;

    Value of X at theend will be 1 andY will be 2.

    Prefix int X = 2, Y;Y = --X;

    Value of X at theend will be 1 andY will be 1.

    They operators are commonly used in loops.

  • 7/27/2019 Introduction to Algorithms and Flowchart

    23/48

    ECT, Department of Engineering23

    Exercise Questions

    1. Write the result of following expressions.

    S. No Expression Result

    1 2 + 32 2 * 3 + 4

    3 5 + (6 + 4) / 2

    4 10 % 3 * 4 + 5 * 2

    5 10 % 2

    6 27 % 7

    7 5 / 4

    8 7.0 / 4.0

    9 7.0 / 4

    10 3+(++2)

    11 int A = 11;

    X = ++A % 3;

    A = ________

    X = ________12 int A = 11;

    X = A++ % 3;A = ________X = ________

    13 int A = 7;X = -A++;

    A = ________X = ________

  • 7/27/2019 Introduction to Algorithms and Flowchart

    24/48

    ECT, Department of Engineering24

    Chapter 4:

    Decision Making and Branching

  • 7/27/2019 Introduction to Algorithms and Flowchart

    25/48

    ECT, Department of Engineering25

    Always the programs dont execute in a sequential flow. Some instructions are depending on

    certain condition to happen for execution. Due to Decision making the normal flow of execution

    of the program can be controlled.

    C language contains following decision making statements:

    1. if statement

    2. if else statement

    3. else if statement

    4. switch statement

    As these statements are used to control the flow of execution, so they are also known as control

    structures/statements.

    In all these structures we use Relational operators to compare the operands and Logical operatorsare used for combining multiple conditions.

    4.1. if statement

    if statement is used to execute certain instructions on the result of the condition i.e. if the result

    of condition will be true, related instructions will execute otherwise not.

    Syntax:

    if (condition)

    { If the number of statements in body is only 1 than curly

    Statement(s) bracket is optional. For multiple instructions in body, its

    } Compulsory.

    Example1:

    #include

    void main()

    {

    int number;

    printf("Please Enter a Number:");

    scanf("%d",&number);if(number > 0)

    printf("Number is Positive" );

    }

    In all these examples we saw we cant mention any instruction for execution if condition returns

    false.

    Example 2:

    #include

    void main()

    {

    int number;

    printf("Please Enter a Number:");

    scanf("%d",&number);if(number%2 == 0)

    printf("Number is Even" );

    }

    Example 3:

    #include

    void main()

    {

    int marks;

    printf("Please Enter C marks:");

    scanf("%d",&marks);if(marks > 60)

    printf("You are Pass" );

    }

  • 7/27/2019 Introduction to Algorithms and Flowchart

    26/48

    ECT, Department of Engineering26

    4.2. if else statement

    As in above if statement example we saw that if condition returns false than we cant mention any

    instruction to execute, this problem is handled in if else statement where we can mention

    instruction on both results of condition i.e. for True as well as for False.

    Syntax:

    if (condition)

    { If the number of instructions in body is only 1 than curly

    Statement(s) bracket is optional. For multiple instructions in body, its

    } Compulsory.

    else

    { If the number of instructions in body is only 1 than curly

    Statement(s) bracket is optional. For multiple instructions in body, its} Compulsory.

    Example 1:

    /* Find Maximum of 2 numbers using if else

    #include

    void main()

    {

    int n1,n2;

    printf("Input 2 numbers: ");

    scanf("%d%d ",&n1,&n2);

    if(n1>n2)

    printf("Maximum = %d",n1);

    else

    printf("Maximum = %d",n2);

    }

    Example2:

    #include

    void main()

    {

    int marks;printf("Please Enter C marks:");

    scanf("%d",&marks);

    if(marks > 60)

    printf("You are Pass" );

    else

    printf("You are Fail" );

    }

    Example 3:

    /* Program to find Maximum of 3 numbers

    using if and if else statements*/

    #include

    void main()

    {

    int n1,n2,n3;

    printf("Input 3 numbers: ");

    scanf("%d%d%d",&n1,&n2,&n3);

    if(n1>n2)

    if(n1>n3)

    printf("Maximum = %d",n1);

    else

    printf("Maximum = %d",n3);

    else

    if(n2>n3)

    printf("Maximum = %d",n2);

    else

    printf("Maximum = %d",n3);

    }

  • 7/27/2019 Introduction to Algorithms and Flowchart

    27/48

    ECT, Department of Engineering27

    4.3. else if statement:

    In both if and if else we can check only 1 condition, for multiple conditions we need to use the

    nesting of if and/or if else. But else if is another good alternative for checking multiple

    conditions and based on the result of each condition specific instructions can be executed.

    Syntax:

    if (condition){

    Statement(s)}else if (condition){

    Statement(s)}

    .

    .

    .else{

    Statement(s)}

    Example 1:

    #include

    void main(){

    int number;

    printf("\n Please Enter a number : ");

    scanf("%d",&number);

    if(number > 0)

    printf("\n You entered a Positive number.");

    else if(number < 0)

    printf("\n You entered a Negative number.");

    else

    printf("\n You entered 0.");}

    Example 2:#include void main(){

    int day;

    printf("\n Please day number (0 to 7) : ");scanf("%d",&day);if(day= =1)printf("\Saturday");else if(day= =2)printf("Sunday");else if(day= =3)printf("Monday");else if(day= =4)printf("Tuesday");else if(day= =5)

    printf("Wednesday");else if(day= =6)printf("Thursday");else if(day= =7)printf("Friday");elseprintf("You entered Wrong number");

  • 7/27/2019 Introduction to Algorithms and Flowchart

    28/48

    ECT, Department of Engineering28

    4.4. switch Statement:

    The switch statement is also used when we have to check multiple conditions like else if. But it

    majorly has certain limitations.

    1. Only Equality can be checked in switch statement and it is automatically done, no need towrite a relational expression using == operator.

    2. It can only be used with int and char data types only.

    Syntax:

    switch (variable/expression){case value-1:

    block of statements;break;

    case value-2:block of statements;break;

    .

    .

    .default: default and its block of statements are optional. It is like else

    block of statements; in else if statement.}

    Example 1:#includevoid main(){

    int day;printf("\n Please day number (0 to 7) : ");scanf("%d",&day);switch(day){

    case 1:printf("\Saturday");

    break;case 2:

    printf("Sunday");break;

    case 3:printf("Monday");break;

    case 4:printf("Tuesday");break;

    case 5:printf("Wednesday");break;

    case 6:printf("Thursday");break;

    case 7:printf("Friday");

    break;default:

    printf("You entered Wrongnumber");

    }}

  • 7/27/2019 Introduction to Algorithms and Flowchart

    29/48

    ECT, Department of Engineering29

    Example 2:/ *An Arithmetic Calculator Program*/

    #includevoid main()

    { char operator;int n1,n2,result;printf( "Welcome to my Calculator");printf ("\nEnter + for Addition");printf("\nEnterfor Subtraction");printf ("\nEnter * for Multiplication");printf("\nEnter / for Division");printf ("\nEnter % for Modulus");printf("\nEnter first number : ");scanf("%d",&n1);

    printf("Enter Second number: ");scanf("%d",&n2);flushall(); /* This function is to clear buffer stream before input of a character */printf ("Enter the Operator: ");scanf("%c",&operator);switch(operator){

    case '+':result = n1+n2;printf("\n \nThe addition of %d and %d gives %d",n1,n2,result); break;

    case '-':result = n1-n2;printf("\n \nThe subtraction of %d and %d gives %d",n1,n2,result); break;

    case '*':result = n1*n2;printf("\n\nThe multiplication of %d and %d gives %d",n1,n2,result);break;

    case '/':result=n1/n2;printf("\n \nThe division of %d and %d gives %d",n1,n2,result);break;

    case '%':result = n1%n2;printf("\n \nThe modulo of %d and %d gives %d",n1,n2,result);break;

    default:printf("\nInvalid Operator entered. ");break;

    }printf("\nThanks for using my calculator... ");

    }

  • 7/27/2019 Introduction to Algorithms and Flowchart

    30/48

    ECT, Department of Engineering30

    Exercise Questions

    1. Write a program that determines the number of digits in a number:

    Enter a number: 374

    The number 374 has 3 digits

    You may assume that the number has no more than four digits. Hint: use if statements to test the

    number. For example, if the number is between 0 and 9, it has one digit. If the number is

    between 10 and 99, it has two digits.

    2. Write a program that asks the user for a 24-hour time, then displays the time in 12-hour

    form:

    Enter a 24- hour time: 21:11

    Equivalent 12-hour time: 9:11 PM

    3. Write a program that asks the user to enter a wind velocity (in knots), then display the

    corresponding description.

    Velocity (knots) Description

    < 1 Calm

    13 Light air427 Breeze

    2047 Gale

    4863 Storm

    > 63 Hurricane

    4. Write a program using Nested if else statement to accept the mark of a student in a course

    and display the letter grade and the grade point. The following table shows the relationship

    between the mark, letter grade and the grade point.

    Marks Grade Grade points

    90-100 A 4.0

    80-89 B 3.0

    70-79 C 2.0

    60-69 D 1.0

    0- 60 F 0.0

  • 7/27/2019 Introduction to Algorithms and Flowchart

    31/48

    ECT, Department of Engineering31

    Chapter 5:

    Control Loops

  • 7/27/2019 Introduction to Algorithms and Flowchart

    32/48

    ECT, Department of Engineering32

    Whenever we need to execute some instructions repeatedly, we can do it using the looping

    statements available in C programming language.

    There are 3 types of Loop constructs available in C language.

    1. while loop It keeps on repeating instructions until the condition returnsfalse.It is useful when we dontknow in advance how many times theloop will be executed.

    2. do while loop It also executes the instructions until condition returns false butcondition is checked after the loop body is executed.This ensures that the loop body runs at least once.

    3. for loop It is commonly used in those problems where the loop will beexecuted for fixed number of times already known toprogrammer.

    5.1. while loop

    Syntax:

    while (condition)

    {

    body of the loop;

    }

    First condition is checked and if it is true, then the body of the loop is executed. After completing

    the execution of body once, again condition will be checked; if it is still true then again body will

    be executed. This process will continue until condition doesnt get false.

    Example 1

    #include

    void main()

    {

    int counter=1;while(counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    33/48

    ECT, Department of Engineering33

    Example 2

    /*A program to print a sequence of first

    n natural numbers */

    #include

    void main(){

    int counter, number;

    printf("Enter the Number");

    scanf("%d",&number);

    counter =0;

    while (counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    34/48

    ECT, Department of Engineering34

    5.2. do while Loop

    This loop executes the body of loop after the test condition is checked.

    Syntax:

    do

    {

    body of the loop;

    }while (test-condition);

    Example 1

    /*Print the Odd numbers from 1 - 50*/

    # includevoid main()

    {

    int counter = 1;

    do

    {

    If(counter % 2 != 0)

    printf("%d\t", counter);

    counter++;

    }while (counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    35/48

    ECT, Department of Engineering35

    Example 3:/ *A program to demonstrate all the arithmetic operations */#includevoid main(){

    char choice, operation;int n1,n2,result;do{printf( "Welcome to my Calculator");printf ("\nEnter + for Addition\nEnterfor Subtraction");printf ("\nEnter * for Multiplication");printf("\nEnter / for Division");printf ("\nEnter %% for Modulus");printf("\nEnter first number : ");scanf("%d",&n1);printf("Enter Second number: ");

    scanf("%d",&n2);flushall(); /* This function is to clear buffer stream before input of a character */printf ("Enter the Operator: ");scanf("%c",&operation);switch(operation){

    case '+':result = n1+n2;printf("\n \nThe addition of %d and %d gives %d",n1,n2,result); break;

    case '-':result = n1-n2;printf("\nThe subtraction of %d and %d gives %d",n1,n2,result); break;

    case '*':result = n1*n2;printf("\nThe multiplication of %d and %d gives %d",n1,n2,result);break;

    case '/':result=n1/n2;printf("\nThe division of %d and %d gives %d",n1,n2,result);break;

    case '%':result = n1%n2;printf("\nThe modulo of %d and %d gives %d",n1,n2,result);break;

    default:printf("\nInvalid Operator entered. ");break;

    }flushall();printf("\nEnter Y/y to continue and N/n for Exit: ");scanf("%c", &choice);

    } while(choice != 'N' && choice!= 'n');}

  • 7/27/2019 Introduction to Algorithms and Flowchart

    36/48

    ECT, Department of Engineering36

    5.3. for Loop

    This loop is best in the scenario where the number of iterations of the loop is known before the

    loop is entered.

    Syntax:

    for (initialization of counter ; condition ; counter increment/decrement)

    {

    /*body of the loop*/

    }

    The execution of the for loop is done on following steps:

    1. Initialization of the counter variable.

    2. The condition is checked if it is true, the body of the loop is executed; otherwise the loop

    is terminated.

    3. After completing 1 iteration, the increment/decrement will be done, condition will be

    checked, if true than same process will be repeated otherwise loop will be terminated.

    Example l

    /* program to print n numbers and their squares */

    #include

    void main()

    {

    int counter, number, square;

    printf(Enter the value till where you want to print Square:");

    scanf("%d", &number);

    for(counter=0;counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    37/48

    ECT, Department of Engineering37

    Example 2

    Print Even numbers from 1 to 100 using for loop

    #include

    void main()

    {

    int counter;

    for(counter =1; counter

  • 7/27/2019 Introduction to Algorithms and Flowchart

    38/48

    ECT, Department of Engineering38

    Example 3

    /*Programs to print

    *

    **

    *******

    *****

    ******

    */

    #include

    void main()

    {

    int counter1, counter2;

    for(counter1=1; counter1

  • 7/27/2019 Introduction to Algorithms and Flowchart

    39/48

    ECT, Department of Engineering39

    Exercise Questions

    1. Write a program using for loop to calculate product of numbers from 110.

    2. Write programs to print the following designs.

    a. ****** b. c.***********************************

    1

    12

    123

    1234

    12345

    1234

    123

    12

    1

  • 7/27/2019 Introduction to Algorithms and Flowchart

    40/48

    ECT, Department of Engineering40

    Chapter 6:

    Arrays

  • 7/27/2019 Introduction to Algorithms and Flowchart

    41/48

    ECT, Department of Engineering41

    Array is a data structure which is used to store multiple data elements of the same data type.

    Following are the important characteristics of Array.

    1. An Array is of a single data type.

    2. Array is always fixed sized.

    3. Array is always allocated sequential memory.

    Arrays are very beneficial to store multiple data elements of the same type, otherwise we have to

    make separate variable for each data and it becomes very difficult to handle so many variables.

    6.1. One dimensional Array

    Syntax for declaring a 1-dimensional Array:

    Data type name of Array[size];

    Examples:

    int numbers[5];

    float values[5];

    char name[35]; Character Arrays are commonly called Strings.

    The elements in the array will be referred as:

    numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]

    we can assign value to any element of array as:

    numbers[0] = 1;

    numbers[1] = 2;

    If the values are already known to be put in array than we can initialize the array as under:

    Int numbers[5] = {1,2,3,4,5};

    Int numbers[ ] = {1,2,3,4,5};

    If values are not known at the time of declaration of array than we can input elements of array

    using a loop, which makes the accessibility of array elements very easy, no matter whatever is

    the size of the array.

    numbers[0]

    numbers[1]

    numbers[2]

    numbers[3]

    numbers[4]

  • 7/27/2019 Introduction to Algorithms and Flowchart

    42/48

    ECT, Department of Engineering42

    Without Arrays Example 1 - With Array

    /*program to enter 5 numbers and then print*/#includevoid main(){

    int numbers[5], index;for(index =0;index < 5; index++){

    scanf("%d",& numbers[index]);}printf("\nYour Entered numbers are : ");for(index =0;index

  • 7/27/2019 Introduction to Algorithms and Flowchart

    43/48

    ECT, Department of Engineering43

    6.2. Two Dimensional Arrays

    One dimensional array can store a linear list of values. If we have to store a table of values than

    we require a 2-dimensional array.

    Syntax for declaring a 2-dimensional array

    Data type name of array [row size][column size];

    Examples:

    int matrix[2][2];

    float quiz_marks[30][2];

    Example 1

    /*Input values in Two, 2-dimensional Arrays (Matrix) of size [3][3], add them & print resultantmatrix.*/#includevoid main(){

    int matrix1[3][3], matrix2[3][3],sum[3][3], row, col;printf("Input elements of the first matrix : ");for(row=0;row

  • 7/27/2019 Introduction to Algorithms and Flowchart

    44/48

    ECT, Department of Engineering44

    Exercise Questions

    1. Write a program to accept 4 integers from the user, store in an array & display the

    contents of the array.

    2. Write a program to store 7 integers into array a, search any stored number from array &

    find the position of this number in array.

    3. Write a program to store 3 quiz marks of 5 students, and then calculate the average quiz

    marks of each student store it in another 1-dimensional array and display it.

  • 7/27/2019 Introduction to Algorithms and Flowchart

    45/48

    ECT, Department of Engineering45

    Chapter 7:

    Functions

  • 7/27/2019 Introduction to Algorithms and Flowchart

    46/48

    ECT, Department of Engineering46

    When the size of program gets big and in same program so many different operations we are

    doing than it becomes difficult to track, understand and debug the program. So we need to adopt

    some modular technique, in which we can divide our program into multiple segments.

    C language provides us a technique for this purpose called functions.

    7.1. Function:

    A Function is a block of statements that perform a particular task and it can be called as many

    numbers of times as required without repeating the complete code.

    7.2. Advantage of Using Function:

    1. Program can be divided into small parts that are easy to understand, debug and modify.

    2. Repetition of code can be avoided. Function can be written once and called many times.

    3. Functions are reusable. Function can be used in many programs.

    In C language functions are of Two types:

    1. Built-in functions / Library functions:

    These functions are ready made and we can directly use them. Example are printf(),

    scanf(), sqrt, strcpy, etc.

    2. User defined functions:

    These functions are written by programmers for their own usage in their programs.

    7.3. How to write a User defined function:

    A User defined function is consisting of two parts.

    1. Definition of function (should be written before main( ) function)

    Syntax of function definition: Example

    Return_type function_name (list of Arguments){

    Body of function (statements)return statement;

    }

    int addition (int n1, int n2){

    int sum;sum = n1 + n2;return(sum);

    }

    2. Calling of function (inside the main or any other user defined function)

    Syntax for Calling function: Example:

    function_name(list of variables as arguments); sum = addition(23,45); orprintf(Sum = %d, addition(23,45)); orint num1 = 23, num2 = 45, sum;sum = addition (num1, num2); orprintf(Sum = %d,addition(num1,num2);

  • 7/27/2019 Introduction to Algorithms and Flowchart

    47/48

    ECT, Department of Engineering47

    Examples:

    Example 1: Example 2:/*Input 2 numbers from User and add themusing a function.*/

    #includeint addition(int n1,int n2){

    int sum;sum=n1+n2;return sum;

    }void main(){

    int num1,num2,sum;printf("Input two numbers: ");

    scanf("%d%d",&num1, &num2);sum = addition(num1,num2);printf("Addition result of %d and %d =

    %d", num1, num2, sum);}

    /*Input a number from User and display itssquare using a function.*/

    #includeint square(int num){int result;result = num*num;return result;}void main(){int number, sqr;

    printf("Input a number for finding its Square:

    ");scanf("%d",&number);sqr = square(number);printf("Square of %d = %d", number, sqr);}

  • 7/27/2019 Introduction to Algorithms and Flowchart

    48/48

    Exercise Questions

    1. Write a program using a function to add, subtract and multiply two numbers.

    2. Write a C program using a function to find factorial of given number.

    3. Write a program to accept two numbers and display the average using a function.

    4. Write a menu driven C program to make calculator for functions +,-, /,* using

    functions.