You are on page 1of 48

Higher College of Technology Department of Engineering Electrical, Computer and Telecommunications Section

Course Title: Course Code: Level:

Computer Programming for Engineering


EECP1290 Diploma (First year)

ECT, Department of Engineering

Chapter 1: Introduction to Algorithms and Flowchart

ECT, Department of Engineering

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. It should be valid for all problems of the same type.

2)

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. Flowcharts diagrammatic representation showing the control flow of the algorithm.

2)

ECT, Department of Engineering

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
Start or End of the algorithm

Shape

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 The direction of flow of flowchart should be from left to right or top to bottom. Only one flow line should Enter/Exit from a process. or

b. c.

ECT, Department of Engineering

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.
No Yes

e.

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

f. g.

Multiple flows can be joined to 1 flow using Connector symbol 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. 2. 3. 4. 5. input x input y sum = x + y average = sum /2 output average
END average = sum/2 Output average Input x and y sum = x + y START

ECT, Department of Engineering

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: No 1. 2. 3. 4. 5. Input N1,N2 if N1 > N2 go to step 3,otherwise go to step 4
Max=N2 N1>N2 Input N1 and N2 START

Yes

Max=N1

Max=N1, go to step 5 Max=N2 Output Max


Output max

END

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 <= 50 3. Output Counter 4. Counter = Counter+2
START

Counter = 2 Counter=Counter+2

Counter <=50

Yes

Output Counter

No
END

ECT, Department of Engineering

Exercise Problems
1. Write algorithms to find the area of a rectangle, triangle and square and draw the flowcharts for each. Draw a flowchart to calculate displacement, S = Vit + at
2

2. 3. 4.

Draw flowchart to find the sum and average of three numbers N1, N2, N3. Draw flowchart to solve the following problem: IF X > 0 IF X <= 0 S = 3X+2 S = 3X-2

5.

Draw a flowchart to Input Basic Salary, Allowances and Deductions. Do the required calculations and display the total take home Salary. Draw a flowchart to Input Item unit Price, discount and Quantity. After performing required calculations, Output the Amount to be paid. Draw a flowchart to Input three numbers and display the minimum. Draw a flowchart to Output all the even numbers from x to y, where x and y are variables. Draw a flowchart to take input of the year from the user and find out whether it is a Leap year or not. (Hint: any year divided by 4 fully is a leap year e.g. 2008 % 4 = 0) Draw a flowchart to take input temperature of Muscat from User and then output the result according to following criteria: Temperature >= 30 Temperature >= 25 and Temperature < 30 Temperature < 25 Hot Moderate Pleasant

6.

7. 8. 9.

10.

ECT, Department of Engineering

Chapter 2 Introduction to C Programming Language

ECT, Department of Engineering

Programming in any language requires learning 2 major parameters. 1. Syntax of Programming language. Grammar or rules of language for writing instructions 2. Semantics Logics / 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 for use 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 a = 60 Displacement = Vi * t + 0.5*a*(t*t) Area = 2 * 3.14 * r Instructions Data

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.

ECT, Department of Engineering

2. 3. 4. 5.

Develop algorithm and draw Flowchart Write the program in a computer language i.e. C using some IDE e.g. Turbo C ++. Test and debug the program. 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 C language 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 <stdio.h> void main () { /* Create variables Input instructions Processing instructions Output instructions */ } 1. #include <stdio.h> 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

ECT, Department of Engineering

10

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

ECT, Department of Engineering

11

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 char int float double

Type of data stored


Store 1 letter/character, e.g. A, H, c, 2 etc whole numbers, e.g. 1 , 23, 1230 etc floating point numbers (upto 7 digit precision) e.g. 3.12, 5.2 etc Bigger floating point numbers with more precision (15 digit)

Size in memory (Bytes)


1 byte / 8 bits 2 bytes / 16 bits 4 bytes / 32 bits 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 ;

ECT, Department of Engineering

12

Variable Naming:
For naming the variables we must need to follow certain rules including: 1. 2. The variable names in C can only be started with a character or an underscore ( _ ). 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. 4. 5. Space is not allowed in the variable names. Special characters / symbols e.g. &, @, $ etc are not allowed in variable names. 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 Value1 1value value_1 Value#1 _1value Long long Return return area(a) id-number _id Status

ECT, Department of Engineering

13

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. 2. Which function we have to use and how. The function we are using is in which Library.

Now for Input and Output we are using: Requirement Output/Display on Monitor Input from Keyboard Function Name Printf scanf Library / Header file stdio.h 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 %c %d %f %lf Data Type char int float double

ECT, Department of Engineering

14

Examples:
1. printf ("I am a student of HCT in Engineering department"); //String output Float gpa = 3.2; 2. 3. printf ("%f",gpa); printf ("My GPA in Programming = %f", gpa);

Example 1
Write a program that add two integers 30 and10 ?
Sum result of 30 and 10 = 40

#include<stdio.h> 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
100 -- 3.14 166.3456 -- A #include<stdio.h> void 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

ECT, Department of Engineering

15

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 \n \t Purpose For New line For Tab (Creating space)

Example 1
# include <stdio.h> void main(){ printf(" I am studying in Diploma (First Year)\n " ); printf(" in Engineering department of\tHCT"); }

I am studying in Diploma (First Year) in Engineering department of HCT

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);

ECT, Department of Engineering

16

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

# include<stdio.h> 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

ECT, Department of Engineering

17

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. b. c. d. 2. How many and which type of variables are required for above program? Write a Valid variable name for each variable which you will use in this program. Do we need to use scanf function in this program and where? Do we need to use printf function in this program and where?

Write programs to find the area of: a. b. c. d. Circle Triangle Square Rectangle

3.

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

ECT, Department of Engineering

18

Chapter 3 Operators and Expressions

ECT, Department of Engineering

19

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. 2. 3. 4. 5. Assignment operators Arithmetic operators Relational operators Logical operators 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; y = x * 2; z = y; /* 6.5 will be assigned to the variable named x */ /* value of x will be multiplied with 2 and result will be put into variable 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

ECT, Department of Engineering

20

Arithmetic Expressions Algebraic expression 3x2+2x+1 Vit+1/2at2 r2 C language expression 3*x*x+2*x+1 Vi*t+0.5*a*t*t 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 10 + 10 * 5 5*3+6/3 4/2*2+3*2+1 10-4+2 11%3*2+3*0 Result 60 17 11 8 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 Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to Example 10 < 12 13 > 13 12 <= 12 12 >= 12 13 == 12 13 != 12 Result 1 (True) 0 (False) 1 (True) 1 (True) 0 (False) 1 (True)

ECT, Department of Engineering

21

3.4. Logical operators


Logical operators are used commonly in C language for combining multiple relational expressions. Following are the Logical operators: Operator Name && AND Rules 1 && 1 = 1 1 && 0 = 0 0 && 1 = 0 0 && 0 = 0 1 || 1 = 1 1 || 0 = 1 0 || 1 = 1 0 || 0 = 0 !1 = 0 !0 = 1 Example 10 >= 8 && 5 < 5 Result 0

||

OR

10 >= 8 || 5 < 5

NOT

!(10 >= 10)

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


These are special operators used in C language. Operator Name Usage Postfix Example int X = 2, Y; Y = X++; int X = 2, Y; Y = ++X; int X = 2, Y; Y = X--; int X = 2, Y; Y = --X; Result Value of X at the end will be 3 and Y will be 2. Value of X at the end will be 3 and Y will be 3. Value of X at the end will be 1 and Y will be 2. Value of X at the end will be 1 and Y will be 1.

++

Increment (Add 1 in current value of variable)

Prefix

Postfix -Decrement (Subtract 1 from current value of variable)

Prefix

They operators are commonly used in loops.

ECT, Department of Engineering

22

Exercise Questions
1. Write the result of following expressions. S. No 1 2 3 4 5 6 7 8 9 10 11 12 13 Expression 2+3 2*3+4 5 + (6 + 4) / 2 10 % 3 * 4 + 5 * 2 10 % 2 27 % 7 5/4 7.0 / 4.0 7.0 / 4 3+(++2) int A = 11; X = ++A % 3; int A = 11; X = A++ % 3; int A = 7; X = -A++; Result

A = ________ X = ________ A = ________ X = ________ A = ________ X = ________

ECT, Department of Engineering

23

Chapter 4: Decision Making and Branching

ECT, Department of Engineering

24

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. 2. 3. 4. if statement if else statement else if statement 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 operators are 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) { Statement(s) }
Example1: #include <stdio.h> void main() { int number; printf("Please Enter a Number:"); scanf("%d",&number); if(number > 0) printf("Number is Positive" ); }

If the number of statements in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory.
Example 2: #include <stdio.h> void main() { int number; printf("Please Enter a Number:"); scanf("%d",&number); if(number%2 == 0) printf("Number is Even" ); } Example 3: #include <stdio.h> void main() { int marks; printf("Please Enter C marks:"); scanf("%d",&marks); if(marks > 60) printf("You are Pass" ); }

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

ECT, Department of Engineering

25

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) { Statement(s) } else { Statement(s) }
Example 1: /* Find Maximum of 2 numbers using if else #include<stdio.h> 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); }

If the number of instructions in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory.

If the number of instructions in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory. Example 3: /* Program to find Maximum of 3 numbers using if and if else statements*/ #include<stdio.h> 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); }

Example2:
#include <stdio.h> void main() { int marks; printf("Please Enter C marks:"); scanf("%d",&marks); if(marks > 60) printf("You are Pass" ); else printf("You are Fail" ); }

ECT, Department of Engineering

26

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 2: #include <stdio.h> void main() Example 1: { #include <stdio.h> int day; void main() printf("\n Please day number (0 to 7) : "); { scanf("%d",&day); int number; if(day= =1) printf("\Saturday"); printf("\n Please Enter a number : "); else if(day= =2) scanf("%d",&number); printf("Sunday"); if(number > 0) else if(day= =3) printf("\n You entered a Positive number."); printf("Monday"); else if(number < 0) else if(day= =4) printf("\n You entered a Negative number."); printf("Tuesday"); else else if(day= =5) printf("Wednesday"); printf("\n You entered 0."); else if(day= =6) } printf("Thursday"); else if(day= =7) printf("Friday"); else printf("You entered Wrong number"); } }

ECT, Department of Engineering

27

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 to write a relational expression using == operator. It can only be used with int and char data types only.

2.

Syntax: switch (variable/expression) { case value-1: block of statements; break; case value-2: block of statements; break;

. . .
default: block of statements; } default and its block of statements are optional. It is like else in else if statement.

Example 1: #include<stdio.h> void 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 Wrong number"); } }

ECT, Department of Engineering

28

Example 2: / *An Arithmetic Calculator Program*/ #include<stdio.h> void main() { char operator; int n1,n2,result; printf( "Welcome to my Calculator"); printf ("\nEnter + for Addition"); printf("\nEnter for 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... "); }

ECT, Department of Engineering

29

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) <1 13 4 27 20 47 48 63 > 63 Description Calm Light air Breeze Gale Storm 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 90-100 80-89 70-79 60-69 0- 60 Grade A B C D F Grade points 4.0 3.0 2.0 1.0 0.0

ECT, Department of Engineering

30

Chapter 5: Control Loops

ECT, Department of Engineering

31

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 returns false. It is useful when we dont know in advance how many times the loop will be executed. It also executes the instructions until condition returns false but condition is checked after the loop body is executed. This ensures that the loop body runs at least once. It is commonly used in those problems where the loop will be executed for fixed number of times already known to programmer.

2.

do while loop

3.

for loop

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<stdio.h> void main() { int counter=1; while(counter <=5) { printf(%d\t, counter); counter ++; } }

ECT, Department of Engineering

32

Example 2 /*A program to print a sequence of first n natural numbers */ #include<stdio.h> void main() { int counter, number; printf("Enter the Number"); scanf("%d",&number); counter =0; while (counter <= number) { printf("%d \n", counter); counter++; } }

Example 3 / *Program to find the sum of the first 10 numbers (1+2+3+ +10) */ #include <stdio.h> void main() { int num,sum; num= 1; sum= 0; while (num <= 10) { sum =sum + num; num++; } printf("Sum of first 10 numbers=%d", sum); }

Example 4 / *Program to print Even numbers from 1 - 50 */ #include <stdio.h> void main() { int num = 1; while (num <= 50) { if(num%2 == 0) Printf("%d\t", num); num++; } }

ECT, Department of Engineering

33

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*/ # include<stdio.h> void main() { int counter = 1; do { If(counter % 2 != 0) printf("%d\t", counter); counter++; }while (counter <= 50); } Example 2 /* Prints digits of a number in reverse order */ #include <stdio.h> void main() { int number, digit; printf("Enter the number to be reversed: "); scanf("%d", &number); do { digit = number%10; printf("%d", digit); number=number/10; }while(number != 0); }

ECT, Department of Engineering

34

Example 3: / *A program to demonstrate all the arithmetic operations */ #include<stdio.h> void main() { char choice, operation; int n1,n2,result; do{ printf( "Welcome to my Calculator"); printf ("\nEnter + for Addition\nEnter for 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'); }

ECT, Department of Engineering

35

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 <stdio .h> void main() { int counter, number, square; printf(Enter the value till where you want to print Square:"); scanf("%d", &number); for(counter=0;counter<=number;counter++) { square = counter * counter; printf("Number = %d\tSquare = %d\n", number, square); } }

ECT, Department of Engineering

36

Example 2 Print Even numbers from 1 to 100 using for loop

Example 3

/*Print multiplication table of a number entered by User.*/ #include<stdio.h> #include <stdio .h> void main() { void main() int number, counter; { printf("Enter a number for printing Table: "); int counter; scanf("%d",&number); for(counter =1; counter <=100; counter ++) for( counter=1;counter<=10;counter++) if(counter%2==0) printf("%d x %d = %d\n", number, counter, printf("%d\t", counter); number*counter); } }

5.4. Nesting of Loops


Nesting of loop means one loop within another loop. For an example, two for loops can be nested as follows: for(counter1=1; counter1<5; counter1++) { for(counter2=1; counter2<5; counter2++) { /* Body of Inner loop */ } /* Statements in body of Outer loop*/ }

Example 1 /*Print multiplication tables from 2 to 5*/ #include<stdio.h> void main() { int counter1,counter2; for(counter1 =2; counter1<=5; counter1++) for(counter2=1; counter2<=10; counter2++) printf("%d x %d = %d\n", counter1, counter2, counter1 * counter2); }

ECT, Department of Engineering

37

Example 3 /*Programs to print * ** *** **** ***** ****** */ #include<stdio.h> void main() { int counter1, counter2; for(counter1=1; counter1<=6; counter1++) { for(counter2=1; counter2<= counter1; counter2++) printf("*"); printf("\n"); } }

ECT, Department of Engineering

38

Exercise Questions
1. 2. a. Write a program using for loop to calculate product of numbers from 1 10. Write programs to print the following designs. ****** ***** **** *** ** * ** *** **** ***** ****** b. c.
1 12 123 1234 12345 1234 123 12 1

ECT, Department of Engineering

39

Chapter 6: Arrays

ECT, Department of Engineering

40

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. 2. 3. An Array is of a single data type. Array is always fixed sized. 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 Examples: int numbers[5]; float values[5]; char name[35]; name of Array[size];
numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

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.

ECT, Department of Engineering

41

Without Arrays /*program to enter 5 numbers and then print*/ #include <stdio.h> void main() { int n1,n2,n3,n4,n5; printf("\nPlease Enter the five numbers : "); scanf("%d %d %d %d %d",&n1,&n2,&n3,&n4,&n5); printf("\nYour Entered numbers are : "); printf("\n%d %d %d %d %d",n1,n2,n3,n4,n5); }

Example 1 - With Array /*program to enter 5 numbers and then print*/ #include<stdio.h> void main() { int numbers[5], index; for(index =0;index < 5; index++) { scanf("%d",& numbers[index]); } printf("\nYour Entered numbers are : "); for(index =0;index<5;index++) { printf("%d\t", numbers[index]); } } Example 2 Example 3 /* Find sum of all the elements of an Array.*/ /*Find sum of all elements of array entered by #include<stdio.h> user*/ void main() #include<stdio.h> { void main() int numbers[5]={13,34,47,67, 102}; { int index, sum=0; int numbers[5]; for(index =0;index < 5; index++) int index, sum=0; sum = sum + numbers[index]; for(index =0; index < 5; index++) printf("\nSum = %d",sum); { } scanf("%d",& numbers[index]); sum = sum + numbers[index]; } printf("\nSum = %d",sum); } Example 4 Example 5: /* Input a number of multiple digits and print /*Find Largest value in Array*/ it in Reverse order.*/ #include<stdio.h> #include<stdio.h> void main() void main() { { int numbers[5], index, max ; int number[5], index; for(index=0;index<=4;index++) printf("Please Enter the 5 integers\t"); scanf("%d",&numbers[index]); for(index =0;index <5; index++) max=numbers[0]; scanf("%d",&number[index]); for(index=0;index<=4;index++) printf("The values in reverse order are\t"); if (max<numbers[index]) for(index =4;index >=0; index--) max=numbers[index]; printf("%d",number[index]); printf("Maximum Number in this array = %d } ",max); }

ECT, Department of Engineering

42

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 Examples: int matrix[2][2]; float quiz_marks[30][2]; name of array [row size][column size];
matrix[0][0] matrix[0][1] matrix[1][0] matrix[1][1] matrix[2][0] matrix[2][1]

Example 1 /*Input values in Two, 2-dimensional Arrays (Matrix) of size [3][3], add them & print resultant matrix.*/ #include<stdio.h> void main() { int matrix1[3][3], matrix2[3][3],sum[3][3], row, col; printf("Input elements of the first matrix : "); for(row=0;row<3;row++) for(col=0;col<3;col++) scanf("%d",& matrix1[row][col]); printf("Input elements of the second matrix : "); for(row=0;row<3;row++) for(col=0;col<3;col++) scanf("%d",& matrix2[row][col]); for(row=0;row<3;row++) for(col=0;col<3;col++) sum[row][col] = matrix1[row][col]+matrix2[row][col]; printf("Resultant matrix is : \n"); for(row=0;row<3;row++) { for(col=0;col<3;col++) printf("%d\t",sum[row][col]); printf("\n"); } }

ECT, Department of Engineering

43

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.

ECT, Department of Engineering

44

Chapter 7: Functions

ECT, Department of Engineering

45

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. 2. 3. Program can be divided into small parts that are easy to understand, debug and modify. Repetition of code can be avoided. Function can be written once and called many times. 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) Example int addition (int n1, int n2) { int sum; sum = n1 + n2; return(sum); }

Syntax of function definition: Return_type function_name (list of Arguments) { Body of function (statements) return statement; }

2.

Calling of function (inside the main or any other user defined function) Example: sum = addition(23,45); or printf(Sum = %d, addition(23,45)); or int num1 = 23, num2 = 45, sum; sum = addition (num1, num2); or printf(Sum = %d,addition(num1,num2);

Syntax for Calling function: function_name(list of variables as arguments);

ECT, Department of Engineering

46

Examples:
Example 1: /*Input 2 numbers from User and add them using a function.*/ #include<stdio.h> int 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); } Example 2: /*Input a number from User and display its square using a function.*/ #include<stdio.h> int 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); }

ECT, Department of Engineering

47

Exercise Questions

1. 2. 3. 4.

Write a program using a function to add, subtract and multiply two numbers. Write a C program using a function to find factorial of given number. Write a program to accept two numbers and display the average using a function. Write a menu driven C program to make calculator for functions +,-, /,* using functions.

ECT, Department of Engineering

48

You might also like