Você está na página 1de 45

Chapter 01

Introductory Concepts
PROGRAMMING LANGUAGE: Programming language: To sort a particular set of data, a computer is given an appropriate set of instructions. A complete set of logical instructions is called programming language. Types of programming language: There are 3 types of programming languages: Low level Mid level High level Low level language: Low level language is the set of actual instructions that the computer can understand without translator and execute directly. There are two types of low level languages: Machine language Assembly language Machine language: Machine languages generally consists of strings of numbers (o and 1) that instruct computer to perform their most elementary operations. This language does not need any translator. Assembly language: Assembly language is the symbolic representation of the actual machine instructions executed by the computer. This type of language needs translator. It is called assembler. Mid level language: It combines the facilities of low level and high level language. Through this language one can control the hardware at bit level and create system program. Example- C, Forth etc. High level language: This language allows programmers to write instructions that look almost like everyday English language and contains commonly used mathematical notations. These are machine dependent language. It needs translator. In a high level language, a single statement corresponds to several instructions of low level languages. A special advantages of this language is the availability of library programs. Example ALGOL, COBOL, FORTRAN, PASCAL, BASIC, C++, JAVA etc. Difference between machine and high level language Machine language 1. Use 0 & 1 i.e. binary or hex method to write instructions. 2. Computer directly understand this language. 3. It does not need any translator. 4. Program executed very fast. 5. Very complex, diligent and time consuming to write instructions. 6. Machine language written for one computer can not execute another computer High level language 1. Very similar to normal English language 2. Computer can not directly understand this language. 3. It needs translator. 4. Program executed slowly than machine language. 5. Easy, enjoying and time saving to write instructions. 6. Here is no such problem.

Compiler: Compiler translates a high level language into an object program. It translates the whole program at a time. Different high level language needs different compilers because a

particular compiler can convert a particular high level language into machine language. Compiler also links necessary routines with object program. Besides compiler detects errors in source code. Structure of a program: Every program has three parts. A full program is formed with the combination of these parts. Input Process Output General rules to write a program: 1. To identify the problem. 2. Required analysis 3. Algorithm design 4. Flow chart 5. Coding 6. Debugging and testing 7. Final implementation. Algorithm: Algorithm means to solve a problem step by step i.e. dividing a problem into several steps, solving these separately and in this way solve the whole problem. It should have the following four characteristics: It should be easy understood. Every step will be clear as computer can understand. Problem will be solved in limited steps. It will be applicable widely. Example: Write an algorithm for finding the roots of the equation ax2+bx+c=0. Step 1: Take input a, b & c. Step 2: If a=0 then one root. Print X1=-c/b and end. Otherwise go to the next step. Step 3: Calculate D=b2-4ac Step 4: Test the sign of D= b2 -4ac. According to sign follow any one of following; a) If D=0, roots are equal and real. Print X1, X2=

b and end. 2a b D b D b) If D>0, roots are unequal and real. Print X1 and end. & X2 2a 2a
c) If D<0, roots are imaginary. Print no real roots and end

Write An Algorithm To Find The Greatest Of Three Numbers. Ans.: The algorithm is as follows: 1. Step 1: Start the program. 2. Step 2: Read the numbers a, b & c. 3. Step 3: If a>b? Then follow one of the following. a) If a>c? Follow one of the forllowing I. If yes print a is big. II. If no go to next. b) If b>c? Follow one of the following I. If yes print b is big. II. If no go to next. III. Print c is big. 4. Step 4: End the program. FLOWCHART: How a program will work is shown by drawing picture in flowchart. A flowchart is some such pictures from which it is understood that to solve the problem how successively we have to move forward. A flowchart should have the following characteristics:

Application of Computer in Textiles (Sheet 1: C Programming Basic)

It will help to perform the object of program. It will help to determine the errors. It will help in changing and widening the program. It will help to code. It will make the complex problem into easy one.

Symbols of flowchart: 1. Start/ End 3. Input/ Output 2. Connector

4. Processing

5. Decision

6. Print or document

7. Direction of flow

8. preparatory symbol

Structure of a C program: # include<header file> main() { define variables; input functions such as scanf, getchar etc; processing by loops or defined functions or others; output functions such as printf, putchar etc. }

Important characteristics of program:


Integrity: This refers to the accuracy of the calculations. It is clear that if the calculations are not carried out correctly all other program enhancements will be meaningless. Thus the integrity of the calculations is an absolute necessity in any computer program. Clarity: It refers to the overall readability of the program with particular emphasis on its understanding logic. If a program is clearly written it is possible other programmers to follow the program logic. It will also be possible for the programmer himself to understand the logic after a long period of time.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

Simplicity: The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible. In order to maintain a relatively simple, straightforward program it is desirable to sacrifice a certain amount of computational efficiency. Efficiency: It is concerned with execution speed and efficient memory utilization. If a program written with efficient it will be executed quickly and output will be found quickly. Modularity: Many programs can be broken into a series of groups. It is good programming practice to implement each of these groups as a separate program module. The use of a modular programming structure enhances the accuracy and clarity of a program. Generality: A program should be as general as possible with reasonable limits. This can be obtained with very little additional programming efforts. What is source code and object code? Ans.: Source code is the instructions we write in programming language. Object code is the transformed instructions formed after the source code is translated by any translator program. What in general happens when a computer program is executed? A stored program can be executed at any time. This causes the following things to happen.1. A set of information called the input data will be entered into the compiler (from keyboard, floppy disc etc) and stored in a portion of the computers memory. 2. The input data will be processed to produce certain desired results, known as the out put data. 3. The output data, and perhaps some of the input data, will be printed onto a sheet of paper or displayed on a monitor (a television receiver specially designed to display computer output). This three step procedure can be repeated many times if desired, thus causing a large quantity of data to be processed in rapid sequence. Distinguish between data and information. Ans.: Data is the unit of information which is unsorted. When data is made into useable by sorting then it is called information. Describe the generations of programming languages. Ans.: The generations of programming languages are as follows: 1. First generation language e.g. machine language. 2. Second generation language e.g. assembly language. 3. Third generation language e.g. mid-level, high-level language. 4. Fourth generation language e.g. SQL/DS, RAPPORT, FOCUS, INTECET. FLOW DIAGRAM: Draw the flow diagram that compares two numbers either one is greater than another or small or both equals. Let variables are a, b& c

Application of Computer in Textiles (Sheet 1: C Programming Basic)

Flow chart to find the greatest the three numbers.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

Chapter 2

C Fundamentals
1. Identifiers & keywords. 2. Data type & Declarations. 3. Variable & Constant. 4. Expressions. 5. Statement. 1. Identifier: Identifiers are names that are given to various program elements such as variables, functions and arrays. Identifiers consist of letters and digits, in any order, except that the first character must character must be a letter. Both uppercase and lower case letters are permitted, though lower case letters are mostly favorable. An underscore ( _ ) is often used in the middle of an identifier. Valid identifiers x1 1x Invalid Reasons The 1st character must be a letter X123 xy x xy Illegal characters () Illegal characters (blank space) x_y _xy x-y 4th Illegal characters (-) The 1st character must be a letter. TABLE File management Excessive number must be a letter. Tax_rate Int It is keyword.

Keywords: There are certain reserved words, called keywords, that have standard, predefined meanings in C. These keywords can be used only for their intended purpose; They can not be used as programmer defined identifiers. The keywords are all lowercase. Standard keywords are: auto do int switch struct

Application of Computer in Textiles (Sheet 1: C Programming Basic)

break case char continue const default

double else enum goto for If

long register return signed short while

typedef union unsigned volatile void

static sizeof extern float

Constant: There are four basic types of constants in C i. Integer constants. ii. Floating point constants. iii. Character constants. iv. String constants. Variable: A variable is an identifier that is used to represent a single data item; i.e. a numerical quantity or a character constant. The data item must be assigned to the variable at some point in the program. The data item can then be accessed later in the program simply by referring to the variable name. Example: int a,b,c ; char d; Here a,b,c are integer variables and d are char type variable. Data type: Basic data types used in C program: C supports several different types of data, each of which may be represent differently within the computers memory. The basic data types are listed below: data types Int Char Float Double integer quantity. single character. floating point number double precision floating point description

Mention their bit widths & Ranges:


How could you extend the range of values of data types repress: The basic data types can be argument by the use of the data type qualifiers short, long, signed and unsigned. Example: integer quantities can be defined as short int, long int or unsigned int. Thus a short int may require less memory than an ordinary int or it may require the same amount of memory of memory as an ordinary int but it will never exceed an ordinary int in word

Application of Computer in Textiles (Sheet 1: C Programming Basic)

length. Similarly a long int may require the same amount of memory as an ordinary int or may require more memory but it will be never less than an ordinary int. If short int and int both have the same memory requirements(2bytes) then long int will generally have double the requirements(4bytes) Or if int and long int both have the same memory requirements(4 bytes)

Then short int will generally have the half memory requirements(2 bytes) Data types Int Char Float Double Bit width / Memory requirements 2 bytes 1 byte 4 byte 8 byte Ranges -32,768 to 32767 -128 to127 3.4 X 10 -38 to 3.4 X 1038 1.7 X 10-308 to 1.7 X 10308

Declarations: A declaration associates a group of variables with a specific data type. A declaration consist of a data type, followed by one or more variable names, ending with a semi colon. Example: A C program contains the following type declarations int a,b,c; float root1,root2; char flag, text[80]; Thus a, b and c are declared to be integer variables root1 and root2 are floating point variables and text is an 80 element, char type array. Expressions: An expression represents a single data item, such as a number or a character. The expression may consist of a single entity, such as a constant, a variable, an array element or a reference to a function. It may also consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions that are either true or false. Example: a+b expression with addition operator. x=y expression with assignment operator. c=a+b The value of the expression (a+b) is assigned to variable C. x<=y expression with relational operator. x==y The expression will have the value 1 (true) if the value of x is equal to the value of y otherwise the expression will have the value of (false). ++i expression with unary operator.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

Statements: A statement causes the computer to carry out some action. Example:

a 3; assignment typestatements. c a b;
++i; incrementing type statement. printf (Area =%f, area); This statement causes the printf function to be evaluated. ; null statement.

Types of statement: There are three different types of statements: i. Expression statements. ii. Compound statements. iii. Control statements. i. Expression statements: An expression / simple statement consists of an expression followed by a semi colon. Example: a=3; c=a+b; ++i; printf (Area = %f ,area); ; ii. Compound statements: A compound statement consists of several individual statements enclosed within a pair of brackets{}. The individual statements may themselves be expression statements, compound statements or control statements. Example: A typical compound statement is shown below: { pi = 3.141493; circumference = 2*pi*radius; area = pi*radius*radius; } Differ expression and compound statements: Expression consists of an expression but compound statement consists of several individual statements. Expression followed by semi colon but individual statements enclosed with in a pair of brackets {} but not end with a semicolon.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

iii.

Control statements: Control statements are used to create special program features, such as logical tests, loops and branches. Examples: The following control statements creates a conditional loop in which several action is satisfied; While (count<=n) {printf(x=); scanf(%f,&x); sum+=x; ++count;

Differ of compound statement from control statement: Compound statement consists of several individual statements Enclosed with a pair of braces. The enclosed statements individual statements may themselves be expression statemen, other compound statements or control statements. But control statement contain expression statements, or compound statements, including embedded compound statements. & control statements create special program feature such as logical tests, loops and branches. But control statements not enclosed with a pair of braces.

10 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Chapter 3

Operators & Expressions


Operators: Operators in C program is special symbol or word which directs the compiler to perform arithmetical or logical works, i.e. The characters which is used in C for special purpose such as mathematical, logical or relational purpose so this character is called operators. Most operators allow the individual operands to be expressions. Example: a+b; Here + is operator and a,b operand. Different categories of Operators: I. II. III. IV. V. VI. Arithmetic operator. Unary operator. Relational operator. Logical operator. Assignment operator. Conditional operator.

Operand: The data items that operands act upon are called operands.

a b a - b a and b are operand. a b


I. Arithmetic operator: There are five arithmetic operators in C. Operator + * / % Addition. Subtraction. Multiplication. Division Remainder after integer division. Purpose

Example: Suppose that a and b are integer variables whose values are 11 and 3, respectively. Several arithmetic expressions, Expression a+b a-b a*b Value 8 14 -33

Application of Computer in Textiles (Sheet 1: C Programming Basic)

11

a/b a%b

-3 2

If a had been assigned a value of -11 and b had been assigned 3. Then the value of a/b would still be -3 but a%b would be -2. Similarly, if a and b had both been assigned negative values (-11 and 3 respectively) Then a/b would be 3 and a%b would be -2. The condition a = ((a/b)*b)+(a%b) will be satisfied in each of the above cases. II. Unary operator: C includes a class of operators that act upon a single operand to produce a new value.

Operator Increment

Symbol ++

Operation Be caused its operand to be increased by 1. Causes its operand to be decreased by 1. Denotes negative value.

Decrement Unary minus

Examples: Suppose i be an integer variable that has been assigned a value of 5. The expression ++i which is equivalent i =i+1 causes the value of i to be increased to 6. Similarly the expression i which is equivalent to i=i-1 causes the value of i to be decreased to 4. III. Relational operator: The operators that are used to form logical expressions which represent condition that are either true or false. The result will be 1 if the condition is true and 0 if false. There are six relational operators in C. They are

Operator < <= > >= == != Less than

Meaning

Less than or equal to Greater than Greater than or equal Equal Not equal

Example: suppose that i, j and k are integer variables whose values are 1, 2 and 3 respectively. Expression i<j (i+j)>=k Interpretation True True Value 1 1

12 Application of Computer in Textiles (Sheet 1: C Programming Basic)

(j+k)>i+5 K!=3 J==2

False False True

0 0 1

IV.

Logical operator: The logical operators act upon operands that are themselves logical expression. i.e. the logical operator is used to perform logical purposes in C. The result of a logical operation will be true if either operands true or both operands are true. The result of a logical or expression will be false only if both operands are false

Operator && || !

Meaning and or not

Example: suppose i is an integer variable whose value is 7, f is a floating variable whose value is 5.5 and C is a char variable that represents the char w Expressions (i>=6)&&(c== w (i>=6)||(c==119) (f<11)&& (i>100) (c!= p || ((i+f)<=10) Interpretation True True False True Value 1 1 0 1

V.

Assignment operator: The operator which are used to form assignment expressions which assign the value of an expression to an identifier are known as assignment operator. The most commonly used assignment operator is = .This is written in the form Identifier = expression. Where identifier generally represents a variable and expression represents a constant, a variable or a more complex expression. Example: a=3 a=y delta =0.001 sum = a+b area = length *width.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

13

VI.

Conditional operator: The operators which is used in C to perform different condition purposes i.e. these are the operators which is used to form an expression in simple condition operations. Conditional operator: ? A conditional expression is written in the form Expression1? Expression2: expression3 Example: X=10 ,y=5 Z=(x>y)?x:5 Output: z=10 Operator precedence: The prominence of one operator to another operator in compiler is called precedence. If more operator is used in expression, the operation of operator is used in expression, the operation of operator depends on operator precedence. Operator category Operators */% -, ++, --, !, sizeof (type) <, <=, >, >=, ==, != &&, || ?: =, +=, -=, /=, %= LR RL LR LR RL RL Associativity

1. Arithmetic: 2. Unary: 3. relational: 4. logical: 5. Conditional 6. Assignment

Problem 01: A C program contain declaration int i=8,j=5; float x= 0.005,y= -0.01; write the output of following expression. 1. (i+j) = -(8+5) = -13 2. ++i = i+1 = 8+1 = 9 3. i++ = i+1 = 8+1 = 9 4. j = j-1 = 5-1 = 4 5. ++x = x+1 = 0.005 +1 = 1.005 6. y-=y-1 = -0.01 -1 = 1.01 7. (x>y) && (i>0) && (j<5) = (0.005> - 0.01)&&(8>0)&&(5<5) =(1 && 1) && 0 =1 && 0 =0 8. (x>y) && (i>0)!!(j<5) =(0.005> - 0.01) && (8>0) !!5<5

14 Application of Computer in Textiles (Sheet 1: C Programming Basic)

=1 &&1!!0 =1!!0 =1 9. (i>0) &&(j<5) =(8>0)&&(5<5) =1 && 0 =0 10. (i>0)!!(j<5) =1!!0 =1 11. 2*x+(y==0) =2* 0.005 + (-0.01 =0) =2*0.005 +0 =0.01 12. !(i<=j) = !(8<=5) =!0 =1 13. !(x>0) =!(0.005>0) =!1 =0 14. 2*((i/5)+4*(j-3))%(i+j-2)) =2*((8/5)+4*(4*(5-3)%(8+5-2)) =2*((1+(4+2))%11) =2*((1+8)%11)) =2*(9%11) =2*9 =18.Ans. 15. (i-3*j)%(c+2*d)/(x-y) =(8-3*5)%(c+2*d)/(0.005+0.01) =-7%2 = 0.015

16.

7+3>5&&!(4+7<9)||3<=4 =7+3>5&&1||3<4 =10>5&&1||3<=4

Application of Computer in Textiles (Sheet 1: C Programming Basic)

15

=1&&1||3<=4 =1&&1||1 =1&&1 =1

16 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Chapter 4

Data Input and output


Input and output function: 1. 2. 3. 4. 5. 6. getchar input function, a signle character. putchar output function, a single character. scanf input function, any value. printf output function, any value. gets input function, a line /string. puts output function, a line.

1.

Getchar function: Getchar function is used to receive a character from the key board. The getchar function is a part of the standard CI/0 library. It returns a single characters from a standard input device ( typically keyboard). In general terms, a function reference would be written as character variable = getchar(); header file of getchar function #include<stdio.h>

Example: A C program contains that c is a character type variable and 2nd statement causes a single character to be entered from the standard input device and then assigned to c. 2. putchar function: The C library function putchar is used to display a single character on the computer. This function is complementary to the character input function getchar and is a part of Ci/0 library. It transmits a single character to a standard output device. in general, the function would be written as: putchar (character variable):

Example: #include<stdio.h> main() { char x= A; putchar(A); putchar(B); } output: AB 3. scanf function: The C library function scanf is to enter input data into the computer from a standard input device (keyboard). this function can be used to enter any combination of numerical values, single characters,

Application of Computer in Textiles (Sheet 1: C Programming Basic)

17

and strings. The function returns the number of data items that have been entered successfully. In general terms, the scanf function is written as scanf (control string, arg1, arg2, .,argn); where control string refers to a string containing certain required formatting information and arg1, arg2, ..argn are arguments that represents the individual data items. Example: A typical application of a scanf function#include<stdio.h> main() { char item[20]; int partno; float cost; scanf (%s %d %f, &item,&partno,&cost); . } 4. printf function: The C library function printf is used to write output data from the computer onto a standard output device. This function can be used to output any combination of numerical values, single characters and strings. It is similar to the input function scanf. The printf function moves data from the computers memory to the standard output device. in general terms, the printf function is written as printf (control string, arg1, arg2,argn) where control string refers to a string that contains formatting information and arg1, arg2.argn are arguments that represent the individual output data items. Example: # include<stdio.h> main() { char item[20]; int partno; float cost; .. printf (%s %d %f , item, partno, cost);

18 Application of Computer in Textiles (Sheet 1: C Programming Basic)

} Function 1. getchar Purpose Enter a single character from the std input device. 2. putchar Send a single character from the std output device. 3. scanf Enter data items from the std input device 4. printf Send data items from the std output device 5. gets Enter a string from the std input device 6. puts Send a string from the std output device stdio.h stdio.h stdio.h stdio.h Header file

stdio.h

stdio.h

Purpose of header file? Is the use of header file absolutely necessary? The purpose of a header file is to supply necessary information to compiler about the library function . Yes, the use of header file is absolutely necessary. Because to write a program we have to use the library functions obviously. And as compiler cant understand these library functions without the header file must include them. Library function: C languages accompanied by a no. of Library functions that carry out various commonly used operations or calculations. These Library functions. are not a part of the languages part of the language purpose through all implementations of the language include them. For example, there are library functions that carry out standard input/output operationsabs(i) return the absolute value of i. cos(d) - - return the cosine of d. exp(d)raise e to the power. pow(d1,d2)return d1 raised to the d2 power. sqrt(d)return the square root of d.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

19

Chapter 5

Prepairing & running a complete C program


Common errors in C:
1. Syntactic error. 2. Execution error. 3. Logical error. 1. Syntactic error: The presence of syntactic error (or grammatical errors will become readily apparent once the Run command has been issued, since these errors will prevent the program from being compiled or executed successfully. Some particularly common errors of this type are improperly declared variables, a reference to an undeclared variables, incorrect punctuation, etc.

Most C compilers will generate diagnostic message when syntactic errors have been detected during the compilations process. These diagnostic messages are not always straightforward in their meaning and they may not correctly identify where the error occurred. 2. Execution error: This type of errors occurs during program execution after a successful compilation. Some common execution errors are a numerical errors are a numerical overflow or under flow. Division by zero attempting to compute the logarithm or the square root of a negative number etc. 3. Logical error: This type of errors occurs when the programmers supplied the computer instructions that are logically incorrect. Logical errors can be very difficult to detect since the output resulting from a logically incorrect. Logical errors can be very difficuolt to detect since the output resulting from a logically incorrect program may appear to be error - free. Debugging: Debugging are the methods or techniques used to find the location of logical errors within a program. Some more common debugging methods are given below: 1. Error isolation. 2. Tracing. 3. Watch values. 4. Break point. 5. Stepping.

20 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Chapter 6

Control Statements
Control statements: Control statements are used to create special program features such as logical tests, loops and branches. All control statements required that other statements be embedded with in them. Classification of control statements:

Control Statements

Branching If else, if, then while

Looping

Switch statement for

Do while

Branching : A C program may require that a logical test be carried out at same particular point within the program. One of several possible actions will then be carried out, depending on the outcome of the logical test. This is known as branching. Looping: A c program may required that a group of instructions be executed repeatedly, until some logical condition has been satisfied. This is known as looping. Branching : If else statement: The if else statement is used to carry out a logical test and then take one of two possible actions, depending on the outcome of the test. The else portion of the if else statement is optional, in its simplest general form, the statement can be written as: If (expression) statement In this form, the statement will be executed only if the expression has a non zero value of zero i.e. if expression is false, then the statement will be ignored. The general form of an if statement which includes the else clause is If the expression has a nonzero value i.e. if the expression is true then statement 1 will be executed. Other wise i.e. if expression is false, statement 2 will be executed.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

21

Example: if (x<=3) y=3*pow(x,2); Else y= 2*pow((x-3),2); printf (%f \n,balance); Here x <= 3 is the expression. If it is true then statement 1 i.e. y= 2*pow((x-3),2); will be executed. other wise that is, if the expression x<=3 is not true then statement 2 will be executed. Switch statement: purpose: Switch statement causes a particular group of statements to be chosen from several available groups. When more complex if else is present in programs, the use of switch statement is convenient instead of if else. Format: switch(expression) { case expression1: statement 1 statement 2 .. statement m break; case expression 2: statement 1 statement 2 .. statement m break; default: statement 1 statement 2 .. statement k }

22 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Utility: switch (choice = getchar()) { case R: printf (RED); break; case B: printf (BLUE); break; case W: printf (WHITE); break; default: printf (Error); } Looping: 1. The while statement: The while statement is used to carry out looping operations, in which a group of statements is executed repeatedly, until some condition has been satisfied. The general formula of the while statement is While (expression) statement The statement will be executed repeatedly, as long as the expression is true. This statement can be simple or compound though it is usually a compound statement. It must include some feature that eventually alters the value of expression, thus providing a stopping condition for the loop. Example: A program to display the consecutive digits 0, 1, 2, 3, ..9. #include<stdio.h> main() { int digit = 0; while(digit <=9) {printf( %d\n, digit); ++digit; } }

Application of Computer in Textiles (Sheet 1: C Programming Basic)

23

2. The do while statement: The do while statement is used to carryout looping operations, in which a group of statements is executed repeatedly until some logical condition has been satisfied. Some times it is described to have a loop with the test for continuation at the end of each pass. This can be accomplished by means of the do while statement. The general form of the do while statement is do (statement while ( expression): The statement will be executed repeatedly, as long as the value of expression is true. It must include some feature that eventually alters the value of expression so the looping action can terminate. The statement can be either simple or compound through most applications will requires. It to be a compound statement. Example: A program to display consecutive digits 0, 1, 2, 39 #include<stdio.h> main() { int digit = 0; do{ printf( %d\n, digit); } while(digit <=9); } Purpose of do while statement: Some times do while statement is desirable to have a loop with the test for continuation at the end of each pass. This can be accomplished by means of the do while statement. In some looping situations, when it is necessary to executed the statement at least once, there the do while statement used. How differs between do while statement & while statement: I. The test for continuation of while loop carried out at the beginning of each pass through the loop. The test for continuation of do while loop is carried is carried out at the end of each pass through the loop. II. The general form of while statement: while (expression) statement The general form of do while statement is do statement while (expression); III. In case of while statement, the statement may not be executed at all. incase of do while statement, the statement always be executed at once.

24 Application of Computer in Textiles (Sheet 1: C Programming Basic)

3. The for statement: The for statement is the third and perhaps the most commonly used looping statement in C. This The general form of the for statement is for (expression 1; expression 2; expression 3) statement where, expression 1 is used to initialize some parameters (index) that controls the looping action. Expression 2 represents a condition that must be true for the loop to continue execution and expression 3 is used to alter the value of the parameter initially assigned by expression 1. Typically expression 1 is an assignment expression; expression 2 is a logical expression or an assignment expression. when the for statement is executed, expression 2 is evaluated and tested at the beginning of each pass through the loop and expression 3 is evaluated at the end of each pass. Thus , the for statement is equivalent to expression 1; while (expression 2 ) statement expression 3; } Example: A program to display consecutive integer quantities such as 0, 1, 2,9 #include<stdio.h> main() { int digit for (digit = 0; digit<=9;++digit) printf(%d\n,digit); } How for statement differ from while statement: While statement are generally used when the number of passes is not known in advance but for loops are generally used when the number of passes is known advance.

Conditional Branching: When program is executed by the influence of conditional statement


it is called conditional program flow or branching. If the condition in conditional program is true, output is one type and other type in case of false. mainly four types of statement used in conditional branching. I. II. If statement. If else.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

25

III. IV. V. VI. VII.

Else if . Switch. For. While. Do while.

Unconditional branching: When program is executed by the influence of unconditional statement, it is called unconditional program flow. Some parts of program is rotated repeatedly or jump to a definite statement by the influence of unconditional statement. Unconditional branching statement used. I. II. continue goto.

Nested if else: It is possible to nest (i.e. embedded) if else statements, one within another. There are several forms that nested if else statements can take. The most general form of two layer nesting is : If e1 if e2 s1 else s2 else if e3 s3 else s4 where e1, e2, e3 are expressions and s1, s2, s3, s4 are statements. One complete if else statement will be executed if e1 is nonzero i.e. true and another complete if else statement will be executed if e1 is zero i.e. false. It is possible that s1, s2, s3 and s4 will contain other if else statements and would then have multilayer nesting some other forms of two layer nestingIf e1 s1 else if e2 s2 if e1 s1 else if e2 s2 else s3 if e1 if e2 s1 else s2 else s3 if e1 if e2 s1 elses s2 compare the use of the switch statement with the use of nested if else statement: I. Switch statement causes a particular group of statements to be chosen from several available groups.

26 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Switch

statement

is

used

incase

of

more

complex

if

else

statement.

in nested if else statement, to nest (embedded) if else statements, one another. II. The general form of the switch statement is switch (expression) statement. The general form of two layer nesting is if e1 if e2 s1 else s2 else if e3 s3 else s4 III. In practical sense, the switch statement may be thought of as an alternative to the use of nested if else statements. It can only replace those if else statements that test for equality. In such situations, the use of the switch statement is much more convenient. Break statement: The break statement is used to terminate loops or to exit from a switch. It can used within a for, while, do while or switch statement. The break statement is written simply as break; without any embedded expression or statements. The break statement causes a transfer of control out of the entire switch statement, to the first statement following the switch statement. If a break statement included in a while, do while, or for loop, then control will immediately transferred out of the loop when the break statement encountered. Example: switch(choice = toupper getchar()) { case R: printf(RED); break; case W: printf(WHITE); break; case B: printf(BLUE); break; default: printf(ERROR); break; } Continue statement: The continue statement is used to by pass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop.

Application of Computer in Textiles (Sheet 1: C Programming Basic)

27

The continue statement can be included within a while, a do while or a for statement. It is written simply as continue; without any embedded statements or expressions.

Program: Calculate the average of non negative numbers in a list of n numbers. #include<stdio.h> main() { int n, count, navg=0; float x, average, sum =0; printf(How many numbers?); scanf(%d, &n); for (count =1; count<=n; ++count) {printf(x= ): scanf(%f,&x); if (x<0) continue: sum+= x; ++navg: average = sum/navg printf(\nThe average is %f \n, average); } } The go to statement: The go to statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. The general form of goto statement can be written as goto label; Where label is an identifier that is used to label the largest statement to which control will be transferred . Control may be transferred to any other statement within the program. The largest statement will appear as Label: statement Each labeled statement within the program must have a unique label i.e. no. two statements can have the same label.

28 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Entry control loop and exit control loop:

Test condition True Body of the loop

False

Body of the loop

Test condition True

False

Application of Computer in Textiles (Sheet 1: C Programming Basic)

29

Chapter 7

FUNCTION
Function: A function is a self contained program segment that carries out some specific, well defined task. A function is defined with two principal components: The first line (including the argument declarations) The body of the function. In general terms, the first line can be written as: Data type name (type 1, arg 1. type 2 arg2, ,typen argn) Where data type represents the data item that is returned by the function, name represents the function name and type1, type2,type3..typen represents the data type of the arguments arg1, arg2, ..argn Example: Char lower_to_upper(char c) { char c2; c2=(c1 =(c1>= a && c1<= z)?(A +c1- a):c1; return(c2); } void main(void) {char lower, upper; printf(please enter a lower case character:); scanf(%c, &lower); upper= lower_to_upper(lower); printf(\nThe upper case equivalent is %c \n\n,upper); }

Advantages of Function: I. The use of programmer defined defn functions allows a large program to be broken into a number of smaller, self contained segments. Each of which has some unique, identifiable purpose. II. The use of function avoids the needs for redundant (repeated) programming of the same instructions. III. The use of functions also enable the programmer to build a customized library of frequently used routines.

30 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Return statement: Information is returned from the function to the calling portion of the program via the return statement. The return statement also causes the program logic to return to the point from which the function was accessed. In general terms, the return statement is written as Return expression, The value of the expression is returned to the calling portion of the program. The expression is optional. If the expression is omitted, the return statement simply causes control to revert back to the calling portion of the program, without any transfer of information. Argument/Parameter: Information passed to the function from the calling portion of the program and return a single value i.e. information passed to the function via special identifiers called arguments/parameters. Local variable/Formal parameter: The arguments appearing in the function call are referred to as actual arguments/Global variable). The first line of the function definition is called Formal parameter. Formal arguments represents the names of data items that are transferred into the function from the calling portion of the program. Formal arguments are local in sense that they are not recognized outside the function. Global variable/Actual parameter: The corresponding arguments of formal arguments in the function reference are called actual parameter. They are called since they define the data items that are actually transferred. In normal function call, there will be one actual argument for each formal argument. The actual arguments must be expressed as constants, single variables or more complex expressions. Each actual argument must be of the same data type as its corresponding formal argument. The relation between Actual & Formal arguments: The actual arguments must correspond to the formal arguments in the function defn i.e. the no. of actual arguments must be the same as the no. of formal arguments and each actual argument must be of the same data type as its corresponding formal arguments. F.P are usually written at the beginning of a program ahead of a programmer defined function (including main) ends with a semicolon

Distinguish between local variable, formal parameters and variables:


Local variable 1. It is declared within a Format parameter 1. It is declared within function Global variable. 1. It is declared out of a function .

Application of Computer in Textiles (Sheet 1: C Programming Basic)

31

function. 2. Its scope is limited to function. 3. The same name may be used as local variable in different functions. 4. Auto or static may precede local variables.

argument. 2. Its scope is limited to function. 3. The same name may be used as local variable in different functions. 4. Usually auto or static is not preceded formal parameters. 4. Extern is preceded global variables. 2. Its scope is through the whole program 3. But it is not possible in data of global variable.

Function call: A function will carry

out its intended action (whenever it is accessed(i.e.

whenever the function is called) from some other portion of the program. The structure of function call: Function_name(); The function call may be a part of a simple expression (such as an assignment statement) or it may be one of the operands within a more complex expression. Void parameter: If in function, no need of parameter void key word is used. Have no return value Function prototype: Some times in C language a top down approach in which main function appears ahead of the programmer defined function definition. In such situation, the function access will be defined later in the program, which is known as function prototype. The general form of function of function prototype is Data type name (type1 arg1, type2 arg2.typen argn); Where data-type represents the data type of the item that is returned by the function, name represents the functional name, and type1, type2 type n represents the data types of the arguments arg1, arg2, .argn. A C program to calculate the factorial of an integer quantity: (by using function prototype): /* a program to find factorial by using function declared as a Global function*/ #include<stdio.h> int factorial(int n); void main() {

32 Application of Computer in Textiles (Sheet 1: C Programming Basic)

int x; printf("enter which factorial"); scanf("%d",&x); printf("%d",factorial(x)); } int factorial(int n) {int i; long int y; y=1; for(i=1;i<=n;i++) y=y*i; return(y); } Recursive function/Recursion: Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. Man iterative problems can be written in this form. In order to solve a problem recursively two conditions must be satisfied. First, the problem must be written in a recursive form and 2nd the problem statement must include a stopping condition. Advantage: Need of less variable. Can be represent the program easily. Reduction of complexity of program. A C program to calculate the factorial of an integer quantity using recursion: /* a program to find out factorial using recursive function*/ #include<stdio.h> long int factorial(int n); void main() { int n; printf("Enter the number:"); scanf("%d", &n); printf("factorial of %d=%ld",n,factorial(n)); } long int factorial(int n)

Application of Computer in Textiles (Sheet 1: C Programming Basic)

33

{ if(n<=1)return(1); else return(n*factorial(n-1)); } A C program that reads a line of text and write it backwards using recursion: #include<stdio.h> #include<conio.h> void reverse(void); void main() { printf("Enter your text:"); reverse(); getch(); } void reverse(void) { char c; if ((c=getchar())!='\n')reverse(); putchar(c); return; } Write a C program to calculate the factorial of n by function: /* a program to find factorial by using function declared as a local function*/ #include<stdio.h> int factorial(int n); void main() { int x; printf("enter which factorial"); scanf("%d",&x); printf("%d",factorial(x)); } int factorial(int n) {int i; long int y; y=1;

34 Application of Computer in Textiles (Sheet 1: C Programming Basic)

for(i=1;i<=n;i++) y=y*i; return(y); }

Application of Computer in Textiles (Sheet 1: C Programming Basic)

35

Chapter 9

Arrays
Arrays: Arrays are defined in much the same manner as ordinary variables, except that each array name must be accompanied by a size specification. General formula of array declarationdata-type-name[size]; data-type means the type of array (int, char etc) & size identified by the total number of variable in array. Example: int i[5];

int i[5]; Data type Array name Index/subscript

Types of Array: Two types of array1. One dimensional array. 2. Multi dimensional array. 1. One dimensional array: The array which is formed by one subscript is called one dimensional array. For one dimensional array, the size is specified by a positive integer expression, enclosed in square brackets. In general terms, a one dimensional array definition may be expressed as storage class data_type array [expression]; Example: Int i[5]; Floati[5]; Static float n[2]; 2. Multi dimensional array: Multi dimensional arrays are defined in the same manner as one dimensional array except that a separate pair of square brackets are required for each subscript. Thus a two dimensional array will require three pairs of square brackets and so on. A multi three dimensional array will require three pairs of square brackets and so on. A multi dimensional array is defined as storage class data type array [exp1][exp2].[expn]

36 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Example: int x[5][5]; two dimensional: Data_type array_name [row][column]; Sorting: Sorting is a process to arrange large number of data in ascending or descending order. Method of sorting: 1. Selection sorting. 2. Bubble sorting. 3.Quick sorting. 4. Heap sorting. 5. Merge sorting. 6.Insertion sorting. /*a program to sort the number descending order*/ #include<stdio.h> int x[100],y,n,i,j,k; void main(){ printf("How many number do you sort"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&x[i]); for(j=0;j<n-1;j++) for(k=j+1;k<n;k++) if(x[j]<x[k]) {y=x[j]; x[j]=x[k]; x[k]=y;} for(i=0;i<n;i++) printf("\t%d",x[i]); } /*a program to sort of strings alphabetically using two dimensional character array*/ #include<stdio.h> #include<string.h>

[< for decending order(largesmall] > for ascending order(smalllarge).]

Application of Computer in Textiles (Sheet 1: C Programming Basic)

37

void reorder(int n, char x[][12]); main() { int n,i; char x[10][12]; printf("Enter each string on a separate line below\n"); printf("Type \'end\' when finished\n\n"); n=0; do { printf("string%d:",n+1); scanf("%s",x[n]); }while (strcmp(x[n++], "end")); n--; reorder(n,x); printf("\n Reorder List of strings are below:\n\n"); for (i=0;i<n;++i) printf("\n %s",x[i]); } void reorder(int n, char x[][12]) { char temp[12]; int i,j; for (j=0;j<n-1;++j) for (i=j+1;i<n;++i) if(strcmp(x[j],x[i])>0) { strcpy(temp,x[j]); strcpy(x[j],x[i]); strcpy(x[i],temp); } return; }

38 Application of Computer in Textiles (Sheet 1: C Programming Basic)

Chapter 10

Pointers
Pointers: A pointer is a variable that represents the location of a data item, such as a variable or an array element. Pointer variables, like all other variables, must be declared before they may be used in C program. Thus a pointer declaration may be written in general termsdata type *ptvar; Here ptvar is the name of pointer variable and data type refers to the data type of the pointers object. Why pointer used: Pointer are frequently used in C as they have a number of applications1. Pointers can be used to pass information back and forth betn a function and its reference point. 2. Pointers provide a way to return multiple data items from a function via function arguments. 3. Pointer also permit references to other functions to be specified as arguments to a given function. This has the effect of passing as arguments to the given function. 4. Pointers also provide an alternative way to access individually array element. 5. Moreover pointers provide a convenient way to represent multidimensional arrays. Int*p[10]*p is 10 element array of pointers to integer quantities. Int(*p)[10]*p is a pointer to a 10 element integer array. Advantage of pointer: 1. In global variable, reduce function calling and easier data accessing in using of pointer. 2. Reduce the length and complexity of program. 3. More efficient in handling the data items. 4. Increase the program execution speed. 5. Saving data storage, place in memory. Disadvantage: Cannot hold the different data item. Dynamic memory allocation: (DMA): The use of a pointer variable to represent an array requires some type of initial memory assignment before the array elements are processed. This is known as dynamic memory allocation. Generally the malloc library function is used for this purpose. Advantages: To reserve as much memory as may be required during program executed. Difference betn Array and Pointer:

Application of Computer in Textiles (Sheet 1: C Programming Basic)

39

Array 1. An array contain the data .

Pointer 1. A pointer contain the address of data.

2. Array stores variables which have common character e.g. same type same storage class. 3. Data items are predeclared.

2. Pointer is a variable which represent the location of a data item.

3. Memory is allow only for input datas not for any array.

4. High memory loss. 5. 2 types. 6. Array declared as storage class data type array [expression]

4. No loss of memory. 5. No classification. 6. Pointer declared as datatype *ptvar.

7. Subscript is used but asteric 7. Asteric (*) is used. is not used.

/*a program to sort number Descending by using pointer*/ #include<stdio.h> #include<stdlib.h> void main() { int *x,y,n,i,j,k; printf("How many number do you sort"); scanf("%d",&n); x=(int*)malloc(n*sizeof(int)); for(i=0;i<n;i++) scanf("%d",x+i); for(j=0;j<n-1;j++) for(k=j+1;k<n;k++) if(*(x+j)<*(x+k)) {y=*(x+j); *(x+j)=*(x+k); *(x+k)=y;} for(i=0;i<n;i++)

40 Application of Computer in Textiles (Sheet 1: C Programming Basic)

printf("\t%d",*(x+i)); } /*a program to count no of vowels, consonant whitespace, digit & others*/ #include<stdio.h> #include<ctype.h> void scan_line(char line[ ], int *pv, int *pc, int *pd, int *pw, int *po); main() { char line[80]; int vowels =0; int consonants = 0; int digits = 0; int whitespc = 0; int other = 0; printf("Enter a line of text below:\n"); scanf("%s", line); scan_line(line, &vowels,&consonants,&digits, &whitespc, &other); printf("\nNo. of vowels: %d",vowels); printf("\nNo. of consonants: %d",consonants); printf("\nNo. of digits: %d",digits); printf("\nNo. of whitespace characters: %d",whitespc); printf("\nNo. of other characters: %d",other); } void scan_line(char line[ ], int *pv, int *pc, int *pd, int *pw, int *po)

{ char c; int count =0;

while((c = toupper(line[count]))!='\0') { if (c =='A' || c=='I'||c=='E' || c =='O'|| c =='U') ++ *pv; else if (c>= 'A' && c<='Z') ++ *pc; else if (c== ' ' || c == '\t')

Application of Computer in Textiles (Sheet 1: C Programming Basic)

41

++ *pw; else if (c>=0||c<=9) ++*pd; else ++ *po; ++count; } return;}

Difference between ordinary variable and array variable: Ordinary variable 1. An ordinary variable does not require size specification. 2. It consists of only one data of certain length according to the type. 3. No dimension. 4. Arguments are passed by value 5.Any change of arguments in other functions does not alter the value of variable in main function. 6. Ordinary variable declared as: Data-type variable name; 6. Array variable declared as: data-type array name [expression] 3.One or more dimension. 4. Arguments are passed by address. 5. Any change of arguments in other functions alters the value of variable in main function. Array variable 1. An array variable requires size specification. 2.It consists of more than one data of certain length .

Chapter 13

C Graphics
function name: syntax arc( ) prototype far arc (int x, int y, int start, int end, int radius); void far arc (int x, int y, int start, int

42 Application of Computer in Textiles (Sheet 1: C Programming Basic)

bar( )

syntax prototype

bar3d( )

syntax prototype

circle( ) cleardevice( ) clearviewport (void) closegraph() drawpoly( )

syntax prototype syntax prototype syntax prototype syntax prototype syntax prototype

end, int radius); bar (int left, int top, int right, int bottom); void far bar (int left, int top, int right, int bottom); bar3d(int left, int top, int right, int bottom, int depth, int topflag); void far bar3d(int left, int top, int right, int bottom, int depth, int topflag); circle ( int x, int y, int radius); void far circle ( int x, int y, int radius); cleardevice (void); void far cleardevice (void); clearviewport(void); void far clearviewport(void); far closegraph(void); void far closegraph(void); drawpoly(int numpoints, int far *points); void far drawpoly(int numpoints, int far *points); ellipse( int x, int y, int start, int end, int xradius, int yradius); void far ellipse( int x, int y, int start, int end, int xradius, int yradius); fillellipse(intx, inty, intxr, int yr); void far fillellipse(intx, inty, intxr, int yr); fillpoly(int numpoints, int far *points); void far fillpoly(int numpoints, int far *points); floodfill(int x, int y, int border); void far floodfill(int x, int y, int border); getcolor(void); int far getcolor(void); getimage ( int left, int top, int bottom, void far*buf); void far getimage ( int left, int top, int bottom, void far*buf); getmaxx ( void); int far getmaxx ( void); getmaxy ( void); int far getmaxy ( void); getpixel (int x, int y); unsigned far getpixel (int x, int y); getx (void); int far getx (void); gety (void); int far gety (void); gotoxy(intx, inty);

ellipse()

syntax prototype

fillellipse( )

syntax prototype syntax prototype syntax prototype syntax prototype syntax prototype

fillpoly()

floodfill ( )

getcolor(void) getimage( )

getmaxx( ) getmaxy( ) getpixel( ) getx(void) gety(void) gotoxy( )

syntax prototype syntax prototype syntax prototype syntax prototype syntax prototype syntax

Application of Computer in Textiles (Sheet 1: C Programming Basic)

43

initgraph( )

prototype syntax prototype

line( )

syntax prototype

movetext( )

syntax prototype

outtextxy( )

syntax prototype syntax prototype syntax prototype

outtext( ) pieslice ( )

putimage( )

syntax prototype

putpixel( ) puttext( )

syntax prototype syntax prototype

rectangle( )

syntax prototype

sector( )

syntax prototype syntax prototype

setallpalette ( )

setcolor( ) setfillpattern( )

syntax prototype syntax prototype

setfillstyle ( )

syntax prototype syntax

settextstyle ( )

void gotoxy(intx, inty); initgraph(int far*driver, int far*mode, char far*path); void far initgraph(int far*driver, int far*mode, char far*path); line( int startx, int starty, int endx, int endy); void far line( int startx, int starty, int endx, int endy); movetext( int left, int top, int right, int bottom, int newleft, int newtop); int movetext( int left, int top, int right, int bottom, int newleft, int newtop); far outtextxy(int x, int y, char *str); void far outtextxy(int x, int y, char *str); outtext (char far *str); void far outtext (char far *str); pieslice( int x, int y , int start, int end, int radius); void far pieslice( int x, int y , int start, int end, int radius); putimage (int x, int y, void far *buf, int op); void far putimage (int x, int y, void far *buf, int op); putpixel(int x, inty, int color); void putpixel(int x, inty, int color); puttext (int left, int top, int bottom void*buf); int puttext (int left, int top, int bottom void*buf); rectangle( int left, int top, int right, int bottom); void far rectangle( int left, int top, int right, int bottom); sector( intx, inty, int end, int xr, int yr); void far sector( intx, inty, int end, int xr, int yr); setailpallette (struct pallettetype far* pal); void far setailpallette (struct pallettetype far* pal); setcolor(int color); void far setcolor(int color); setfillpattern(char far*pattern, int color); void far setfillpattern(char far*pattern, int color); setfillstyle (int pattern, int color); void far setfillstyle (int pattern, int color); settextstyle ( int font, int direction, int

44 Application of Computer in Textiles (Sheet 1: C Programming Basic)

prototype textbackgroun d( ) textcolor( ) syntax prototype syntax prototype

size); void far settextstyle ( int font, int direction, int size); textbackground(int color); void textbackground(int color); textcolor(int color); void textcolor(int color);

A program to draw a national flag: #include<stdio.h> #include<conio.h> #include<graphics.h> void main ( ) { int driver= DETECT, mode=0; initgraph(&driver, &mode, c:\\tc\\bgi); selector(2); setfillstyle(3, 13); floodfill(100, 100,2); printf(\n\nNational flag of Bangladesh); selector(2); rectangle(200,150,450,300); setfillstyle(1,2); floodfill(325, 225,2); setcolor(4); rectangle(180, 150, 200, 400); circle(325,225); setfillstyle(1,4); floodfill(325, 225, 4); setcolor(3); rectangle(180,150,200,400); setfillstyle(1,5); floodfill(190, 350,3); selector(3) rectangle( 170,400,210, 420); setfillstyle( 1,8); floodfill( 200, 410,3); getch(); }

Application of Computer in Textiles (Sheet 1: C Programming Basic)

45

Você também pode gostar