100
Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine : A machine is any device that uses energy to perform some activity. Data : In computer science, data is anything in a form suitable for use with a computer. Instructions: In computer science, source code is any sequence of statements or declarations June 26, 2022 1

Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Embed Size (px)

Citation preview

Page 1: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

What is Computer ?

Session # 2 [Introduction to Computers]

What is Computer ?

A computer is a machine that manipulates data according to a list of instructions.

Machine : A machine is any device that uses energy to perform some activity.

Data : In computer science, data is anything in a form suitable for use with a computer.

Instructions: In computer science, source code is any sequence of statements or declarations

written in some human-readable computer programming language.

A computer is a machine that manipulates data according to a list of instructions.

Machine : A machine is any device that uses energy to perform some activity.

Data : In computer science, data is anything in a form suitable for use with a computer.

Instructions: In computer science, source code is any sequence of statements or declarations

written in some human-readable computer programming language.

April 11, 2023 1

Page 2: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Data Vs. Information

Session # 2 [Introduction to Computers]

Data Vs. Information

DataCollection of raw facts are nothing but data. In fact it is plural, singular for this is

datum. ex:

Information Processed data is the nothing but Information.

ex:

DataCollection of raw facts are nothing but data. In fact it is plural, singular for this is

datum. ex:

Information Processed data is the nothing but Information.

ex:

April 11, 2023 2

Roll No Sub Code S1 S2 S3 A1 A2 A3

Y7CSE11 CSE311 9 8 7 6 5 6

Y7CSE12 CSE311 8 8 9 7 5 3

Y7CSE13 CSE311 7 7 8 6 5 5

Roll No Sub Code Marks

Y7CSE11 CSE311 29

Y7CSE12 CSE311 29

Y7CSE13 CSE311 26

Page 3: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Data Processing Activities

Session # 2 [Introduction to Computers]

Data Processing Activities

April 11, 2023 3

Page 4: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Computer Processing Capabilities

Session # 2 [Introduction to Computers]

Computer Processing Capabilities

April 11, 2023 4

Page 5: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Computer Processing Capabilities

Session # 2 [Introduction to Computers]

Computer Processing Capabilities

April 11, 2023 5

Input unitInput unit

output unitoutput unit

Primary memory

[ram]

Primary memory

[ram]

ALUALU

CUCU

Secondary memory[H.D]

Secondary memory[H.D]

Page 6: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Computer Programming Languages

Session # 2 [Introduction to Computers]

Computer Programming Languages

April 11, 2023 6

Page 7: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 2 [Introduction to Computers]

Computer Language Translators

Session # 2 [Introduction to Computers]

Computer Language Translators

Compiler :

A compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language). The original sequence is usually called the source code and the output called object code.

The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine language)

Interpreter :An interpreter may be a program that either

executes the source code directly translates source code into some efficient intermediate representation (code) and immediately executes this explicitly executes stored precompiled code made by a compiler which is part of the interpreter system

Compiler :

A compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language). The original sequence is usually called the source code and the output called object code.

The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine language)

Interpreter :An interpreter may be a program that either

executes the source code directly translates source code into some efficient intermediate representation (code) and immediately executes this explicitly executes stored precompiled code made by a compiler which is part of the interpreter system

April 11, 2023 7

Page 8: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

An Overview of C

Session # 3 [C Fundamentals]

An Overview of C

History of C language :

Characteristics of C’ language: Middle level Language [ It has good qualities of both high/low level languages] Structured Programming Language Programmer’s Language

History of C language :

Characteristics of C’ language: Middle level Language [ It has good qualities of both high/low level languages] Structured Programming Language Programmer’s Language

April 11, 2023 8

Page 9: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

C Character Set

Session # 3 [C Fundamentals]

C Character Set

C Character set Includes C Character set Includes

April 11, 2023 9

Page 10: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Identifiers

Session # 3 [C Fundamentals]

Identifiers

IdentifiersIdentifiers are used to identify some programming elements like, variables,

arrays, pointers, functions, and user defined things. The following are the rules to construct valid identifiers.

• We have to use only alphabets, digits and one special character [ _ ] underscore.• The first letter must not be a digit• The length of these identifiers may vary from one to several characters. • Identifier name should not be same as a C keyword.

IdentifiersIdentifiers are used to identify some programming elements like, variables,

arrays, pointers, functions, and user defined things. The following are the rules to construct valid identifiers.

• We have to use only alphabets, digits and one special character [ _ ] underscore.• The first letter must not be a digit• The length of these identifiers may vary from one to several characters. • Identifier name should not be same as a C keyword.

April 11, 2023 10

Page 11: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

keywords

Session # 3 [C Fundamentals]

keywords

Keywordsa few words are reserved for particular programming purpose in all most

all modern programming languages. C’ also have reserved a few words to play key role in programming purpose. They are as follows.

Keywordsa few words are reserved for particular programming purpose in all most

all modern programming languages. C’ also have reserved a few words to play key role in programming purpose. They are as follows.

April 11, 2023 11

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Page 12: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Literals

Session # 3 [C Fundamentals]

Literals

April 11, 2023 12

Page 13: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Variables

Session # 3 [C Fundamentals]

Variables

Variables:While solving a problem we may need to remember some data values temporarily. Such values are placed in the named locations in the memory. These named locations in the memory are called variables.

To create a location in the memory, system needs three specifications

Variables:While solving a problem we may need to remember some data values temporarily. Such values are placed in the named locations in the memory. These named locations in the memory are called variables.

To create a location in the memory, system needs three specifications

April 11, 2023 13

Page 14: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Variables Declarations

Session # 3 [C Fundamentals]

Variables Declarations

You create location or locations in the memory with these specifications, we can specify to the system through variable declaration statement.

Its syntax is:type variablelist;

To declare single variable:type variablename;

Note: Variable name should be valid identifier. Remaining two specifications we are specifying through data type.

You create location or locations in the memory with these specifications, we can specify to the system through variable declaration statement.

Its syntax is:type variablelist;

To declare single variable:type variablename;

Note: Variable name should be valid identifier. Remaining two specifications we are specifying through data type.

April 11, 2023 14

Page 15: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Data Types

Session # 3 [C Fundamentals]

Data Types

Data TypesIt defines two things

Type of value, the location has to hold, Set of operations may be performed against the location.

C supports 5 foundational data types

Data TypesIt defines two things

Type of value, the location has to hold, Set of operations may be performed against the location.

C supports 5 foundational data types

April 11, 2023 15

Page 16: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 3 [C Fundamentals]

Variable Declaration Examples

Session # 3 [C Fundamentals]

Variable Declaration Examples

April 11, 2023 16

Page 17: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 4 [Operators]

Introduction to Operators

Session # 4 [Operators]

Introduction to Operators

Operators:Operators are symbols that perform a particular operation on operands. Here operands might

be variables/constants.note: operators and operands are collectively form C’ expressions.

ex: ‘+’ operator performs an addition operation

Depending on the number of operands the operator is expecting, all operators are classified into 3 types:

Operators:Operators are symbols that perform a particular operation on operands. Here operands might

be variables/constants.note: operators and operands are collectively form C’ expressions.

ex: ‘+’ operator performs an addition operation

Depending on the number of operands the operator is expecting, all operators are classified into 3 types:

April 11, 2023 17

Page 18: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 4 [Operators]

Assignment Operator

Session # 4 [Operators]

Assignment Operator

Assignment Operator [ = ]In ‘c’, (=) is the assignment operator, it performs the assignment operation. Assignment statement is constructed by using this operator.Syntax : variable= value/expression;

ex: int a = 67;

Multiple Assignments to store 5 integers constants temporary we need 5 variables of int type.

int a, b, c, d, e;to assign 10 in all these locations

a = 10; b = 10;

c = 10; d = 10; e = 10;

Instead of 5 assignment statements we can manage with single assignment statement as a = b = c = d = e = 10;

Assignment Operator [ = ]In ‘c’, (=) is the assignment operator, it performs the assignment operation. Assignment statement is constructed by using this operator.Syntax : variable= value/expression;

ex: int a = 67;

Multiple Assignments to store 5 integers constants temporary we need 5 variables of int type.

int a, b, c, d, e;to assign 10 in all these locations

a = 10; b = 10;

c = 10; d = 10; e = 10;

Instead of 5 assignment statements we can manage with single assignment statement as a = b = c = d = e = 10;

April 11, 2023 18

Page 19: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 4 [Operators]

Arithmetic Operators

Session # 4 [Operators]

Arithmetic Operators

Arithmetic OperatorsArithmetic Operators

April 11, 2023 19

Page 20: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #4 [Operators]

Increment and Decrement Operators

Session #4 [Operators]

Increment and Decrement Operators

Increment and Decrement Operators(++) is an increment operator. it increments its operand value by 1.( -- ) is a decrement operator. it decrements its operand value by 1.

Both operators are unary operators. They expect numeric or char type variable as operand.ex : i + + ; is equivalent to i = i + 1 ;

These two operators can precede the operand or can follow the operand+ + i prefix formi + + post fix form

There is no difference between prefix form and postfix form in short expressions but there is difference in long expression.

Increment and Decrement Operators(++) is an increment operator. it increments its operand value by 1.( -- ) is a decrement operator. it decrements its operand value by 1.

Both operators are unary operators. They expect numeric or char type variable as operand.ex : i + + ; is equivalent to i = i + 1 ;

These two operators can precede the operand or can follow the operand+ + i prefix formi + + post fix form

There is no difference between prefix form and postfix form in short expressions but there is difference in long expression.

April 11, 2023 20

prefix postfix

expression a=10, b; b=++a;

a=10, b; b=a++;

result a=11 b=11

a=11 b=10

Page 21: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Relational Operators

Session # 5 [Operators]

Relational Operators

Relational Operators(outcome to any relational expression is either nonzero(or) zero)Relational Operators(outcome to any relational expression is either nonzero(or) zero)

April 11, 2023 21

C relational Operators Example of C condition Meaning of the condition

Equality Operators

= == x==y x is equals to y

not = != x!=y x is not equals to y

Relational Operators

> > x > y x is greater than y

< < x < y x is less than y

>= >= x >= y x is greater or equals to y

<= <= x <=y x is less or equal to y

Page 22: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Logical Operators

Session # 5 [Operators]

Logical Operators

Logical Operators

&& ( logical AND ) Returns true if both conditions are true

|| ( logical OR ) Returns true if either of its conditions are true

! ( logical NOT, logical negation )Reverses the truth/falsity of its conditionUnary operator, has one operand

Truth Table

Logical Operators

&& ( logical AND ) Returns true if both conditions are true

|| ( logical OR ) Returns true if either of its conditions are true

! ( logical NOT, logical negation )Reverses the truth/falsity of its conditionUnary operator, has one operand

Truth Table

April 11, 2023 22

exp1 exp2 exp1 && exp2 exp1 || exp2 !exp1

False False False False True

False True False True True

True False False True false

True True True True false

Page 23: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Conditional Operator

Session # 5 [Operators]

Conditional Operator

Conditional Operator [? : ] ternary operator.

Syntax

expression 1 ? expression 2 : expression 3;

The expression 1 is evaluated first and if the outcome of expression 1 is true then the outcome of the complete expression is expression 2 otherwise the outcome of the complete expression is expression 3.

Conditional Operator [? : ] ternary operator.

Syntax

expression 1 ? expression 2 : expression 3;

The expression 1 is evaluated first and if the outcome of expression 1 is true then the outcome of the complete expression is expression 2 otherwise the outcome of the complete expression is expression 3.

April 11, 2023 23

exp1exp1 exp2exp2 exp3exp3

true

false

Page 24: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Bit wise Operator

Session # 5 [Operators]

Bit wise Operator

Bitwise OperatorsAll data represented internally as sequences of bits

Each bit can be either 0 or 1 Sequence of 8 bits forms a byte

Bitwise OperatorsAll data represented internally as sequences of bits

Each bit can be either 0 or 1 Sequence of 8 bits forms a byte

April 11, 2023 24

Operator Name Description& bitwise AND The bits in the result are set to 1 if the corresponding bits in the

two operands are both 1.

| bitwise OR The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1.

^ bitwise exclusive OR The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1.

<< left shift Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from right with 0 bits.

>> right shift Shifts the bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent.

~ One’s complement All 0 bits are set to 1 and all 1 bits are set to 0.

Page 25: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Pointer Operators

Session # 5 [Operators]

Pointer Operators

Pointer OperatorsThere are two pointer operators: * and &.& (Address Of):The & is a unary operator that returns the memory address of its operand. Example: int count,*m; m=&count;The first statement will create one variable with name count and pointer with name m of int type .The second statement places address of count variable into the pointer variable m.You can think of & has returning “the address of”. Therefore the preceding statement can be verbalized as “m receives the address of count".*( At address):The second pointer operator is the compliment of &, This is also a unary operator that returns the value located at that address. Example: q=*m;

Pointer OperatorsThere are two pointer operators: * and &.& (Address Of):The & is a unary operator that returns the memory address of its operand. Example: int count,*m; m=&count;The first statement will create one variable with name count and pointer with name m of int type .The second statement places address of count variable into the pointer variable m.You can think of & has returning “the address of”. Therefore the preceding statement can be verbalized as “m receives the address of count".*( At address):The second pointer operator is the compliment of &, This is also a unary operator that returns the value located at that address. Example: q=*m;

April 11, 2023 25

Page 26: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Operator Precedence and Associativity

Session # 5 [Operators]

Operator Precedence and Associativity

April 11, 2023 26

Operator Description Associativity

()[].

->++ --

Parentheses (function call) (see Note 1)Brackets (array subscript)Member selection via object nameMember selection via pointerPostfix increment/decrement (see Note 2)

left-to-right

++ --+ -! ~

(type)*&

sizeof

Prefix increment/decrementUnary plus/minusLogical negation/bitwise complementCast (change type)DereferenceAddressDetermine size in bytes

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

Page 27: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Operator Precedence and Associativity

Session # 5 [Operators]

Operator Precedence and Associativity

April 11, 2023 27

<< >> Bitwise shift left, Bitwise shift rightleft-to-right

< <=> >=

Relational less than/less than or equal toRelational greater than/greater or equal to

left-to-right

== != Relational is equal to/is not equal toleft-to-right

& Bitwise ANDleft-to-right

^Bitwise exclusive OR left-to-right

| Bitwise inclusive ORleft-to-right

&& Logical AND left-to-right

|| Logical ORleft-to-right

?: Ternary conditionalright-to-left

Page 28: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 5 [Operators]

Operator Precedence and Associativity

Session # 5 [Operators]

Operator Precedence and Associativity

April 11, 2023 28

=+= -=*= /=

%= &=^= |=

<<= >>=

AssignmentAddition/subtraction assignmentMultiplication/division assignmentModulus/bitwise AND assignmentBitwise exclusive/inclusive OR assignmentBitwise shift left/right assignment

right-to-left

, Comma (separate expressions)left-to-right

Note 1:Parentheses are also used to group expressions to force a different order of evaluation; such parenthetical expressions can be nested and are evaluated from inner to outer

Note 2:Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done.

CastsYou can force an expression to be of a specific type by using a cast. The general form of a cast is (type) expression(Here type is a valid data type.) For example, to cause the expression x/2 to evaluate to type float, write (float) x/2

Page 29: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 6 [Console I/O]

Input Output Statements

Session # 6 [Console I/O]

Input Output Statements

Console I/O

Introduction Files and streams

In C any physical device which is used to do input or output operations is called file. Examples: Keyboard, Screen, Printer, Disk file, etc...

StreamA stream is a logical device, which is an abstraction between the physical device and program. Via streams only input output operations takes place. There are two types of streams.

Text Stream Binary Stream

In fact we read from the source, and write to the sink.

Console I/O

Introduction Files and streams

In C any physical device which is used to do input or output operations is called file. Examples: Keyboard, Screen, Printer, Disk file, etc...

StreamA stream is a logical device, which is an abstraction between the physical device and program. Via streams only input output operations takes place. There are two types of streams.

Text Stream Binary Stream

In fact we read from the source, and write to the sink.

April 11, 2023 29

Page 30: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 6 [Console I/O]

Reading Data from Source

Session # 6 [Console I/O]

Reading Data from Source

Reading Data from Source

To read data from source do the following.

Reading Data from Source

To read data from source do the following.

April 11, 2023 30

Page 31: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 6 [Console I/O]

Writing data to the Sink

Session # 6 [Console I/O]

Writing data to the Sink

Writing Data to Sink

To write data to the sink ,do the following.

Writing Data to Sink

To write data to the sink ,do the following.

April 11, 2023 31

Page 32: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 6 [Console I/O]

Standard Streams

Session # 6 [Console I/O]

Standard Streams

Standard StreamsTo read data from user via keyboard or to give output to the user via screen we need not do first two steps in reading and writing because when C program execution is started some predefined streams are opened automatically. They are

Standard StreamsTo read data from user via keyboard or to give output to the user via screen we need not do first two steps in reading and writing because when C program execution is started some predefined streams are opened automatically. They are

April 11, 2023 32

Page 33: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 7 [Console I/O]

Unformatted and Formatted Functions

Session # 7 [Console I/O]

Unformatted and Formatted Functions

Built in FunctionsTo write data to stdout we have putchar (), puts (),printf() built-in functions.putchar ()Syntax: #include <stdio.h> int putchar( int ch );The putchar() function writes ch to STDOUT. The code putchar( ch );

puts()Syntax: #include <stdio.h> int puts( char *str ); The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure

Built in FunctionsTo write data to stdout we have putchar (), puts (),printf() built-in functions.putchar ()Syntax: #include <stdio.h> int putchar( int ch );The putchar() function writes ch to STDOUT. The code putchar( ch );

puts()Syntax: #include <stdio.h> int puts( char *str ); The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure

April 11, 2023 33

Page 34: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 7 [Console I/O]

Unformatted and Formatted Functions

Session # 7 [Console I/O]

Unformatted and Formatted Functions

Built in Functionsprintf ()Syntax: #include <stdio.h> int printf( const char *format, ... ); The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code char name[20] = "Bob"; int age = 21;

printf( "Hello %s, you are %d years old\n", name, age );Displays the following output: Hello Bob, you are 21 years oldThe %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot.

Built in Functionsprintf ()Syntax: #include <stdio.h> int printf( const char *format, ... ); The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code char name[20] = "Bob"; int age = 21;

printf( "Hello %s, you are %d years old\n", name, age );Displays the following output: Hello Bob, you are 21 years oldThe %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot.

April 11, 2023 34

Page 35: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 7 [Console I/O]

Format Specifiers

Session # 7 [Console I/O]

Format Specifiers

Format Specifiers:Format Specifiers:

April 11, 2023 35

code format Code format

%c Character %o Octal

%d signed integers %s a string of characters

%i signed integers %u unsigned integer

%e scientific notation, with a lowercase "e" %xunsigned hexadecimal, with lowercase

letters

%E scientific notation, with a uppercase "E" %Xunsigned hexadecimal, with uppercase

letters

%f floating point %p a pointer

%g use %e or %f, whichever is shorter %nthe argument shall be a pointer to an

integer into which is placed the number of characters written so far

%G use %E or %f, whichever is shorter %% a '%' sign

Page 36: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Form of a C program

Session # 9 [introduction to C Program]

Form of a C program

THE FORM OF C’ PROGRAM # include<header file 1>

. Preprocessor directives # include<header file N>

User function declarations (prototypes) if anyVariables declarations if any

int main (void){

Statements;}

returntype function1 (parameter list){

Statements;}..returntype functionN (parameter list){

Statements;} note: red in color specifies to be optional

THE FORM OF C’ PROGRAM # include<header file 1>

. Preprocessor directives # include<header file N>

User function declarations (prototypes) if anyVariables declarations if any

int main (void){

Statements;}

returntype function1 (parameter list){

Statements;}..returntype functionN (parameter list){

Statements;} note: red in color specifies to be optional

April 11, 2023 36

Page 37: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

First C program

Session # 9 [introduction to C Program]

First C program

A SIMPLE C’ PROGRAM

#include<stdio.h>#include<conio.h>/* no user function declarations [prototypes] no global variables

*/

int main (void){

clrscr ();printf (“Welcome to SSIT”);getche();

}

A SIMPLE C’ PROGRAM

#include<stdio.h>#include<conio.h>/* no user function declarations [prototypes] no global variables

*/

int main (void){

clrscr ();printf (“Welcome to SSIT”);getche();

}

April 11, 2023 37

Page 38: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Program Development Process

Session # 9 [introduction to C Program]

Program Development Process

Analyze the given problem and design solution with the following strategy.Analyze the given problem and design solution with the following strategy.

April 11, 2023 38

Page 39: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #9 [introduction to C Program]

Computer Algorithm and Flow Chart

Session #9 [introduction to C Program]

Computer Algorithm and Flow Chart

What is a computer algorithm?

To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal.

When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept.

What is a Flow chart?

A flowchart illustrates the steps in a process. By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved.

What is a computer algorithm?

To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal.

When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept.

What is a Flow chart?

A flowchart illustrates the steps in a process. By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved.

April 11, 2023 39

Page 40: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Example Program

Session # 9 [introduction to C Program]

Example Program

Problem:Program to compute the sum of given two numbers

Step 1:

Problem:Program to compute the sum of given two numbers

Step 1:

April 11, 2023 40

Page 41: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Example Program

Session # 9 [introduction to C Program]

Example Program

Step 2: Step 2:

April 11, 2023 41

Page 42: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Example Program

Session # 9 [introduction to C Program]

Example Program

Flow Chart Flow Chart

April 11, 2023 42

StartStart

Clear the Screen

Enter no1:Enter no1:

Read no1Read no1

Enter no2Enter no2

Read no2Read no2

Print “no1+no2=no1+no2”

StopStop

Page 43: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 9 [introduction to C Program]

Example Program

Session # 9 [introduction to C Program]

Example Program

Program #include <stdio.h>

#include <conio.h> /* no global variables no user function declarations (prototypes) */ int main(void)

Block starts here int no1,no2; // declatation statement clrscr(); // call statement printf(“enter no1:”); // call statement scanf(“%d”,&no1); // call statement printf(“enter no2:”); // call statement scanf(“%d”,&no2); // call statement printf(“%d + %d = %d”,no1,no2,no1+no2); getche(); // call statement return 0; // jump statement

Block ends here

Program #include <stdio.h>

#include <conio.h> /* no global variables no user function declarations (prototypes) */ int main(void)

Block starts here int no1,no2; // declatation statement clrscr(); // call statement printf(“enter no1:”); // call statement scanf(“%d”,&no1); // call statement printf(“enter no2:”); // call statement scanf(“%d”,&no2); // call statement printf(“%d + %d = %d”,no1,no2,no1+no2); getche(); // call statement return 0; // jump statement

Block ends here

April 11, 2023 43

Page 44: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 10 [Statements]

Types of Statements

Session # 10 [Statements]

Types of Statements

To do this, we can specify to the system by using statement. A statement is a complete instruction categorizes statements into these groups:To do this, we can specify to the system by using statement. A statement is a complete instruction categorizes statements into these groups:

April 11, 2023 44

Page 45: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 10 [Statements]

Control Statements

Session # 10 [Statements]

Control Statements

C program control statements can be put into the following categories.C program control statements can be put into the following categories.

April 11, 2023 45

-if , switch-if , switch for, while, dofor, while, do goto, break, continue, return

goto, break, continue, return

Page 46: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 10 [Statements]

Selection Statements

Session # 10 [Statements]

Selection Statements

Selection Statements

C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative to if in certain circumstances.If

The general form of the if statement is If(expression)

statement; [else

statement;]

Here a statement may consist of a single statement, a block of statements, or nothing. The else clause is optional.

Selection Statements

C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative to if in certain circumstances.If

The general form of the if statement is If(expression)

statement; [else

statement;]

Here a statement may consist of a single statement, a block of statements, or nothing. The else clause is optional.

April 11, 2023 46

Page 47: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 10 [Statements]

Selection Statements

Session # 10 [Statements]

Selection Statements

If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed, otherwise the statement after the target of else is executed, if it exists. The conditional statement controlling if must produce a scalar result. A scalar is integer, character, pointer or floating point type.

If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed, otherwise the statement after the target of else is executed, if it exists. The conditional statement controlling if must produce a scalar result. A scalar is integer, character, pointer or floating point type.

April 11, 2023 47

Page 48: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 11 [Statements]

Selection Statements

Session # 11 [Statements]

Selection Statements

If LadderIf we have several groups of statements and one of the group is to be executed selectively specify that

intension by using if Ladder or switch in some casesSyntax

if(expression)statement;

else if(expression) statement;

else if(expression) statement;

.

.else

statement;

The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of ladder is bypassed. If none of the conditions are true, the final else is executed. If the final else is not present, no action takes place if all other conditions are false.

If LadderIf we have several groups of statements and one of the group is to be executed selectively specify that

intension by using if Ladder or switch in some casesSyntax

if(expression)statement;

else if(expression) statement;

else if(expression) statement;

.

.else

statement;

The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of ladder is bypassed. If none of the conditions are true, the final else is executed. If the final else is not present, no action takes place if all other conditions are false.

April 11, 2023 48

Page 49: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 11 [Statements]

Selection Statements

Session # 11 [Statements]

Selection Statements

switchC has a built-in multiple-branch selection statement, called switch, which successively test the value of an expression against list of integer or character constant. When a match is found, the statements associated with that constants are executed. The general form of switch statement is

switch(expression){

case constant1: statement sequence [break];

case constant2: statement sequence [break];

case constant3: statement sequence [break];

.

.[default: statement sequence;]

}The expression must be evaluated to an integer type thus we can use character or integer values, but floating point expressions, for example, are not allowed.

switchC has a built-in multiple-branch selection statement, called switch, which successively test the value of an expression against list of integer or character constant. When a match is found, the statements associated with that constants are executed. The general form of switch statement is

switch(expression){

case constant1: statement sequence [break];

case constant2: statement sequence [break];

case constant3: statement sequence [break];

.

.[default: statement sequence;]

}The expression must be evaluated to an integer type thus we can use character or integer values, but floating point expressions, for example, are not allowed.

April 11, 2023 49

Page 50: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 11 [Statements]

Iteration Statements

Session # 11 [Statements]

Iteration Statements

Iteration statementsYou do these things repeatedly, we can specify to the system by using one of the three repetition statements:while loopThe general form is while(condition) statement;

Here statement may be an empty statement, a single statement, or a block of statements. The condition may be any expression, and true is any non zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of the code immediately following the loop.

Iteration statementsYou do these things repeatedly, we can specify to the system by using one of the three repetition statements:while loopThe general form is while(condition) statement;

Here statement may be an empty statement, a single statement, or a block of statements. The condition may be any expression, and true is any non zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of the code immediately following the loop.

April 11, 2023 50

Page 51: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #12 [Statements]

Iteration Statements

Session #12 [Statements]

Iteration Statements

do-while loopThe general form of the do-while loop is

do{

Statement;}while(condition);

The do-while loop iterates until condition becomes false. The do-while loop checks its condition at the bottom of the loop. This means that the do-while always executes at least once.

do-while loopThe general form of the do-while loop is

do{

Statement;}while(condition);

The do-while loop iterates until condition becomes false. The do-while loop checks its condition at the bottom of the loop. This means that the do-while always executes at least once.

April 11, 2023 51

Page 52: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 12 [Statements]

Iteration Statements

Session # 12 [Statements]

Iteration Statements

for loopYou do this things repeatedly varying so and so variable value from so and so to so with

increment or decrement so and so to specify use for statement. The general form of for loop is

for(Initialization; Condition; Increment){

//statements}

for loopYou do this things repeatedly varying so and so variable value from so and so to so with

increment or decrement so and so to specify use for statement. The general form of for loop is

for(Initialization; Condition; Increment){

//statements}

April 11, 2023 52

Page 53: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 12 [C Fundamentals]

Jump Statements

Session # 12 [C Fundamentals]

Jump Statements

Jump StatementsC has four statements that perform an unconditional branch, You can use return and goto anywhere inside the function. You can use break and continue statements inside any of the loop statements. You can also use break with switch.return You return this value back to the calling area we can specify to the system by using return statement.

The general form is below.return value / expression;

break The break statement has two uses ,To break the switch and the loop

The general formbreak;

Continue To opt for the early iteration use it.

General formcontinue;

Jump StatementsC has four statements that perform an unconditional branch, You can use return and goto anywhere inside the function. You can use break and continue statements inside any of the loop statements. You can also use break with switch.return You return this value back to the calling area we can specify to the system by using return statement.

The general form is below.return value / expression;

break The break statement has two uses ,To break the switch and the loop

The general formbreak;

Continue To opt for the early iteration use it.

General formcontinue;

April 11, 2023 53

Page 54: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 13 [Functions]

Introduction to Functions

Session # 13 [Functions]

Introduction to Functions

Functions

C’s main structural component is function. It allows compartmentalization of code and data. Functions (sub programs) are used to carry out certain sub tasks. We can divide a long C program into small blocks which can perform a certain task.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done.

Generally in C, what are the functions we are writing other than main () function we declare them before the main(), we call them in main() and define them after main(). So function contains declaration and definition.

Functions

C’s main structural component is function. It allows compartmentalization of code and data. Functions (sub programs) are used to carry out certain sub tasks. We can divide a long C program into small blocks which can perform a certain task.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done.

Generally in C, what are the functions we are writing other than main () function we declare them before the main(), we call them in main() and define them after main(). So function contains declaration and definition.

April 11, 2023 54

Page 55: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 13 [Functions]

Functions Declaration

Session # 13 [Functions]

Functions Declaration

Function DeclarationFunction declaration syntax:

returntype function_name ( parameter list);To write a function declaration easily, try to get answers for the following questions

To determine maximum of two integers int max(int a, int b);

Function DeclarationFunction declaration syntax:

returntype function_name ( parameter list);To write a function declaration easily, try to get answers for the following questions

To determine maximum of two integers int max(int a, int b);

April 11, 2023 55

Page 56: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #1 3 [Functions]

Functions Definition

Session #1 3 [Functions]

Functions Definition

Function DefinitionSyntax. returntype functionname (parameter list)

{ /*statements*/ } Example:

int max ( int a, int b) {

if(a>b) return a;

else return b; }

Function DefinitionSyntax. returntype functionname (parameter list)

{ /*statements*/ } Example:

int max ( int a, int b) {

if(a>b) return a;

else return b; }

April 11, 2023 56

Page 57: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #13 [Functions]

Functions Call Statement

Session #13 [Functions]

Functions Call Statement

Function call statementTo run so and so function we can specify to the system by using function call statement. Syntax

Functionname (arguments);

To ask the system to run a function called max() which is expecting two integers

max(10,20);

When this statement is executed control goes to max () function taking arguments to the formal parameters and function executes, when function returns, return value (if any) replaces the function call statement. To receive the return value, use the following syntax.

Variable=Functionname (arguments);

Function call statementTo run so and so function we can specify to the system by using function call statement. Syntax

Functionname (arguments);

To ask the system to run a function called max() which is expecting two integers

max(10,20);

When this statement is executed control goes to max () function taking arguments to the formal parameters and function executes, when function returns, return value (if any) replaces the function call statement. To receive the return value, use the following syntax.

Variable=Functionname (arguments);

April 11, 2023 57

Page 58: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 13 [Functions]

Types of Call Statements

Session # 13 [Functions]

Types of Call Statements

Call By Value and Call By Address

In a computer language there are two ways to pass the arguments to a function; the first one is call by value. This method copies the value of the argument into the formal parameter of the function. In this case , changes made to the parameter have no effect on the argument.ex:

void ssit (int , int);

Call by Address is second way of passing the arguments to the function. In this method the address of the argument will be copied to the formal parameters. In side the function ,the address is used to access the actual argument used in the call. This means that the changes made to the parameter effect to the argumentex:

void ssit (int *,int *);

Call By Value and Call By Address

In a computer language there are two ways to pass the arguments to a function; the first one is call by value. This method copies the value of the argument into the formal parameter of the function. In this case , changes made to the parameter have no effect on the argument.ex:

void ssit (int , int);

Call by Address is second way of passing the arguments to the function. In this method the address of the argument will be copied to the formal parameters. In side the function ,the address is used to access the actual argument used in the call. This means that the changes made to the parameter effect to the argumentex:

void ssit (int *,int *);

April 11, 2023 58

Page 59: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #1 3 [Functions]

Example Program using Function

Session #1 3 [Functions]

Example Program using Function

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

int max(int,int,int);

void main(void){

int m,n,o,big;clrscr();printf("enter any three nos. one by one\n");scanf("%d%d%d",&m,&n,&o);printf("\n m = %d and n = %d and o = %d",m,n,o);big=max(m,n,o);printf("\n maximum is :%d:“,big);getche();

}

int max(int x,int y,int z){

return x > y && x > z ? x : y > z ? y : z;}

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

int max(int,int,int);

void main(void){

int m,n,o,big;clrscr();printf("enter any three nos. one by one\n");scanf("%d%d%d",&m,&n,&o);printf("\n m = %d and n = %d and o = %d",m,n,o);big=max(m,n,o);printf("\n maximum is :%d:“,big);getche();

}

int max(int x,int y,int z){

return x > y && x > z ? x : y > z ? y : z;} April 11, 2023 59

Page 60: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 14 [Arrays and Strings]

Introduction 2 Arrays

Session # 14 [Arrays and Strings]

Introduction 2 Arrays

Arrays

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type[int] with a unique identifier.

These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats are called simply an array.

Moreover we can construct one dimensional array as well as multidimensional array.

Arrays

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type[int] with a unique identifier.

These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats are called simply an array.

Moreover we can construct one dimensional array as well as multidimensional array.

April 11, 2023 60

Page 61: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 14 [Arrays and Strings]

One Dimensional Arrays

Session # 14 [Arrays and Strings]

One Dimensional Arrays

One Dimensional ArrayIt is an array that stores values in the memory horizontally.

Array declaration: To construct a one dimensional array system requires the following 3 specifications, they

include.

One Dimensional ArrayIt is an array that stores values in the memory horizontally.

Array declaration: To construct a one dimensional array system requires the following 3 specifications, they

include.

April 11, 2023 61

Page 62: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 14 [Arrays and Strings]

One Dimensional Arrays

Session # 14 [Arrays and Strings]

One Dimensional Arrays

Syntax Type ArrayVariableName [size];eg:

int nos [5];when above statement is executed , memory will be allocated to store 5 integers in continuous locations.

0 1 2 3 4 nos

101 103 105 107 109The amount of storage required to hold an array is directly related to its type and size, for a single dimensional array the total size in bytes will be computed as

total bytes=sizeof(base type)* size of an array.

Total number of bytes allotted for this array are:

sizeof(int) * 5 => 2 * 5 = 10;

Syntax Type ArrayVariableName [size];eg:

int nos [5];when above statement is executed , memory will be allocated to store 5 integers in continuous locations.

0 1 2 3 4 nos

101 103 105 107 109The amount of storage required to hold an array is directly related to its type and size, for a single dimensional array the total size in bytes will be computed as

total bytes=sizeof(base type)* size of an array.

Total number of bytes allotted for this array are:

sizeof(int) * 5 => 2 * 5 = 10;April 11, 2023 62

Page 63: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 14 [Arrays and Strings]

One Dimensional Arrays

Session # 14 [Arrays and Strings]

One Dimensional Arrays

Accessing array elements:

Each element is identifying with unique index value. Indexing is zero based. First element index is 0, second element index is 1, so on. To name the element of the array syntax is

Arrayname [index]Name of the first element is nos[0],name of the second is nos[1],so on.

While constructing the array, if we know what values elements are to represent, use the following syntax.

type arrayvariable[size] ={list of values};int nos[]={10,20,30,40,50} ;

Reading values into Array elements:for example, to read values from the keyboard to the array that above declared, do the following

for (i=0; i< size; i++)scanf(“%d”,&nos[i]);

Accessing array elements:

Each element is identifying with unique index value. Indexing is zero based. First element index is 0, second element index is 1, so on. To name the element of the array syntax is

Arrayname [index]Name of the first element is nos[0],name of the second is nos[1],so on.

While constructing the array, if we know what values elements are to represent, use the following syntax.

type arrayvariable[size] ={list of values};int nos[]={10,20,30,40,50} ;

Reading values into Array elements:for example, to read values from the keyboard to the array that above declared, do the following

for (i=0; i< size; i++)scanf(“%d”,&nos[i]);

April 11, 2023 63

Page 64: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 15 [Arrays and Strings]

Two Dimensional Arrays

Session # 15 [Arrays and Strings]

Two Dimensional Arrays

Two-Dimensional ArrayC supports multi dimensional arrays. The simplest form of multidimensional array is the two

dimensional array. A two dimensional array is essentially, an array of one dimensional arrays.

To declare two dimensional array syntax istype arrayname[m][n];

Example:int twod[4][3];

To access the element of two dimensional array arrayname[i][j];

To assign 1 in first elementtwod[0][0]=1;

In case of two dimensional arrays, the following formula yields the number of bytes of memory needed to hold it.

Bytes=sizeof(firstindex) * sizeof(secondindex) * sizeof (base type)

Two-Dimensional ArrayC supports multi dimensional arrays. The simplest form of multidimensional array is the two

dimensional array. A two dimensional array is essentially, an array of one dimensional arrays.

To declare two dimensional array syntax istype arrayname[m][n];

Example:int twod[4][3];

To access the element of two dimensional array arrayname[i][j];

To assign 1 in first elementtwod[0][0]=1;

In case of two dimensional arrays, the following formula yields the number of bytes of memory needed to hold it.

Bytes=sizeof(firstindex) * sizeof(secondindex) * sizeof (base type)

April 11, 2023 64

Page 65: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 16 [Pointers]

Introduction to Pointers

Session # 16 [Pointers]

Introduction to Pointers

Pointers A pointer is a variable that holds memory address. This address is the location of another variable in memory. Correct understanding and use of pointers is crucial to successful c programming, there are several reasons for this:

Pointers A pointer is a variable that holds memory address. This address is the location of another variable in memory. Correct understanding and use of pointers is crucial to successful c programming, there are several reasons for this:

April 11, 2023 65

Page 66: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 16 [Pointers]

Pointer Variables

Session # 16 [Pointers]

Pointer Variables

Pointer variablesA pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be declared as such type * variablename ; Example:

int * p; Here type is the base type of the pointer.

Sample program using pointer operators:

int a=15,*p; pp=&a;printf(“ a=%d”,*p); a

201

Pointer variablesA pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be declared as such type * variablename ; Example:

int * p; Here type is the base type of the pointer.

Sample program using pointer operators:

int a=15,*p; pp=&a;printf(“ a=%d”,*p); a

201April 11, 2023 66

201201

1515

Page 67: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 17 [Pointers]

Pointer Arithmetic

Session # 17 [Pointers]

Pointer Arithmetic

Pointer Arithmetic There are only two arithmetic operations that can use on pointers, they are

1. Addition2. Subtraction

To understand what occurs in pointer arithmetic,Let p1 be an integer pointer with the address 2000. Also assume int ‘s are 2 bytes long. After

the expression : P1++;P1 contains 2002, not 2001.

The reason for this is that each time p1 is incremented it will point to the next integer. The same is true for decrements. Each time a pointer is incremented, it points to the memory location of the next element of its base type. Each time it is decremented it points to the memory location of the previous element.

Subtracting one pointer from other, in order to find number of objects of base type that separate the two pointers.

Note: all other arithmetic operations are prohibited.

Pointer Arithmetic There are only two arithmetic operations that can use on pointers, they are

1. Addition2. Subtraction

To understand what occurs in pointer arithmetic,Let p1 be an integer pointer with the address 2000. Also assume int ‘s are 2 bytes long. After

the expression : P1++;P1 contains 2002, not 2001.

The reason for this is that each time p1 is incremented it will point to the next integer. The same is true for decrements. Each time a pointer is incremented, it points to the memory location of the next element of its base type. Each time it is decremented it points to the memory location of the previous element.

Subtracting one pointer from other, in order to find number of objects of base type that separate the two pointers.

Note: all other arithmetic operations are prohibited.April 11, 2023 67

Page 68: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 17 [Pointers]

Arrays with Pointers

Session # 17 [Pointers]

Arrays with Pointers

Arrays with Pointerswe are already familiar with arrays(collection of similar data elements referred through common name).Processing array with pointers is much more effective and it is very simple, because generally all data elements of an array are stored in continuous memory locations, so if you know address of starting element of an array, it is very easy to move till the end.

Finding address of the first element of an array is simple, as like getting the address of any (by prefixing & to that variable).Here in our arrays each element can name as Arrayname [index]; First element index is 0, so the first element name is Arrayname [0]; so & Arrayname [0];(address of first element)

int a[10],*p;( 'a' be the array and 'p' is the pointer). p=&a[0];

we can write p=a; (Because Arrayname itself contains address of first element)

Arrays with Pointerswe are already familiar with arrays(collection of similar data elements referred through common name).Processing array with pointers is much more effective and it is very simple, because generally all data elements of an array are stored in continuous memory locations, so if you know address of starting element of an array, it is very easy to move till the end.

Finding address of the first element of an array is simple, as like getting the address of any (by prefixing & to that variable).Here in our arrays each element can name as Arrayname [index]; First element index is 0, so the first element name is Arrayname [0]; so & Arrayname [0];(address of first element)

int a[10],*p;( 'a' be the array and 'p' is the pointer). p=&a[0];

we can write p=a; (Because Arrayname itself contains address of first element)

April 11, 2023 68

Page 69: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 17 [Pointers]

Arrays with Pointers

Session # 17 [Pointers]

Arrays with Pointers

Arrays with PointersOnce u know address of first element it’s very easy to move forward, thru pointer addition.

At the same time we can move from last element to first also, thru pointer subtraction from last element address.

Example: int a[5]={20,30,40,10,50}, *p; p=a; /* suppose address is 2000*/ The base address value is obtained by mentioning its name first value can be accessed by using *p .similarly we can access next elements by *(p + i).

Arrays with PointersOnce u know address of first element it’s very easy to move forward, thru pointer addition.

At the same time we can move from last element to first also, thru pointer subtraction from last element address.

Example: int a[5]={20,30,40,10,50}, *p; p=a; /* suppose address is 2000*/ The base address value is obtained by mentioning its name first value can be accessed by using *p .similarly we can access next elements by *(p + i).

April 11, 2023 69

Page 70: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 17 [Arrays and Strings]

Arrays with Functions

Session # 17 [Arrays and Strings]

Arrays with Functions

Passing One Dimensional Array to Functions

In C , you can not pass an entire array as an argument to function, However You can pass a pointer to an array by specifying arrays name with out an index. For example the following program fragment passes the address of nos to display().

int main(void){

int nos[]={10,20,30,40,50};display(nos);return 0;

} If a function receives a pointer to a one dimensional array, you can declare its formal parameter in one of three ways: as a pointer, as a sized array or as unsized array. For example, to receive nos, function called display() it can be defined as

Passing One Dimensional Array to Functions

In C , you can not pass an entire array as an argument to function, However You can pass a pointer to an array by specifying arrays name with out an index. For example the following program fragment passes the address of nos to display().

int main(void){

int nos[]={10,20,30,40,50};display(nos);return 0;

} If a function receives a pointer to a one dimensional array, you can declare its formal parameter in one of three ways: as a pointer, as a sized array or as unsized array. For example, to receive nos, function called display() it can be defined as

April 11, 2023 70

Page 71: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #17 [Arrays and Strings]

Arrays with Functions

Session #17 [Arrays and Strings]

Arrays with Functions

Passing One Dimensional Array to Functions

All three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received

Passing One Dimensional Array to Functions

All three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received

April 11, 2023 71

Page 72: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 18 [Arrays and Strings]

Strings

Session # 18 [Arrays and Strings]

Strings

StringsSome thing which is placed in between double quotation marks is called string literal .In C a string is

treated as one dimensional char array terminated with null character. This means that after the last truly usable char there is a null, hex 00, which is represented in C by '\0'.Example:

char str[15],*p;p=str; // similar to p=& str[0],bcz array name itself contains first element address.

The above statement declares a char array called str. C provides fifteen consecutive bytes of memory. Only the first fourteen bytes are usable for character storage, because one must be used for the string-terminating null

The following is a representation of what would be in RAM, if the string "Hello, world!" is stored in this array.

StringsSome thing which is placed in between double quotation marks is called string literal .In C a string is

treated as one dimensional char array terminated with null character. This means that after the last truly usable char there is a null, hex 00, which is represented in C by '\0'.Example:

char str[15],*p;p=str; // similar to p=& str[0],bcz array name itself contains first element address.

The above statement declares a char array called str. C provides fifteen consecutive bytes of memory. Only the first fourteen bytes are usable for character storage, because one must be used for the string-terminating null

The following is a representation of what would be in RAM, if the string "Hello, world!" is stored in this array.

April 11, 2023 72

characters H e l l O , w o r l d ! \0

Hex values 48 65 6c 6c 6f 2c 20 77 6f 71 6c 64 21 00

subscripts 0 1 2 3 4 5 6 7 8 9 10 11 12 13

Page 73: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 18 [Arrays & Strings]

String Functions

Session # 18 [Arrays & Strings]

String Functions

Built in String FunctionsThe string functions operate on null-terminated arrays of characters and require the header<string.h>strlen()Syntax: size_t strlen( char *str );The strlen() function returns the length of str (determined by the number of characters before null termination). The following code will result in len having the value 13.

int len = strlen("Hello, world!");strcpy()Syntax: char *strcpy( char *to, const char *from );The strcpy() function copies characters in the string from to the string to, including the null termination. Given the following declarations, several things are possible.

char S[25],D[25];Copying a whole string from S to D:

strcpy (D, S); Copying the tail end of string S to D:

strcpy( D, &S[8]);

Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result.

Built in String FunctionsThe string functions operate on null-terminated arrays of characters and require the header<string.h>strlen()Syntax: size_t strlen( char *str );The strlen() function returns the length of str (determined by the number of characters before null termination). The following code will result in len having the value 13.

int len = strlen("Hello, world!");strcpy()Syntax: char *strcpy( char *to, const char *from );The strcpy() function copies characters in the string from to the string to, including the null termination. Given the following declarations, several things are possible.

char S[25],D[25];Copying a whole string from S to D:

strcpy (D, S); Copying the tail end of string S to D:

strcpy( D, &S[8]);

Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result.April 11, 2023 73

Page 74: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 18 [Arrays & Strings]

String Functions

Session # 18 [Arrays & Strings]

String Functions

Built in String Functionsstrcat()Syntax: char *strcat( char *str1, const char *str2 );The strcat() function concatenates str2 onto the end of str1, and returns str1. For example: printf( "Enter your name: " ); scanf( "%s", name ); title = strcat( name, " the Great" ); printf( "Hello, %s\n", title ); strncat()Syntax: char *strncat( char *str1, const char *str2, size_t count );The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned. Given the following declarations, several things are possible, but only one is commonly used.

char S[25] = "world!“,D[25]=“Hello,”;Concatenating five characters from the beginning of S onto the end of D and placing a null at the end:

strncat(D, S, 5); [strncat(D, S, strlen(S) -1);]Both would result in D containing "Hello, world".

Built in String Functionsstrcat()Syntax: char *strcat( char *str1, const char *str2 );The strcat() function concatenates str2 onto the end of str1, and returns str1. For example: printf( "Enter your name: " ); scanf( "%s", name ); title = strcat( name, " the Great" ); printf( "Hello, %s\n", title ); strncat()Syntax: char *strncat( char *str1, const char *str2, size_t count );The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned. Given the following declarations, several things are possible, but only one is commonly used.

char S[25] = "world!“,D[25]=“Hello,”;Concatenating five characters from the beginning of S onto the end of D and placing a null at the end:

strncat(D, S, 5); [strncat(D, S, strlen(S) -1);]Both would result in D containing "Hello, world".

April 11, 2023 74

Page 75: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 19 [Arrays & Strings]

String Functions

Session # 19 [Arrays & Strings]

String Functions

Built in String Functionsstrcmp()The function strcmp() compares str1 and str2Syntax:

int strcmp( const char *str1, const char *str2 );For example: printf( "Enter your name: " ); scanf( "%s", name ); if( strcmp( name, "Mary" ) == 0 ) printf( "Hello, Dr. Mary!\n" );strncmp()Syntax: int strncmp( const char *str1, const char *str2, size_t count );The strncmp() compares at most count characters of str1 and str2. The return value is as follows(even strcmp() returns the same):

If there are less than count characters in either string, then the comparison will stop after the first null termination is encountered.

Built in String Functionsstrcmp()The function strcmp() compares str1 and str2Syntax:

int strcmp( const char *str1, const char *str2 );For example: printf( "Enter your name: " ); scanf( "%s", name ); if( strcmp( name, "Mary" ) == 0 ) printf( "Hello, Dr. Mary!\n" );strncmp()Syntax: int strncmp( const char *str1, const char *str2, size_t count );The strncmp() compares at most count characters of str1 and str2. The return value is as follows(even strcmp() returns the same):

If there are less than count characters in either string, then the comparison will stop after the first null termination is encountered.

April 11, 2023 75

Return value Explanationless than 0 str1 is less than str2equal to 0 str1 is equal to str2greater than 0 str1 is greater than str2

Page 76: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 20[DMA]

Introduction to DMA

Session # 20[DMA]

Introduction to DMA

Dynamic memory allocation:

C’s Memory MapA complied C program creates and uses four logically distinct regions of memory.

stack heap

Dynamic memory allocation:

C’s Memory MapA complied C program creates and uses four logically distinct regions of memory.

stack heap

April 11, 2023 76

Page 77: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #20 [DMA]

DMA Functions

Session #20 [DMA]

DMA Functions

Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation.

Although c does not inherently have this facility there are four library routines which allow this function. Standard C defines four dynamic allocation functions that all compilers will

support[associated with stdlib.h ], those are..

Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation.

Although c does not inherently have this facility there are four library routines which allow this function. Standard C defines four dynamic allocation functions that all compilers will

support[associated with stdlib.h ], those are..

April 11, 2023 77

Page 78: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 21 [Derived Types]

Introduction to Derived Data Types

Session # 21 [Derived Types]

Introduction to Derived Data Types

Derived TypesC language gives you five ways to create a custom data types , those are..

Derived TypesC language gives you five ways to create a custom data types , those are..

April 11, 2023 78

Page 79: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 21 [Derived Types]

Structures

Session # 21 [Derived Types]

Structures

StructuresA structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together.A structure declaration forms a template that can be used to create structured objects.The variables that make up the structure are called members. They are also commonly refer to as elements or to as fields.Need of structureHow will you store the address of a person which consists of name, street, city, state, pin with the following types

char name[20]char street[20]char city[20]char state[3]unsigned long int pin

The above stated address will be created in 5 locations which may not be side-by-side,to store all the variables of a particular data in consecutive locations of memory there is a need for new data type.i.e STRUCTURE

StructuresA structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together.A structure declaration forms a template that can be used to create structured objects.The variables that make up the structure are called members. They are also commonly refer to as elements or to as fields.Need of structureHow will you store the address of a person which consists of name, street, city, state, pin with the following types

char name[20]char street[20]char city[20]char state[3]unsigned long int pin

The above stated address will be created in 5 locations which may not be side-by-side,to store all the variables of a particular data in consecutive locations of memory there is a need for new data type.i.e STRUCTURE

April 11, 2023 79

Page 80: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 21 [Derived Types]

Structures

Session # 21 [Derived Types]

Structures

Structure Features Structure allows us to keep related variables under one nameThis type object allows us to keep related information together

The General form a structure declaration is

Note: Here either tag or structure-variables may be omitted, but not both.

Structure Features Structure allows us to keep related variables under one nameThis type object allows us to keep related information together

The General form a structure declaration is

Note: Here either tag or structure-variables may be omitted, but not both.April 11, 2023 80

struct tag {

type member-name;type member-name;type member-name;..

} structure-variables;

Page 81: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 21 [Derived Types]

Structure Examples

Session # 21 [Derived Types]

Structure Examples

Structure ExamplesStructure Examples

April 11, 2023 81

Page 82: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 22 [Derived Types]

Constructing the structure objects

Session # 22 [Derived Types]

Constructing the structure objects

Constructing the structure objects To use the Structure we need to construct structure object , we have created the following different variablesA simple variableA pointer variableA simple array variableAn array of pointers In the same way we can create a structure type variablesysntax:

struct <structure name> <variable>;Eaxmple:To declare variable of type addr, write

struct addr addr_info; When above statement is executed for all members memory locations are allocated as per their specifications in a continuous manner.

Constructing the structure objects To use the Structure we need to construct structure object , we have created the following different variablesA simple variableA pointer variableA simple array variableAn array of pointers In the same way we can create a structure type variablesysntax:

struct <structure name> <variable>;Eaxmple:To declare variable of type addr, write

struct addr addr_info; When above statement is executed for all members memory locations are allocated as per their specifications in a continuous manner.

April 11, 2023 82

Page 83: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 22 [Derived Types]

Structure Processing

Session # 22 [Derived Types]

Structure Processing

Accessing structure membersIndividual members of a structure are accessed through the use of the “.” (dot) Operator.The general form for accessing the member of the structure is

objectname.membernameFor Example, the following statement assigns the pin code 500036 to the pin field of the structure variable addr_info.

addr_info.pin=500036;

Structure Memory AllocationStructure object occupies the memory as “total no. of bytes occupied by all the members of the

structure” Consider Student address structure

struct addr{ char name[20]; char street[20]; char city[20]; char state[3]; unsigned long int pin;};

The total memory allocated for this structure is20+20+20+3+4 = 67 bytes

Accessing structure membersIndividual members of a structure are accessed through the use of the “.” (dot) Operator.The general form for accessing the member of the structure is

objectname.membernameFor Example, the following statement assigns the pin code 500036 to the pin field of the structure variable addr_info.

addr_info.pin=500036;

Structure Memory AllocationStructure object occupies the memory as “total no. of bytes occupied by all the members of the

structure” Consider Student address structure

struct addr{ char name[20]; char street[20]; char city[20]; char state[3]; unsigned long int pin;};

The total memory allocated for this structure is20+20+20+3+4 = 67 bytes

April 11, 2023 83

Page 84: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 22 [Derived Types]

Structure Example Program

Session # 22 [Derived Types]

Structure Example Program

#include<stdio.h>#include<conio.h>struct addr{

char name[20],street[20],city[20];unsigned long pin ;

};struct addr addr_info; int main(void){

clrscr();printf(“Enter Name”); gets(addr_info.name);printf(“Enter Street”); gets(addr_info.street);printf(“Enter City”); gets(addr_info.city);printf(“Enter State”); gets(addr_info.state);printf(“Enter Pin”); scanf(“%d”,addr_info.pin);printf(“Name:%s\n”,addr_info.name);printf(“street:%s\n”,addr_info.street);printf(“city:%s\n”,addr_info.city);printf(“state:%s\n”,addr_info.state);printf(“pin:%d\n”,addr_info.pin);return 0;

}

#include<stdio.h>#include<conio.h>struct addr{

char name[20],street[20],city[20];unsigned long pin ;

};struct addr addr_info; int main(void){

clrscr();printf(“Enter Name”); gets(addr_info.name);printf(“Enter Street”); gets(addr_info.street);printf(“Enter City”); gets(addr_info.city);printf(“Enter State”); gets(addr_info.state);printf(“Enter Pin”); scanf(“%d”,addr_info.pin);printf(“Name:%s\n”,addr_info.name);printf(“street:%s\n”,addr_info.street);printf(“city:%s\n”,addr_info.city);printf(“state:%s\n”,addr_info.state);printf(“pin:%d\n”,addr_info.pin);return 0;

} April 11, 2023 84

Page 85: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 23 [Derived Types]

Array of structures

Session # 23 [Derived Types]

Array of structures

Array of structures As we know array is collection of similar data types like int, float, char etc. In the same way we can also define array of structures. In that array every element is of structure type. Array of structures can be declared as follows.

struct addr{

char name[20];char street[20];char city[25];char state[3];unsigned long pin ;

}; struct addr addr_info[5];

Array of structures As we know array is collection of similar data types like int, float, char etc. In the same way we can also define array of structures. In that array every element is of structure type. Array of structures can be declared as follows.

struct addr{

char name[20];char street[20];char city[25];char state[3];unsigned long pin ;

}; struct addr addr_info[5];

April 11, 2023 85

Page 86: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #23 [Derived Types]

Nested structures

Session #23 [Derived Types]

Nested structures

Structure within structure (Nested Structure)We can take any data type for declaring structure members like int, float, char etc.we can also take objects of one structure as members of another structure.The general form is

struct date{ int dd; int mm; int yy;};

example Struct person

{ char name[25]; struct date dob;}emp;

We can access the dd as emp.dod.dd

Structure within structure (Nested Structure)We can take any data type for declaring structure members like int, float, char etc.we can also take objects of one structure as members of another structure.The general form is

struct date{ int dd; int mm; int yy;};

example Struct person

{ char name[25]; struct date dob;}emp;

We can access the dd as emp.dod.dd

April 11, 2023 86

Page 87: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 23 [Derived Types]

Passing Structure object to functions

Session # 23 [Derived Types]

Passing Structure object to functions

Passing Structure object to functionsLike variables of standard type, structure variables can also be passed to the function by value

or address . Syntax:

return type function name (structure variable){

stmts;..

}Example:

void show ( struct record m){

}

Passing Structure object to functionsLike variables of standard type, structure variables can also be passed to the function by value

or address . Syntax:

return type function name (structure variable){

stmts;..

}Example:

void show ( struct record m){

}

April 11, 2023 87

Page 88: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 23 [Derived Types]

Pointer to a STRUCTURE

Session # 23 [Derived Types]

Pointer to a STRUCTURE

Pointer to a STRUCTURE Pointer is a variable that holds the address of another variable. The variable may be of any type int,

float, char etc. in the same way we can define a pointer to a structure. Structure pointers are declared by placing * in front of structure variables name.Example:

struct addr{ char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ;};

struct addr *p; (p is pointer to structure.)To access the member of a structure using pointer to the structure we must use (arrow) operatorAs Pointer name member nameFor Example, to assign 500036 to pin p->pin=500036

Pointer to a STRUCTURE Pointer is a variable that holds the address of another variable. The variable may be of any type int,

float, char etc. in the same way we can define a pointer to a structure. Structure pointers are declared by placing * in front of structure variables name.Example:

struct addr{ char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ;};

struct addr *p; (p is pointer to structure.)To access the member of a structure using pointer to the structure we must use (arrow) operatorAs Pointer name member nameFor Example, to assign 500036 to pin p->pin=500036

April 11, 2023 88

Page 89: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 24 [Derived Types]

Enumerations

Session # 24 [Derived Types]

Enumerations

EnumerationsEnumeration is a set of named integer constants. Enumerations are defined much like structures. The keyword enum the start of the enumeration type. The general form for enumerations isSyntax

enum tag{ //Enumeration list } var_list; The following four fragments define an enumeration called coin:

enum coin { penny, nickel, dime, quarter, half_dollar, dollar };The enumeration tagname can be used to declare variables of its type the following declare money to be a variable of type coin: enum coin money;

if(money==quarter) printf (“Money is a quarter.\n”);The key point to understand about is the enumeration is that each of the symbols stands for an integer value. Each symbol is given a value one greater than the symbol that precedes it. The value of the first enumeration symbol is zero. Therefore,

printf (“%d %d “,penny, dime); [ o/p : 0 2]

EnumerationsEnumeration is a set of named integer constants. Enumerations are defined much like structures. The keyword enum the start of the enumeration type. The general form for enumerations isSyntax

enum tag{ //Enumeration list } var_list; The following four fragments define an enumeration called coin:

enum coin { penny, nickel, dime, quarter, half_dollar, dollar };The enumeration tagname can be used to declare variables of its type the following declare money to be a variable of type coin: enum coin money;

if(money==quarter) printf (“Money is a quarter.\n”);The key point to understand about is the enumeration is that each of the symbols stands for an integer value. Each symbol is given a value one greater than the symbol that precedes it. The value of the first enumeration symbol is zero. Therefore,

printf (“%d %d “,penny, dime); [ o/p : 0 2]

April 11, 2023 89

Page 90: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 24 [Derived Types]

Unions

Session # 24 [Derived Types]

Unions

UnionsA union is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time. Once a new value is assigned to a field, the existing data is wiped over with the new data. The size of a union is equal to the size of it's largest data member. why because only one member can be used at a timeSyntax to declare a union:

UnionsA union is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time. Once a new value is assigned to a field, the existing data is wiped over with the new data. The size of a union is equal to the size of it's largest data member. why because only one member can be used at a timeSyntax to declare a union:

April 11, 2023 90

union tag { type member-name;

type member-name; type member-name; . .

} variables;

Page 91: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 24 [Derived Types]

Unions

Session # 24 [Derived Types]

Unions

UnionsACCESSING UNION FIELDS

To access the fields of a union, use the dot operator(.) just as you would for a structure.Example:

union data{ int x;

float f;} myData;

int main(){ myData.x = 42;

printf("Here is the Data:\n%i\n%.3f\n”,myData.x, myData.f );

myData.f = 101.357;

printf("Here is the Data:\n%i\n%.3f\n“, myData.x, myData.f );}

UnionsACCESSING UNION FIELDS

To access the fields of a union, use the dot operator(.) just as you would for a structure.Example:

union data{ int x;

float f;} myData;

int main(){ myData.x = 42;

printf("Here is the Data:\n%i\n%.3f\n”,myData.x, myData.f );

myData.f = 101.357;

printf("Here is the Data:\n%i\n%.3f\n“, myData.x, myData.f );}

April 11, 2023 91

Page 92: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 25 [Pre Processor Directives]

Introduction to Pre Processor Directives

Session # 25 [Pre Processor Directives]

Introduction to Pre Processor Directives

Preprocessing Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros – Format of preprocessor directives Lines begin with # Only whitespace characters before directives on a line #include Preprocessor Directive ( Copy a specified file included in place of the directive ):

used for Programs with multiple source files to be compiled together

Preprocessing Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros – Format of preprocessor directives Lines begin with # Only whitespace characters before directives on a line #include Preprocessor Directive ( Copy a specified file included in place of the directive ):

used for Programs with multiple source files to be compiled together

April 11, 2023 92

Page 93: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 35 [Pre Processor Directives]

Introduction to Pre Processor Directives

Session # 35 [Pre Processor Directives]

Introduction to Pre Processor Directives

#define Preprocessor Directive ( Preprocessor directive used to create symbolic constants and macros – Symbolic constants ):

When program compiled, all occurrences of symbolic constant or macro replaced with replacement text

Format: #define identifier replacement-text

Example: #define PI 3.14159 – Everything to right of identifier replaces text

Replaces “ PI ” with " = 3.14159 “

Note : Cannot redefine symbolic constants once they have been created

#define Preprocessor Directive ( Preprocessor directive used to create symbolic constants and macros – Symbolic constants ):

When program compiled, all occurrences of symbolic constant or macro replaced with replacement text

Format: #define identifier replacement-text

Example: #define PI 3.14159 – Everything to right of identifier replaces text

Replaces “ PI ” with " = 3.14159 “

Note : Cannot redefine symbolic constants once they have been created

April 11, 2023 93

Page 94: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 25 [Pre Processor Directives]

Introduction to Pre Processor Directives

Session # 25 [Pre Processor Directives]

Introduction to Pre Processor Directives

Macros A macro without arguments is treated like a symbolic constant A macro with arguments has its arguments substituted for replacement text, when the macro is expanded

Performs a text substitution No data type checking

Macro Examples

Macros A macro without arguments is treated like a symbolic constant A macro with arguments has its arguments substituted for replacement text, when the macro is expanded

Performs a text substitution No data type checking

Macro Examples

April 11, 2023 94

Macro definition Macro call Replacement form#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); area = (3.14159 * (4) * (4));

‘’ area = CIRCLE_AREA( c + 2 ); area= 3.14159 * (c + 2) * (c +2);

#define RECT_AREA(x, y) ((x)*(y)) area=RECT_AREA((a+4),(b+7)); area = ( ( a + 4 ) * ( b + 7 ) );

Page 95: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #26 [File I/O]

Introduction to File I/O

Session #26 [File I/O]

Introduction to File I/O

C File I/O and Binary File I/OWhen accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file). example: FILE *fp;To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode); The modes are…

C File I/O and Binary File I/OWhen accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file). example: FILE *fp;To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode); The modes are…

April 11, 2023 95

symbol functionality mode functionality

r open for reading r+ open for reading and writing, start at beginning

w open for writing (file need not exist)

w+ open for reading and writing (overwrite file)

a open for appending (file need not exist)

a+ open for reading and writing (append if file exists)

Page 96: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #26 [File I/O]

File Process

Session #26 [File I/O]

File Process

Example of using fopen:FILE *fp;fp=fopen("c:\\test.txt", "r"); [open test.txt for reading in text mode]

To close a function you can use the functionint fclose(FILE *a_file); [returns zero if the file is closed successfully ]

Example of fclose : fclose(fp);

you can use fprintf and fscanf ,to working with text I/O and they are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. Example:

FILE *fp;fp=fopen("c:\\test.txt", "w");fprintf(fp, "Testing...\n");

fgetc(): [read a single character from a file] int fgetc (FILE *fp); fputc(): [write a character at a time into a file ]

int fputc( int c, FILE *fp );

Example of using fopen:FILE *fp;fp=fopen("c:\\test.txt", "r"); [open test.txt for reading in text mode]

To close a function you can use the functionint fclose(FILE *a_file); [returns zero if the file is closed successfully ]

Example of fclose : fclose(fp);

you can use fprintf and fscanf ,to working with text I/O and they are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. Example:

FILE *fp;fp=fopen("c:\\test.txt", "w");fprintf(fp, "Testing...\n");

fgetc(): [read a single character from a file] int fgetc (FILE *fp); fputc(): [write a character at a time into a file ]

int fputc( int c, FILE *fp );April 11, 2023 96

Page 97: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #26 [File I/O]

Binary Files

Session #26 [File I/O]

Binary Files

Binary I/O [ fread() ,fwrite() ]These are dealing with blocks of memories - usually arrays. Because they accept pointers,

you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

Declarations :size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Example: FILE *fp;fp=fopen("c:\\test.bin", "wb");char x[10]="ABCDEFGHIJ";fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

Binary I/O [ fread() ,fwrite() ]These are dealing with blocks of memories - usually arrays. Because they accept pointers,

you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

Declarations :size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Example: FILE *fp;fp=fopen("c:\\test.bin", "wb");char x[10]="ABCDEFGHIJ";fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

April 11, 2023 97

Page 98: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #27 [ C Standard Library]

math.h

Session #27 [ C Standard Library]

math.h

April 11, 2023 98

Page 99: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session #27 [ C Standard Library]

ctype.h

Session #27 [ C Standard Library]

ctype.h

April 11, 2023 99

Page 100: Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine

Session # 27[ C Standard Library]

stdlib.h

Session # 27[ C Standard Library]

stdlib.h

April 11, 2023 100