C PROGRAMMING NOTES FOR TU ENGINEERING AND CSIT

 

chapters:

Chapter 1: Overview of Computer Software & Programming Language

What is Computer Software?

Computer Software is a collection of instructions and data that tell a computer how to work Ex: MS Office, Microsoft Windows, Linux,Chrome Browser, Facebook, Teams, etc..

What is System Software?

System software is software designed to provide a platform for other software Ex: Microsoft Windows, Mac Os, Linux, Android, etc…

What is Application Software?

Application software is software designed to perform a specific task Ex: Teams, MS Office, Facebook, etc…

Features of software

1) Functionality 2) Reliability 3) Efficiency 4) Maintainability 5) Usability 6) Portability 7) Accuracy

Programming Language

A programming language is a computer language programmers use to develop software programs or other sets of instructions for computers to execute. Programming Languages: C, C++,C#, Java, Python, etc…

Generation of Programming Language It has Five generations: a) First Generation Language b) Second Generation Language c) Third Generation Language d) Fourth Generation Language e) Fifth Generation Language

First Generation Language(1GL) -It is a low level language -It is also called machine language ie the code and instructions are directly given in ‘1’ & ‘0’ form -1GL or Machine language are directly understood by the computers so its processing is fast. -Writing codes in Machine language is difficult

Second Generation Language(2GL) -It is a low level language -It is also called Assembly language -Assembly language needs to be converted into Machine language and its conversion process is fast -Writing codes in Assembly language is easier than Machine language -Ex: Coding in microprocessor

Third Generation Language(3GL) -It is a high level language -It is high level language because It contains easy to read syntax that is easy for humans to understand -Writing codes in High level language is much easier -Ex: C, C++, Java

Fourth Generation Language(4GL) -It is a high level language -It is advancement upon 3GL -These are languages that consist of statements that are similar to statements in the human language. -It is used mainly in database programming and scripting. -Ex: Python, SQL, etc..

Fifth Generation Language(5GL) -It is a high level language (It is much intelligent) -Fifth-generation languages are designed to make the computer solve a given problem using constraints without the need of programmer -Fifth-generation languages are used mainly in artificial intelligence research. -Ex: Prolog

Prolog Constraints: a) Ram and Sita are best friends b) Ram and Sita both love same things c) Ram likes watching football

Can we conclude: Sita likes watching football? Result: Yes, Sita likes watching football

Chapter 2 : Problem Solving using Computer

Problem Analysis

Problem: -Problem is defined as the difference between an existing situation and a desired situation. -If a problem is solved by using machine called computer, then such process is called Problem Solving using Computer. -Before solving any problem you must first try to solve it manually. Unless you have a clear understanding of problem and the steps that should be followed to reach the solution you cannot solve the problem using machine. So, first try to get clear idea about the problem.

Steps for problem solving: a)Determine the nature of problem ( type of computation required ex: whether you need to perform addition or multiplication or both)

a)Apply each steps properly ( do not carry out the steps in wrong order ex: If addition has to be done before multiplication then do so and do not change their order else incorrect result might appear)

a)To ensure that everything happens in order, plan the program before writing it b) (ex: preparing Algorithm and flowchart before beginning program execution)

Algorithm development and Flowchart

Algorithm -Sequence of instructions designed in such a way that if the instructions are executed in the specified sequence, the desired result will be obtained. -In simple words, algorithm is the step that you should follow to solve a problem.

For ex: Your mother wants you to go to the market and bring a chicken. What will be its steps?

Step1: You will take the money

Step2: You will go to the market

Step3: You will buy the chicken

Step4: You will come back home

Characteristics of Algorithm 1)Each and every instruction should be precise and unambiguous (clear) 2)Each instruction should be such that it can be performed in a finite time 3)One or more instruction should not be repeated infinitely. This ensures that the algorithm will ultimately terminate 4)After performing the instructions, that is after the algorithm terminates, the desired results must be obtained

Problem : The attendance sheet of your class is given to you. Only those students with attendance of 70% or above are qualified to attend final examination (for them print ‘Q’ ) else print ‘NQ’. Write an algorithm to check whether a student is Qualified or not [Assume Total days of class as ‘TotalClass’]

Hint: Assume the total days a student is present as ‘TotalPresent’ Calculate the PresentPercentage of student : (TotalPresent / TotalClass)*100% If (PresentPercentage >= 70 ) print ‘Q’ else print ‘NQ’ Solution Step1: Start

Step2: Get the attendance of a student as ‘TotalPresent’

Step3: Calculate the ‘PresentPercentage’ as (TotalPresent/TotalClass) * 100%

Step4: If (PresentPercentage >= 70% ) print ‘Q’ Else print ‘NQ’ Step5: Stop
Problem: Write an algorithm to check whether a number entered by user is odd or even [075 Ashwin]

[Hint: If the number is divisible by 2 then its even else it is odd]

Importance of Algorithm: a)Gives the idea about problem and solution b)Easy to implement an algorithm rather than starting from scratch c)Proper Utilization of resources d)Writing algorithm improves thinking and reasoning abilities

Flowchart -A flowchart is a pictorial representation of an algorithm that uses boxes of different shapes to denote different types of instructions. -The actual instructions are written within these boxes using clear and concise statements. -These boxes are connected by solid lines having arrow marks to indicate the flow of operation.

Normally, an algorithm is first represented in the form of a flowchart and the flowchart is then expressed in some programming language to prepare a computer program.

Since a flowchart shows the flow of operations in pictorial form, any error in the logic of the procedure can be detected more easily.

Guidelines to draw Flowchart

1)Each flowchart must have one and only one Start object. 2)The flow of control must always enter an object from the top. 3)The flow of control must always leave an object from the bottom (except for Decision objects, which allow the flow of control to leave from the side). 4)The flow of control must not split.

Advantages of Flowchart 1)Improved Communication: Flowchart empowers entire teams to collaborate as they create, edit, and analyze flowcharts 2)Visual Clarity: People often can’t spend the necessary time reading complicated documents. Flowcharts can bring clarity to concepts that are otherwise difficult to understand. 3)Effective Analysis: The flowcharts can help you visually identify problems. 4)Problem Solving: After identifying a potential problem, programmers can know in which places they need to modify their code. 5)Documentation: Flowcharts may prove useful for simplifying otherwise difficult procedures. Flowchart Symbols Alt text

Terminal: The terminal symbol is used to indicate the beginning (START) and ending (STOP). It is the first symbol and last symbol in the program logic.

Input/Output: If there is a program instruction to input data from a disk, cardreader, or any other type of input device, that step will be indicated in the flowchart with an input/output symbol. Similarly, all output instructions whether it is output on a printer, magnetic tape, terminal screen or any output device, are indicated in the flowchart with an input/output symbol.

Processing: A processing symbol is used in a flowchart to represent arithmetic and data movement instructions. Adding, subtracting, multiplying and dividing are shown by a processing symbol

Flowlines: Flowlines with arrowheads are used to indicate the flow of operations. The normal flow of flowchart is from top to bottom and left to right.Flowlines should not cross each other

Decision: The decision symbol is used in a flowchart to indicate a point at which a decision has to be made and a branch to one of two or more alternative points is possible. The criteria for making the decision should be indicated clearly within the decision box.

Connector: Whenever a flowchart becomes complex enough that the direction of flowlines is confusing or it spreads over more than one page, it is useful to utilize the connector symbol


Problem: A student appeared in semester examination. There were total 5 subjects and the total marks of each subject was 100. Take the input data(marks of each subject), calculate the percentage and display output using Flowchart.

[Hint: To calculate the percentage : First calculate total marks obtained ‘TotalMarksObtained’ (TMO) Then calculate the total full marks ‘TotalFullMarks’ (TFM) Now calculate percentage as : Percentage = (TMO / TFM) * 100% ]

Alt text

Problem: Draw a flowchart to check whether a number entered by user is even or odd. [075 Ashwin]

Compilation and Execution

Compilation: The compilation is a process of converting the source code into object code. It is done with the help of the compiler. The compiler checks the source code for the syntactical errors, and if the source code is error-free, then it generates the object code. Alt text

The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.

Pre-processing: This source code is first passed to the preprocessor, and then the preprocessor expands this code. After expanding the code, the expanded code is passed to the compiler.

Compiling: The compiler converts the pre-processed code into assembly code.

Assembling: The assembly code is converted into object code by using an assembler.If the name of the source file is 'hello.c', then the name of the object file would be 'hello.obj'.

Linking: Mainly, all the programs written in C use library functions.The main working of the linker is to combine the object code of library files with the object

Execution: After the creation of an object code, the linker creates the executable file. The loader will then load the executable file for the execution.

Testing and Debugging

Debugging The process of finding and removing errors (also sometimes called buggs) from a program is known as debugging

One simple method of debugging is to place print statements throughout the program to display the values of variables. It displays the dynamics of a program and allows us to examine and compare the information at various points. Once the location of an error is identified and the error is corrected, the debugging statements may be removed.

Generally programmers commit three types of errors.They are

1.Syntax errors: -A syntax error is an error in the syntax. -Each function has its own rules, for ex: printf function requires text written inside ” ” which is present inside ( ). If any character is missed then it is called syntax error

2.Logic errors: -A logic error (or logical error) is a mistake in a program's source code that results in incorrect or unexpected behavior. -Ex: To calculate avg of 3 numbers we need to add three numbers and then divide the result by 3. But, if a programmer divides the result by 2 instead of 3 then it is logical error

3.Run-time errors: -A runtime error is a program error that occurs while the program is running -Ex:Divide by zero Null pointer assignment Data over flow

Testing -Testing is the process of reviewing and executing a program with the intent of detecting errors. -Testing can be done manually and computer based testing. -Manual testing includes code inspection by the programmer, codeinspection by a test group and a review by a peer group. -Computer based testing is done by computer with the help of compiler

Programming Documentation

Any written text, illustrations or video that describe a software or program to its users is called programming documentation. User can be anyone from a programmer, system analyst and administrator to end user.

These are some guidelines for creating the documents −

1)Documentation should be from the point of view of the reader 2)Document should be unambiguous 3)There should be no repetition 4)Industry standards should be used 5)Documents should always be updated

Advantages of Documentation These are some of the advantages of providing program documentation − 1)Keeps track of all parts of a software or program 2)Maintenance is easier 3)Programmers other than the developer can understand all aspects of software 4)Improves overall quality of the software

Chapter 3 : Introduction to ‘C’ Programming [3 hr]

Before starting anything else lets have a look at the structure of a C program Alt text

-The documentation section consists of a set of comment lines giving the name of the program, the author and other details -The link section provides instructions to the compiler to link function from the system library. -The definition defines all the symbolic constants. -There are some variables that are used in more than one function. Such variables are called global variables and are declared in global declaration section that is outside of all the function. -Every C program must have one main( ) function section. This section consists two parts: declaration part and executable part The declaration part declares all the variables used in the executable part. These two parts must appear between the opening and the closing braces. -The subprogram section contains all the user-defined functions that are called in the main ( ) function

Character Set C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program elements (e.g. constants,variables, operators, expressions, etc).

The special characters are listed below: + - * / = % & # ! ? ^ “ ' ~ \ | < > ( ) [ ] { } : ; . , -


Identifiers and Keywords

C Tokens: In a C program the smallest individual units are known as C tokens. C has six types of tokens: 1. Identifiers e.g.: x area __ temperature PI 2. Keywords e.g.: int float for while 3. Constants e.g.: -15.5 100 4. Strings e.g.: “ABC” “year” 5. Operators e.g.: + - * 6. Special Symbols e.g.: ( ) [ ] { }

Identifiers: Identifiers are names that are given to various program elements, such as variables, functions and arrays. Identifiers consisted of letters and digits, in any order, except that first character must be a letter.

Rules for Identifier: 1.First character must be an alphabet (or Underscore). 2.Must consist of only letters, digits or underscore. 3.Only first 31 characters are significant. 4.Cannot use a keyword. 5.Must not contain white space.

The following names are valid identifiers: X a12 sum_1 _temp name area tax_rate TABLE

The following names are not valid identifier for the reason stated 4th The first character must be letter “X” Illegal characters (“) Order-no Illegal character (-) Error flag Illegal character (blank space)

Keywords: There are certain reserved words, called keywords that have standard, predefined meanings in C. These keywords can be used only for their intended purpose; they cannot be used as programmer-defined identifiers. The standard keywords are

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

The keywords are all lowercase. Since upper and lowercase characters are not equivalent, it is possible to utilize an uppercase keyword as an identifier. Normally, however, this is not done, as it is considered a poor programming practice.


Data Types

C supports several different types of data, each of which may be represented differently within the computer memory. There are three cases of data types: 1.Basic data types (Primary or Fundamental) e.g.: int, char 2.Derived data types e.g.: array, pointer, function 3.User defined data types e.g.: structure, union, enum

The basic data types are also known as built in data types. The basic data types are listed below. Typical memory requirements are also given:

Data typeTypical Memory requirement
char1 byte(Letter / character)
Int2 bytes(Integer number)
float4 bytes(1 word)(Decimal number)
double8 bytes(2 word)(Decimal + memory space is large)

[ next type of data is string. String is nothing but just array of characters, i.e a string variable can hold more than one character ] ex: char c[10];

More on string example: char text[]=“California”;

The declaration could also have been written as: char text [11] = “California” ; -> at the end of string data ‘ \0 ’ is automatically appended to indicate the end of string where size of the array is explicitly specified. In such situations, it is important, however, that the size be specified correctly.

If the size is too small, eg. char text [10] = “California” ; the character at the end of the string (in this case, the null character) will be lost.

If the size is too large e.g. char text [20] = “California” ; the extra array elements may be assigned zeros, or they may be filled with meaningless characters


Constants & Variables

Constants Constants in C refer to fixed values that do not change during the execution of a program. There are four basic types of constants in C. They are integer constants, floating point constants, character constants and string constants.

The following rules apply to all numeric type constants(integer, float). 1.Commas and blank spaces cannot be included within the constants. 2.The constant can be preceded by a minus (-) if desired. 3.The value of a constant cannot exceed specified minimum and maximum bounds.

Variable A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory.

A C program contains the following lines:

int a,b,c ;
char d ;
- - - - -
- - - - -
a = 3 ;
b = 5 ;
c = a + b ;
d = ‘a’ ;
- - - - -
- - - - -
a = 4 ;
b = 2 ;
c = a – b ;
d= ‘w’;

The first two lines are not type declaration which state that a, b and c are integer variables, and that d is a character type. Thus, a, b and c will each represent an integer-valued quantity, and d will represent a single character.

The next four lines cause the following things to happen: the integer quantity 3 is assigned to a, 5 is assigned to b and the quantity represented by the sum a+b (.e. 8) is assigned to c. The character ‘a’ is assigned then assigned to d.In the third line within this group, the values of the variables a and b are accessed simply by writing the variables on the right-hand side of the equal sign.

The last four lines redefine the values assigned to the variables as the integer quantity 4 is assigned to a, replacing the earlier value, 3; then 2 is assigned to b, replacing the earlier value, 5; The difference between a and b (i.e. 2) is assigned to c, replacing the earlier value 8. Finally the character ‘w’ is assigned to d, replacing the earlier character, ‘a’.

Declaration of variable A declaration associates a group of variables with a specific data type. A declaration consists of a data type, followed by one or more variable names, ending with a semicolon. int a; [this is declaration] Each array variable must be followed by a pair of square brackets,containing a positive integer which specifies the size (i.e. the number of elements) of the array. char text [80] ;

A C program contains the following type declarations: int a, b, c ; float root1, root2 ; char flag, text[80];

Thus, a, b and c are declared to be integer variables, root1 and root 2 are floating variables, flag is a char-type variable and text is an 80-element, char-type array. These declarations could also have been written as follows:

int a ;
int b ;
int c ;
float root1 ;
float root2 ;
char flag ;
char text [80] ;

A C program can also contain following type declarations.

int c = 12 ;
char star = ‘*’ ;
float sum = 0. ;
double factor = 0.21023e-6

Thus, c is an integer variable whose initial value is 12, star is a char type variable initially assigned the character ‘*’, sum is a floating point variable whose initial value is 0 and factor is double precision variable whose initial value is 0.21023 × 106.


Preprocessor Directives

-Preprocessor directives are the special instructions which are executed before code passes through the compilation process.

-Every C programs are checked for the preprocessor statements before compiling and if any preprocessor statements are used in the program then they are processed first and then preprocessed program is handed over to the compiler for further compilation.

-It begins with hash (#) symbol and do not require semicolon at the end.

One of the most important preprocessor directive is #include which is used for including header file. For examples:

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

Some other Preprocessor directives are: #define, #undef etc..

#define is used to define constant in the program ex: #define PI 3.1415926 #define Capital “kathmandu”

[ What is #include used for? ] The #include preprocessor directive is used to paste code of given file into current file.


Escape Sequence

Many programming languages support a concept called Escape Sequence. When a character is preceded by a backslash (), it is called an escape sequence and it has a special meaning to the compiler.

Some escape sequences:

CharacterEscape Sequence
Horizontal tab\t
New Line\n
Backslash\\


Operators & Statements

Operator Operators are those symbols that perform some specific task. Like, when we add two numbers we generally use '+' sign. In programming also, to perform some specific task, compiler has assigned some specific symbols. These symbols are called operators.

Operand The data items that operators act upon are called operands. Some operators require one operand to act upon, whereas some require more than one.

Expression An expression is a combination of operands and operators written according to the syntax of language.

Operator, Operand and Expression example Alt text

Some operator works on a single operand while some works on two operand and some on even more. Depending upon the number of operands that they operate, operators can be classified as: a.Unary Operator (1 operand) b.Binary Operator (2 operand) c.Ternary Operator (3 operand)

a) Unary Operator: Operators that act upon a single operand to produce a new value

Unary Minus (-) : The most common unary operator is unary minus, where a numerical constant, variable, or expression is preceded by a minus sign. For example: -23.4, -34 etc.

Increment Operator (++) : The increment operator causes its operand to be incremented by 1. This operator can be used in two ways i.e. as a post increment or pre increment.

a)Post increment: If a = 2 then a++ causes value of a to be incremented by one i.e. after executing a++ we get value of a =3.

b)Pre Increment: If a = 2 then ++a also causes value of a to be incremented by one i.e. after executing ++a we get value of a =3.

Things to know

Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in a expression. In the Pre-Increment, value is first incremented and then used inside the expression. Syntax: a = ++x; Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression.

Post-increment operator: A post-increment operator is used to increment the value of variable after executing expression completely in which post increment is used. In the Post-Increment, value is first used in a expression and then incremented. Syntax: a = x++; Here, suppose the value of ‘x’ is 10 then value of variable ‘a’ will be 10 because old value of ‘x’ is used.

Decrement Operator (--) : The decrement operator causes its operand to be decremented by 1. This operator can be used in two ways i.e. as a post decrement or pre decrement. a)Post Decrement: If a = 2 then a-- causes value of a to be decremented by one i.e. after executing a-- we get value of a =1. b)Pre Decrement: If a =2 then --a also causes value of a to be decremented by one i.e. after executing --a we get value of a =1.

sizeof() Opearator: sizeof is keyword in C which is used to find size occupied by different data types in memory. For example: a. sizeof(int) gives value of 2. b. If we declare variable like: float x; then sizeof(x) gives 4.

b) Binary Operator: Binary operators act upon a two operands to produce a new value. Binary operators can be classified into following categories: i) Arithmetic Operator ii) Relational Operator iii) Logical Operator iv) Assignment Operator

i) Arithmetic Operator

OperatorsPurposes
+Addition
-Subtraction
*Multiplication
/Division
%Modulus(remainder after integer division

ii) Relational Operator

OperatorsPurposes
<less than
<=less than or equal to
>greater than
>=greater than or equal to
==is equal to
!=is not equal to

iii) Logical Operator

OperatorsPurposes
&&and
||or
!not

iv) Assignment Operator

OperatorsPurposes
=used to assign value to variable
+=addition and assignment
-=subtraction and assignment
*=multiplication and assignment
/=division and assignment

(Note: The result of a logic ‘and’ operation will be true only if both operands are true where as the result of a logic ‘or’ operation will be true if either operand is true or if both operands are true.)

c) Ternary Operator: It acts upon three operands to produce a new value. It is also called Conditional Operator It is of the form: (condition ? Truecase : Falsecase)

Ex: Write a program to find the smallest number among two LOGIC: int n1, n2, smallest ;
smallest = (n1<n2) ? n1 : n2 ;

This can be achieved by using the if_else statement as follows: if (n1<n2) smallest = n1 ; else smallest = n2 ;


Operator Precedence and Associativity

Operator Precedence Operator precedence describes the order in which C evaluates different operators in a complex expression. In the expression y=10+5*20, which happens first? Addition or Multiplication?

Operator Associativity Operator associativity describes the order of execution of operators when they have same level of precedence. In the expression y = 12* 20/5, which happens first? Multiplication or Division?

Precedence and Associativity Table

OperatorsPrecedenceAssociativity
Parenthesis (), Brackets []1Left to Right
++, --, unary minus (-), unary plus (+)2Right to Left
*, /, %3Left to Right
+, -4Left to Right
<,>, <=,>=5Left to Right
= =, !=6Left to Right

Question: a)result = 2 + 3 * 5 What will be the answer: 25 or 17? solution:

  • has higher precedence than + so multiplication will be performed before addition

Try solving these: a) 34 + 12/4 - 45 ? b) 12 + 3 - 4 / 2 < 3 + 1 ? c) (2 + (3 + 2) ) * 10 ?

Solutions:




Chapter 4 : Input Output [2 hrs]

C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library has methods for input and output. The standard input functions are scanf( ),getchar( ), getch( ), gets( ), etc The standard output functions are printf( ), putchar( ), putch( ), puts( ), etc

Types of Input Output - Formatted I/O - Unformatted I/O

Formatted Input & Output

-Used to take one or more inputs from user at console(computer screen) -Also allows to display one or multiple values to user at console. Example:

    #include <stdio.h> 
    int main( ) 
    { 
    char item[20] ; 
    int partno ; 
    float cost ; 
    - - - - - - 
    scanf (“%s %d %f”, item, &partno, &cost) ; 
    - - - - - -  
    }

Formatted Input : scanf (scan formatted) Formatted Output : printf (print formatted)

Formatted Input scanf() -The scanf() method reads value from the console. -Syntax: scanf(“%X”, &variableOfXType); where %X is the format specifier in C ( It tells the compiler what type of data is in a variable ) and & is the address operator in C

Data typeInput Syntax
Intscanf("%d", &intVariable);
Floatscanf("%f", &floatVariable);
Characterscanf("%c", &charVariable);
Stringscanf("%s", stringVariable);

Integer: Float: Input: scanf("%d", &intVariable); Input: scanf("%f", &floatVariable);

Character: String: Input: scanf("%c", &charVariable); Input: scanf("%s", stringVariable);

Formatted Input: Example1

    #include<stdio.h> 
    main( ) 
    { 
    char line[80];
    - - - - - 
    scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line) ; //formatted input
    - - - - - - 
    } 

Explanation of example1: If the string HIMALAYA COLLEGE OF ENGINEERING is entered from the standard input device when the program is executed, the entire string will be assigned to the array line since the string is comprised entirely of uppercase letters & blank spaces. If the string were written as Himalaya College of Engineering then only the single letter H would be assigned to line. Since the first lowercase letter ( in this case i) would be interpreted as the first character beyond the string

Formatted Input: Example2

    #include<stdio.h> 
    main( ) 
    { 
    char line [80]; 
    - - - - - 
    scanf (“ %[^\n]”, line) ; 
    - - - - - 
    }

Explanation of example2: A variation of this feature which is often more useful is to precede the characters within the square brackets by a circumflex (or caret). If the character within the brackets is simply the circumflex followed by a newline character, then string entered from the standard input device can contain any ASCII characters except the newline characters (line feed). Thus, the user may enter whatever he or she wishes and then presses the Enter Key. The Enter Key will issue the newline character, thus signifying the end of the string. % [characters] % [^characters]

% [character] mean that only characters specified in the brackets are permissible as input string.

For example: scanf(“%[a-z]”,address); will allow only the lowercase alphabets to be accepted.

% [^character] means exactly the opposite. That is, characters specified in the brackets are not permissible as input string. Reading of the string will terminate as one of those characters are encountered.

Formatted Input: Example3

    #include<stdio.h> 
    main( ) 
    { 
    int a, b, c ;
    scanf ("%3d %3d %3d", &a, &b, &c) ;
    printf("a:%d \t b:%d \t c:%d", a,b,c); 
    }

Input: 12 23 34 Output: a:12 b:23 c:34 Input: 123 234 345 Output: a:123 b:234 c:345 Input: 1234 234 345 Output: a:123 b:4 c:234 Input: 12345 45 61 Output: a:123 b:45 c:45 Input: 1234567 12 32 Output: a:123 b:456 c:7

Formatted Output -Prints the value passed as parameter to it on console(screen) -Printf is used for formatted output. -Syntax: printf(“%X”, variableOfXType);

Integer: Output: printf("%d", intVariable); Float: Output: printf("%f", floatVariable); Character: Output: printf("%c", charVariable); String: Output: printf("%s", stringVariable)

[NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it. ] int i = printf("studytonight"); In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i, because studytonight has 12 characters.]

Formatted Output: Example1

    int main()
    {
    float a=345.567123;
    printf("%f", a);
    }

Output:345.567123

printf(“%9f”, a);                printf(“%12f”, a);

Output:345.567123                Output:  345.567123
                                (_ _ _ _ _ _ _ _ _ _ _ _)
                                       (_ _ 345.567123)(right justified)


printf(“%.4f”, a);                printf(“%-12f”, a);

Output:345.5671                 Output: 345.567123
                                (_ _ _ _ _ _ _ _ _ _ _ _)
                                (345.567123 _ _)(left justified)

Alt text

Floating-point format specifier : %f, %e or %E

    int main() 
    { 
    float a = 12.67; 
    printf("%f \n", a); 
    printf("%e \n", a); 
    return 0; 
    }

Output: 12.670000
1.267000e+01

Octal number for integer : %o

    #include <stdio.h> 
    int main() 
    { 
    int a = 67; 
    printf("%o \n", a);     
    return 0; 
    }

Output: 103

Unsigned Hexadecimal for integer: %x, %X

    #include <stdio.h> 
    int main() 
    { 
    int a = 15; 
    printf("%x\n", a); 
    return 0; 
    } 

Output: f


Unformatted Input Output

-Unformatted functions do not allow user to read or display data in desired format.
-It basically deals with a single character or a string of characters. -The functons getchar( ), putchar( ), gets( ), puts( ), getch( ), getche( ), putch( ) are considered as unformatted functions.

getchar( ) and putchar (): getchar: -The getchar( ) function reads a character from a standard input device. -The general syntax is: character_variable = getchar( );

ex:

    char ch;
    printf(“Enter any character”);
    ch=getchar();    

writing scanf(“%c”, &ch) is similar to ch=getchar()

where charactervariable is a valid C char type variable. When this statement is encounted, the computer waits until a key is pressed and assign this character to charactervariable.

putchar(): -The putchar( ) function displays a character to the standard output device. -The general syntax of putchar( ) function is: putchar(character_variable)

writing printf(“%c”, ch) is similar to putchar(ch)

getch( ), getche( ) and putch( ):

getch(), getche() -getch( ) and getche( ) reads single character the instant it is typed without waiting for the enter key to be hit. -The difference between them is : getch( ) reads the character typed without echoing(displaying) it on the screen, while getche( ) reads the character and echoes (displays) it on the screen.

-Syntax: syntax of getch( ): charactervariable = getch( ) ; syntax of getche( ) is: charactervariable = getche( ) ;

putch() -The putch( ) function prints a character onto the screen. -Syntax: putch(character_variable) ;

gets( ) and puts( ): gets() -Used to read a string containing whitespaces, until a newline character is encountered. -Offers an alternative function of scanf( ) function for reading strings. -Unlike scanf( ) function, it reads whitespaces. -Syntax: gets(string_variable) ;

puts() -used to display a string onto the console(screen). -syntax : puts (string _variable)

This prints the string value of string_variable and then moves the cursor to the beginning of the next line on the screen.



Chapter 5 : Control Statements

Introduction

-The statements which alter the flow of execution of the program are known as control statements. -In the absence of control statements, instructionare executed in the same order in which they appearSometimes, we may want to execute some statements several times. -Sometime we want to use a condition for executing only a part of program. So, control statements enable us to specify the order in which various instruction in the program are to be executed.

There are two types of control statements: 1Decisions: if, if…else, nested if….else, switch 2Loops : for, while, do-while

Decision

Since decision making statements control the flow of execution, they also fall under the category of control statements. Following are decision making statements: -if statements -if….else statements -else if statement -Nested if…else statement -switch statement -Jump Statements: -break -continue -goto

if statement

-The most simple decision making statement. -Used to decide whether a certain statement or block of statements will be executed or not.

Syntax:

    if (condition) 
{ 
// Statements to execute if 
// condition is true 
} 

Here, condition after evaluation will be either true or false. If the value is true then it will execute the block of statements below it otherwise not.

Flowchart Alt text

C program to illustrate If statement

#include <stdio.h> 
int main() 
{ 
    int i = 10; 
    if (i > 15) 
        { 
        printf("10 is less than 15"); 
        } 
    printf("I am Not in if"); 
} 

Output: I am Not in if


If…else statement

-With if statement we can do nothing when the condition is false. -We can use the else statement with if statement to execute a block of code when the condition is false.

Syntax:

        if (condition) 
{ 
// Executes this block if 
// condition is true 
} 
else 
{ 
// Executes this block if 
// condition is false 
}

Flowchart Alt text

C program to illustrate If…else statement

    #include <stdio.h> 
    int main() 
    { 
    int i = 20; 
    if (i < 15) 
    {
                    printf("i is smaller than 15"); 
            }
            else 
            {
                    printf("i is greater than 15"); 
            }

    } 

Output: i is greater than 15


else-if

-User can decide among multiple options.
-As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. -If none of the conditions are true, then the final else statement will be executed.

Syntax:

    if (condition1) 
        {
        statement ; 
        }
    else if (condition2) 
        {
        statement ;
}
    else if (condition3)
        {
            statement ;
        }
. 
. 
    else    
        { 
            statement;
        }

Flowchart Alt text

C program to illustrate else if statement

#include <stdio.h> 
int main() 
{ 
int i = 20; 
if (i == 10) 
    printf("i is 10");
else if (i == 15) 
    printf("i is 15"); 
else if (i == 20) 
    printf("i is 20"); 
else 
        printf("i is not in our category"); 
} 

Output: i is 20


Nested if…else

-When a series of decision is required, nested if-else is used.

Let's write a program to illustrate the use of nested if-else.

#include<stdio.h> 
int main() 
{ 
    int num=40; 
    if(num<10) 
    { 
    if(num==1) 
    {   
    printf("The value is:%d\n",num); 
    } 
    else 
    { 
    printf("The value is greater than 1"); 
    } 
    } 
    else 
    { 
        if(num<20) 
        {   
        printf("The value is less than 20",num); 
        } 
        else 
        { 
        printf("The value is greater than 20"); 
            } 
    } 

    }   

Output: The value is greater than 20

Flowchart Alt text


switch case:

-Switch statement allows a variable to be tested for equality against a list of values. General syntax:

switch (expression)  
{ 
case constant-expression1  :     
statement(s);             
break; /* optional */ 

case constant-expression2  :     
statement(s);             
break; /* optional */ 

case constant-expression3  : 
statement(s); 
break; /* optional */ 


/* you can have any number of case statements */ 

default :  /* Optional */         
statement(s);             
}

Explanation Here, switch, case and default are keywords. The ‘expression’ following the switch keyword can be any C expression that yields an integer value or a character value.

Firstly, the switch expression is evaluated then value of this expression is compared one by one with every case constant. If the value of expression matches with any case constant, then all statements under that particular case are executed. If none of the case constant matches with the value of the expression then the block of statements under default is executed Alt text

Program to understand the switch control statement

#include<stdio.h> 
main( ) 
{ 
int choice ; 
printf (“Enter your choice :” ) ; 
scanf (“%d”, & choice) 

switch(choice) 
{ 
    case 1 :        // if (choice == 1)
    printf (“first\n”) ; 
    case 2 :        // if (choice == 2)
    printf (“second\n”) ; 
    case 3 :        
    printf (“third\n”) ; 
    default :
    printf (“wrong choice\n”) ; 
} 
} 

Output: Enter your choice : 2

Second Third Wrong Choice

Explanation Here value of choice matches with second case so all the statements after case 2 are executed sequentially. The statements of case 3 and default are also executed in addition to the statements of case2. This is known as falling through cases Suppose we don’t want the control to fall through the statements of all the cases under the matching case, then we can use break statement.

Break statement: -Used inside lops and switch statements. -Used to terminate the loop. -It causes an immediate exit from that loop in which this statement appears.

It can be written as (i.e. general syntax) : break ;

If a break statement is encountered inside a switch, then all the statements following break are not executed and the control jumps out of the switch.

Program to understand the switch with break statement

#include<stdio.h> 
int main( ) 
{ 
int choice ;
printf (“Enter your choice : ”) ; 
scanf (“%d”, & choice) ; 

switch (choice)
{ 
    case1: 
    print (“First\n”) ; 
    break ; /* break statement */ 
    case2: 
    printf(“Second\n”) ; 
    break ; 
    case3: 
    printf (Third\n”) ; 
    break ; 
    default : 
    printf (“Wrong choice\n”) ; 
}/*end of switch*/

 } /* End of main( ) */ 

Output: Enter your choice : 2

Second

Program to perform arithmetic calculation on integers

#include<stdio.h> 
int main( ) 
{ 
char op ; 
int a, b ; 

printf (“Enter two numbers :”) ; 
scanf (“%d%d, &a, &b) ; 

printf(“Enter the arithmetic operator:”);
scanf(“%c”,&op);
switch (op) 
{ 
    case ‘+’ : 
    printf (“Result = %d\n”, a+b) ; 
    break ; 
    case ‘-‘ : 
    printf (“Result = %d\n”, a-b) ;
    break; 
    case ‘*’ : 
    printf (“Result = %d\n”, a*b) ; 
    break;
    case ‘/’ :
    printf (“Result = %d\n”, a/b) ; 
    break;
    case ‘%’ :
    printf (“Result = %d\n”, a%b) ; 
    break;
    default: 
    printf (“Enter your valid operation”) ; 
} /* end of switch */ 

} /* end of main( ) */

Continue statement: -Used to bypass the remainder of the current pass through a loop. -The loop does not terminate when a continue statement is encountered. Instead the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop.

The general syntax : continue ;

Program to demonstrate continue statement

#include<stdio.h>
int main( )
{
int i, num ;
printf (“\n Enter a number :”) ;
scanf (%d”, &num) ;

printf (“\n The even numbers from 2 to %d are : \n”, num) ;

for (i=1, ; i<=num ; i++)
{ 
    if( i%2 != 0 )  
        continue ;
    printf (“\t%d”, i) ;    
} /* end of for loop */

} / * end of main( ) */

Output: Enter a number : 20 The even numbers from 2 to 20 are: 2 4 6 8 10 12 14 16 18 20

goto statement: -Used to alter the normal sequence of program execution by unconditionally transferring control to some other part of the program. -The goto statement transfers the control to the labeled statement somewhere in the current function. The general syntax of goto statement:

goto label ;
 - - - - -
 - - - - - 
label : 
statement ; 
- - - - - 
- - - - - 

Explanation Here, label is any valid C identifier and it is followed by a colon. Whenever, the statement goto label, is encountered, the control is transferred to the statement that is immediately after the label. Generally, the use of goto statement is avoided as it makes program illegible and unreliable. This statement is used in unique situations like -Branching around statements or group of statements under certain conditions -Jumping to the end of a loop under certain conditions, thus bypassing the remainder of loop during current pass. -Jumping completely out of the loop under certain conditions, terminating the execution of a loop.

Program to print whether the number is even or odd

#include<stdio.h> 
int main( ) 
{ 
int n ; 
printf( “Enter the number :”) ; 
scanf (“%d”, &n) ; 

if (n%2 = = 0) 
    goto even ; 

else 
    goto odd; 

even : 
    printf (“Number is even”) ; 
    goto end ;

odd :
    printf (“Number is odd”) ;

end :
printf (“\n”) ;
}

Output: Enter the number : 6 Number is even.


Loops

-Loops are used when we want to execute a part of program or block of statement several times. (So, a loop may be defined as a block of statements which are repeatedly executed for a certain number of times or until a particular condition is satisfied. ) -Each loop consists of two segments, one is known as the control statement and the other is the body of the loop. -The control statement in loop decides whether the body is to be executed or not. -Depending on the position of control statement in the loop, loops may be classified either entrycontrolled loop or exitcontrolled loop. -While and For are entrycontrolled loops where as do…while is exitcontrolled loop.

There are three types of loop statements in C: 1. For 2. While 3. Do…while


For loop

-Useful to execute a statement for a number of times. -When the number of repetitions is known in advance, the use of this loop will be more efficient. -Thus, this loop is also known as determinate or definite loop.

The general syntax:

for (counter initialization ; test condition ; update expression) 
{                                 
| * body of loop * |
 }                                

Ex: for ( i=0 ; i<10 ; i++ )

Flowchart of for loop: Alt text

Algorithm example of for loop: Suppose you are given a number. Write an algorithm to find first 10 multiples of that number.

Step1: Start

Step2: Take input ‘number’ from user

Step3: Declare a control variable ‘i’ and set it to 0 (i=0)

Step4: Declare a variable ‘result’ and set it to 0 (result = 0)

Step5: result = result + number

Step6: If (i<10) then print ‘result’ make i=i+1 and goto Step5
Else goto Step7

Step7: Stop

Write a program to calculate the factorial of a number using For Loop ( Factorial of 5 = 1x2x3x4x5=120, Factorial of 40 = 1x2x3x4x…x38x39x40 )

Source Code:

#include <stdio.h>

void main()
    {
        int num, i ,fact;
        fact=1;
        printf(“Enter the number whose factorial you want to calculate:”);
        scanf(“%d”, &num);

        for ( i=1; i<=num ; i++)    
        {               
                fact = fact*i;          
        }                   

        printf(“The factorial of given number is: %d”, fact);
    }

Alt text

WAP to add the digits of a 5 digit number (Hint: say, number=23145, sum=0 Create a new variable ‘temp’ temp = number % 10
sum=sum+temp
Number = number / 10
)


While Loop

The general syntax:

while(condition) 
{ 
statement ; /* body of the loop */ 
- - - - - - - 
}

How does While loop work? -The while loop evaluates the test expression inside the parenthesis (). -If the condition is true, statements inside the body of while loop are executed. -Then, the condition is evaluated again. -The process goes on until the condition is evaluated to false. -If the condition is false, the loop terminates (ends).

Flowchart of While loop Alt text

Print numbers from 1 to 5 using while loop

    #include <stdio.h> 
    int main() 
    { 
        int i = 1; 
        while (i <= 5) 
       {    
                printf("%d\n", i);         
            i=i+1;          
        } 
    }

Here, we have initialized i to 1 -When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2. -Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3. -This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be false and the loop terminates.

WAP to separate each digits of a 3 digit number entered by the user

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int num,temp;

        printf("Enter a 3 digit number\n");
        scanf("%d", &num);

        printf("\nSeparated digits are:\n");    
        while(num>0)                
        {
            temp=num%10;        
            printf("%d\n", temp);           
            num=num/10;     
        }                   

    }

Alt text


do…while Loop

-The do..while loop is similar to the while loop with one important difference (the body of do…while loop is executed at least once. Only then, the condition is evaluated)

The syntax of the do…while loop is:

do
     { 
// the body of the loop 
-----------------

        } while (condition);

How does do…while work? -The body of do…while loop is executed once. Only then, the test expression is evaluated. -If the test expression is true, the body of the loop is executed again and the test expression is evaluated. -This process goes on until the test expression becomes false. -If the test expression is false, the loop ends.

Flowchart of do…while loop Alt text

Program to add numbers until the user enters zero

#include <stdio.h> 
int main() 
{ 
int number, sum = 0; 
do { 
printf("Enter a number: ");         
scanf("%d", &number);     
sum =sum+ number;            
     } while(number != 0) ;            

printf("Sum = %d",sum);             
return 0; 
}

Alt text

Alt text

Exam solution

Write a program to evaluate the following series until the difference between the two terms is less than 0.001 [070 Chaitra Old Back] s=x + (x^3 / 3!) + (x^5 / 5!) + …..

#include <stdio.h>
#include <math.h>
int main()
{
    int i,j;
    float x,first, second, diff,fact;

    printf("Enter the value of x\n");
    scanf("%f", &x);

    first=x;
    printf("%f\t",first);               //printing the first term

    for(i=3; i<=25; i=i+2)              //for second term both power and
    {                                   //factorial starts from 3 so i=3

        fact=1;
        for(j=1; j<=i; j++)
        {
            fact=fact*j;                //calculating: i!

        }
        second = (pow(x,i)/fact);       //calculating: (x^i)/i!

        diff=(second-first);

        if(diff<0)
        {
            diff=diff*(-1);             //taking absolute value
        }

        if(diff<0.001)                  //applying the condition
        {
            break;
        }
        else
        {
            printf("%f\t", second);   //printing rest of the terms
            first=second;
            continue;
        }

    }
}

Chapter 6: User Defined Function [4 hrs]


Functions

-A function is defined as a self contained block of statements that performs a particular task. -This is a logical unit composed of a number of statements grouped into a single unit -Each program has one or more functions. -The function main( ) is always present in each program which is executed first and other functions are optional.

Advantages of using Functions: The advantages of using functions are as follows:

-A difficult problem is divided into sub problems and then solved. This divide and conquer technique is implemented in C through functions.

-When some specific code is to be used more than once and at different places in the program, the use of function avoids repetition of that code.

-The program becomes easily understandable. It becomes simple to write the program and understand what work is done by each part of the program.

-Functions can be stored in a library and reusability can be achieved.

Types of Functions C program has two types of functions: -Library Functions -User defined functions

Library Functions: -These are the functions which are already written, compiled and placed in C Library. -They are not required to be written by a programmer. -For example: printf(), scanf(), sqrt(), getch(), etc.

User defined Functions: -These are the functions which are defined by user at the time of writing a program. -The user has choice to choose its name, return type, arguments and their types. -The job of each user defined function is as defined by the user. -A complex C program can be divided into a number of user defined functions. Alt text

Example of user defined function:

#include<stdio.h> 
double convert (int a)  ; /* function prototype */ 
void main( ) 
{ 
int c ; 
double d ; 
printf (“Enter temperature in Celsius: ”) ; 
scanf (“%d”, &c) ; 
d = convert(c) ; /*Function call*/ 
printf (“The Fahrenheit temperature of %d C = %lf F”,c, d) ; 

} 

double convert (int a) /* function definition */ 
{ 
double f ; 
f = 9.0*a/5.0+32.0 ; 
return f ; 
}

What is about main( ) function? The function main() is an user defined function except that the name of function is defined or fixed by the language. The return type, argument and body of the function are defined by the programmer as required. This function is executed first, when the program starts execution


Function Declaration or Prototype:

The function declaration or prototype is model or blueprint of the function. Function prototypes are usually written at the beginning of a program, ahead of any user-defined function including main(). Function prototypes provide the following information to the compiler. − The type of the value returned by the function. − The name of the function − The number and the type of arguments that must be supplied while calling the function

The general syntax of function prototype is returntype functionname (type1, type2, …., typen) ;

For example: int add (int n1, int n2) ; void display (int a) ;

Function definition: A function definition is a group of statements that is executed when it is called from some point of the program. The general syntax is:

return_type function_name (parameter1, parameter2, ....., parametern)
 {
 - - - - -
 statements ; 
 - - - - - 
} 

where, -return_type is the data type specifier of data returned by the function.

-function_name is the identifier by which it will be possible to call the function.

-Parameters(as many as needed) : Each parameter consists of a data type specifier followed by an identifier like any regular variable declaration. (for eg: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

-statements is the function’s body. It is a block of statements surrounded by braces{}.

-The first line of the function definition is known as function header.

for example:

int addition (int a, int b) /* function prototype */ 
main( ) 
{ 
int z ; 
z = addition (5,3) ; /*function call */ 
printf (“The result is%d”z) ; 
} 

int addition(int a, int b) /* function header */ 
{ 
int r; 
r = a+b 
return r; 
} 

Output: The result is 8

return statement: -The return statement is used in a function to return a value to the calling function. -It may also be used for immediate exit from the called function to the calling function without returning a value. -This statement can appear anywhere inside the body of the function. -There are two ways in which it can be used: return ; return (expression) ; where return is a keyword.

The first form of return statement is used to terminate the function without returning any value. In this case only return keyword is written

Program to understand the use of return statement

#include<stdio.h> 
void funct( int age, float ht) ; 
main() 
{ 
int age ; 
float ht ; 
printf (“Enter age and height :”) ; 
scanf (“%d%f”, &age, &ht) ; 
funct (age, ht) ;  // function calling 
} 

void funct (int age, float ht) 
{ 
if (age>25) 26
{ 
printf (“Age should be less than 25\n”) ; 
return ;
} 
if (ht<5) 6
{ 
printf (“Height should be more than 5\n”); 
return ; 
} 
print (“selected \n”) ; 
} 

The second form of return statement is used to terminate a function and return a value to the calling function. The value returned by the return statement may be any constant, variable, expression or even any other function call which returns a value. For example: return 1 ; return x++;
return (x+yz); return (3sum(a,b)) ;

Calling a function : A function can be called by specifying its name, followed by a list of arguments enclosed in parenthesis and separated by commas in the main() function. The syntax of the call if function returntype is void is: functionname (parameter name) ;

If function return int, float or any other type value then we have to assign the call to same type value like : variable = function_name(parameter) ; For example: m = mul(x, y) The type of m is same as the return type of mul function.

Actual and Formal Parameters: The arguments are classified into 1.Actual : When a function is called some parameters are written within parenthesis. These are known as actual parameter.

2.Formal parameters: Formal parameters are those who are written in function header.

For example:

main() 
{ 
- - - - - 
convert(c) ; //actual parameter 
- - - - - 
} 

For example:

double convert (int a) //formal parameter 
{

} 


Types of functions:

The functions can be classified into four categories on the basis of the arguments and return values: 1.Functions with no arguments and no return value 2.Functions with no arguments and a return value 3.Functions with arguments and no return value 4.Functions with arguments and a return value

Functions with no arguments and no return value: -When a function has no arguments, it does not receive any data from the calling function. -Similarly, when called function does not return a value, the calling function does not receive any data from it. -Thus, in such type of functions, there is no data to transfer between the calling function and the called function. -This function can be return as:

Void function_name( ) 
{ 
/* body of function */ 
} 

The keyword void means the function does not return any value

Program to illustrate the function with no arguments and no return values

void add( ) 
{ 
int a, b, sum ; 
printf (“\n Enter two numbers: \t”) ; 
scanf (“%d%d”, &a, &b) ; 
sum = a + b; 
printf (“\n The sum is %d”, sum) ; 
} 

void main( ) 
{ 

add( ) ; 

} 

Output: Enter two numbers: 3 4 ↵ The sum is 7


Functions with no arguments and a return value: -These type of functions do not receive any arguments but they can return a value. -This functions can be return as:

int func() ;
Void main() 
{ 
int r ; 
- - - - 
} 

int func(void) 
{ 
- - - - - - - - 
return (expressions) ;
} 

Program to illustrate function with no argument and a return value

#include<stdio.h> 
int add() ; 
void main () 
{ 
    int sum;
    sum = add();
printf (“ The sum is %d\n”,  sum); 
} 

int add() 
{ 
int n1, n2, sum ; 
printf (“Enter two numbers: \t”) ; 
scanf (“%d%d”, &n1, &n2) ; 
sum = n1+n2 ; 
return (sum) ; 
} 

Output: Enter two numbers: 3 4 ↵ The sum is 7
Functions with arguments and no return values: -These types of functions have arguments, hence the calling function can send data to the called function but the called function does not return any value.

-This functions can be written as:

void func (int, int) ;

void main( ) 
{
- - - - 
func(a, b) ; 
- - - - 
} 

void func( int c, int d) 
{
- - - - 
statements 
- - - - 
} 

Program to illustrate the functions with arguments but no return values

void add(int a, int b) ; 
void main( ) 
{ 
int a, b;
printf (“Enter two numbers: \t”) ; 
scanf (“%d%d”, &a, &b) ; 
add (a, b) ;
} 

void add(int a, int b) 
{ 
int sum ; 
sum = a+b; 
printf (“ \n The sum is %d”, sum) ; 
} 

Output: Enter two numbers: 3 4 ↵ The sum is 7


Functions with arguments and return values: -These types of functions have arguments, so the calling function can send data to the called function. -It can also return any values to the calling function using return statement. -This function can be written as:

int func (int, int) ; 
void main( ) 
{ 
int r ; 
- - - - - 
r = func(a,b) ; 
} 

int func(int a, int b) 
{ 
- - - - - - - - - - 
return(expression) ; 
} 

Program to illustrate the function with argument and return values

int add(int a, int b) ; 
void  main( ) 
{ 
int a, b, sum ; 
printf (“Enter two numbers : \t”) ; 
scanf (“%d%d”, &a, &b) ; 
sum = add(a, b) ; 
printf (“ln the sum is \t%d|, sum) ; 
} 
int add(int a, int b) 
{ 
int sum ; 
sum = a+b ; 
return sum ; 
} 

Output: Enter two numbers : 4 3 ↵ The sum is 7


Call by value & Call by reference

( Or Pass by value & Pass by reference)

Function call by value: -In this the value of actual parameter is passed to formal parameter when we call the function. -But actual parameters are not changed.

For eg:

#include<stdio.h> 
void swap(int, int) ; /*function prototype*/ 
void main( ) 
{ 
int x, y ; 
x = 10 ; 
y=20;
swap (x,y) ; /*function call by value */         
printf (“x = %d \n”, x) ;    
printf (“y=%d\n”, y);        
}

void swap (int a, int b) /*function definition */        
{
    int t ;
t = a ;        
a = b ;        
b = t ;        
}

Output x = 10 y = 20

Function call by reference: -In this type of function call, the address of variable is passed to the function as argument instead of actual value of variable. -For this, pointer is necessary

#include<stdio.h> 
void swap(int *, int * ) ; /* function prototype */ 
void main ( ) 
{ 
int x, y ;  //x & y are local variables for this function
x = 10 ; 
y = 20 ;
swap (&x, &y) ; /* function call by address */
printf (“x=%d\n”, x) ;        
printf (“y=%d\n”, y) ;        
}

void swap(int *a, int *b)    
{
int t ;            //a,b,t are local variables for this function
t = *a ;            
*a = *b ;        
*b = t ;    

}

Output: x = 20 y=10

Write a program in c to find out whether the nth term of the Fibonacci series is a prime number or not. Read the value of n from the user and display the result in the main. Use separate function to generate the nth term and separate function to check whether the number is prime or not [074 Ashwin]

#include <stdio.h>
#include <stdlib.h>

int fibo_term_generator(int a);
int prime_checker(int b);

int main()
{
    int n, value, final_value;
    printf("Enter the nth term:\n");
    scanf("%d", &n);

    value=fibo_term_generator(n);
    printf("\nThe nth term of fibonacc series is: %d\n\n", value);

    final_value=prime_checker(value);
    if(final_value == 1)
        printf("The nth term is prime");

    else
        printf("The nth term is not prime");

}

int fibo_term_generator(int a)
{
    /* this function generates the fibonacci series and return nth term */

    int n1,n2,n,temp;
    n1=1;
    n2=1;
    n=a;

     do
    {
        printf("%d\t", n1);
        temp=n1;
        n1=n2;
        n2=temp+n2;
        n--;
    }while(n>0);

    return temp;
}

int prime_checker(int b)
{
    int i, num, count;
    num=b;
    count=0;
    for(i=2; i<num ; i++)
    {
        if(num%i == 0)
        {
            count++;
        }
    }

    if(count>0)
        //printf("the number %d is not prime ", num);
        return 0;
    else
        //printf("the number %d is prime", num);
        return 1;
}


Concept of Local, Global and Static variable

Local variable: -Variables that are declared inside a function or block are called local variables. -They can be used only by statements that are inside that function or block of code -Local variables are not known to functions outside their own.

Here all the variables a, b, and c are local to main() function.

#include <stdio.h> 
int main () 
{ 
int a, b;     /* local variable declaration */ 
int c;         

a = 10; 
b = 20; 
c = a + b; 
printf ("value of a = %d, b = %d and c = %d\n", a, b, c); 
return 0; 
}

Global Variables: Global variables are defined outside a function, usually on top of the program. A global variable can be accessed by any function.

The following program shows how global variables are used in a program.

#include <stdio.h>

int g;    //global variable declaration

void next_function();
void  main()
{
    int a, b;   //local variable declaration

    a=10;
    b=20;
    g=a+b;

    printf("The value of g is:%d", g);
    next_function();
}

void next_function()
{
    g++;
    printf("\nNew value of g is:%d", g);
}

Output: The value of g is:30 New value of g is:31

A program can have same name for local and global variables but the value of local variable inside a function will take preference.

Static variables : Static variables are declared by writing keyword static in front of the declaration. static type var_name ;
-A static variable is initialized once and the value of a static variable is retained between function call. -If a static variable is not initialized then it is automatically initialized to O. -Its scope is local to the block in which the variable is defined. -The life time is global i.e. its value persists between different function calls.

Program with normal variable                Program with static variable
void increment( )                 void increment( ) 
{                         { 
int i = 1                     static int i = 1 
printf (“%d\n”, i ) ;                 printf (“%d\n”, i ) ; 
i++ ;                         i++ ;   
}                         }

main( )                     main( ) 
{                        { 
increment( ) ;                 increment( ) ; 
increment() ;                    increment( ) ; 
increment() ;                     increment( ) ; 
increment() ;                     increment( ) ; 
}                         } 

Output :     1                       1 
1                         2 
1                         3 
1                         4


Recursive function

-Recursion is the process of repeating items in a self-similar way. -In programming, if a program allows you to call a function inside the same function, then it is called a recursive function.

A function will be recursive, if it contains following features: -The function should call itself. -The function should have a stopping condition (base criteria)

To solve a problem using recursive method, two conditions must be satisfied. They are: -Problem could be written or defined in terms of its previous result. -Problem statement must include a stopping condition i.e. we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return.

Alt text

WAP to find the factorial of a number using recursive method factorial of 5 = 1x2x3x4x5 ->120

int factorial (int n) ;

void main( ) 
{ 
int num ,result; 
printf (“Enter a number : ”) ; 
scanf (“%d”, &num) ;         //4
result = factorial(num);        
printf (“The factorial is %d”, result) ; 
} 

int factorial (int n)                
{ 
if (n == 1)                                         
return (1) ;                                     
else                             
return (n*factorial(n-1)) ;      
} 

Output: Enter a number : 5 ↵ The factorial is 120

Alt text

Alt text

Program : Fibonacci number by recursion

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

int fib(int x) ;

void main() 
{ 
int i, n, no ; 
printf (“how many no in series : ”) ; 
scanf(“%d”, &n) ; 
for (i = 1 ; i<=n ; i++) 
{ 
no = fib(i) ; 
printf(“%d”, no) ; 
} 
}

int fib(int x)
{ 
if (x = = 0 | | x = =1) 
return 1 ; 
else 
return(fib(x-1) + fib(x-2)) ; 
} 

WAP to add the natural numbers using recursive method

long int add (int n) 
{ 
If(n = =0) 
return 0; 
else 
return (n + add(n-1)) ; 
} 

void main( ) 
{ 
int num ; 
printf (“Enter How many numbers : ”) ; 
scanf (“%d”, &num) ; 
printf (“The sum of natural number is %ld”, add(num)) ; 
} 

Output: Enter How many numbers :5 The sum of natural numbers is 15

WAP to check whether a number is armstrong or not using recursive function [073 Shrawan]

WAP to calculate sum of digits of a number using recursive function[072 Chaitra]

Chapter 7 - Arrays and Strings [6hrs]

Array

-An array is defined as the collection of similar type of data items stored at contiguous memory locations. -Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float

Why do we need Array? (Significance/Application) What would happen, if we need to enter the marks of 50 students? Would we declare 50 float type of variable individually? Of course not, so, alternative and more convenient way to write such program is by using array which makes us easier to declare such large amount of variable at once.

PROPERTIES OF ARRAY: -Each element of an array is of same data type and carries the same size -Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. -Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.

ARRAY DECLARATION Array Declaration Arrays must be declared before they can be used in the program. Standard array declaration is as : Datatype Arrayname[Lengthofarray/SIZE];

Here, type specifies the variable type of the element which is going to be stored in the array. In C programming language, we can declare the array of any basic standard type which C language supports i.e int, char, float.

Syntax:
Datatype Arrayname[size];

For example: int A[4];

Alt text

ADVANTAGES OF ARRAY:

  • Code Optimization: Less code to the access the data.
  • Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
  • Ease of sorting: To sort the elements of the array, we need a few lines of code only.
  • Random Access: We can access any element randomly using the array.

Types of Array

(Single & Multi - dimension array)

One or Single dimension array In one dimensional array, there is a single subscript or index whose value refers to the individual array element which ranges form 0 to n-1 where n is the size of the array. For e.g. int a[5]

Alt text

Initialization of array: The array is initialized like follow datatype arrayname[size] = {value1, value2, …….., valuen} ;

For eg. 1)int subject[5] = {85, 96, 40, 80, 75} ; // How to access second subject’s mark? 2)char gender[2] = {‘M’, ‘F’} ; 3)float marks[3] = {80.5, 7.0, 50.8} ; 4)int element[5] = {4, 5, 6}

In example(4), elements are five but we are assigning only three values. In this case the value to each element is assigned like following: element[0] = 4 element[1] = 5 element[2] = 6 element[3] = 0 element[4] = 0 i.e. missing element will be set to zero

How to read data and store it in array? To store the data in array we use loop (mainly for loop)

***for ( i=0 ; i < size_of_array ; i++ )***
    ***scanf(“%d”, &array_name[i]);     //%d is for integer***

Write a program to read the ioe rank of 10 students of your class

#include <stdio.h>
void main()
{
    int i;
    int marks[10];

printf(“Enter the IOE rank of 10 students\n”);

    for(i=0 ; i<10 ; i++)
    {
        scanf(“%d”, &marks[i]);
    }
}

How to display the data that is stored in array? To display the data in array we use loop (mainly for loop)

***for ( i=0 ; i < size_of_array ; i++ )***
    ***printf(“%d”, array_name[i]);     //%d is for integer***

Write a program to display the ioe rank of 10 students of your class [Assume that you have already read the value in previous example]*

#include <stdio.h>
void main()
{
    Int i;

printf(“The IOE rank of 10 students are:\n”);
    for(i=0 ; i<10 ; i++)
    {
        printf(“%d”, marks[i]);
    }

}

Write a program to read ioe rank of 10 students of your class and display it.

#include <stdio.h>

void main()
{
    int i;
    int marks[10];

printf(“Enter the IOE rank of 10 students\n”);
for(i=0 ; i<10 ; i++)
    {
        scanf(“%d”, &marks[i]);
    }

    printf(“The IOE rank of 10 students are:\n”);
    for(i=0 ; i<10 ; i++)
    {
        printf(“%d\t”, marks[i]);
    }
}

Program to sort n numbers in ascending order

int main( ) 
{ 
int num[50], i, j, n, temp, 
printf(“How many numbers are there? \t”) ; 
scanf(“%d”, &n) ; 
printf(“\n Enter %d numbers: \n”, n) ; 
for(i=0; i<n; i++)
{
    scanf(“%d”, &num[i]);       
}
for (i=0; i<n; i++)                 
{
for (j=i+1 ; j<n ; j++)             
{ 
if (num[i]>num[j])      
{ 
temp = num[i] ;            
num[i] = num[j] ;            
num[j] = temp ;            
} /* end of if */ 
} /*end of inner loop */ 
} /* end of outer loop */ 

printf(“\n The numbers in ascending order : \n”) ; 
for (i=0 ; i<n ; i++) 
{
printf(“\t%d, num[i] );
}

} /* end of main */ 

Output: How many numbers are there? 5 Enter 5 numbers : 12 56 3 9 17 The numbers in ascending order: 3 9 12 17 56

# use num[i] < num[j] to arrange in descending order

Multi-dimensional arrays: An array of arrays is called multi-dimensional array. For example a one dimensional array of one dimensional array is called two dimensional array. A one dimensional array of two dimensional arrays is called three dimensional arrays, etc. The two dimensional array are very useful for matrix operations.

Declaration of two dimensional array: Multidimensional arrays are declared in the same manner as one dimensional array except that a separate pair of square brackets are required for each subscript i.e. two dimensional array requires two pair of square bracket ; three dimensional array requires three pairs of square brackets, four dimensional array require four pair of square brackets, etc.

The general format for declaring multidimensional array is: datatype arrayname [size1] [size2] …… [sizen] ;

For example: 1)int n[5] [6] ; 2)float a[3] [3] ; 3)int p[3] [3] [4]; Alt text

Alt text

Initialization of multidimensional array: Similar to one dimensional array, multidimensional array can also be initialized. For e.g. 1.int a[3] [2] = {1, 2, 3, 4, 5, 6) ; The value is assigned like follow: a[0] [0] = 1 ; a[0] [1] = 2 ; a[1] [0] = 3 ; a[1] [1] = 4 ; a[2] [0] = 5 ; a[2] [1] = 6 ;

2.int a[3] [2] = { {1,2}, {3,4}, {5,6} } ; In above example, the two value in the first inner pair of braces are assigned to the array element in the first row, the values in the second pair of braces are assigned to the array element in the second row and so on. i.e. a[0] [0] = 1 ; a[0] [1] = 2 ; a[1] [0] = 3 ; a[1] [1] = 4 ; a[2] [0] = 5 ; a[2] [1] = 6 ;

3.int a[3] [3] = { {1,2}, {4,5}, {7, 8, 9} } ; In above example, the values are less than the elements of array. The value assign like follow: a[0] [0] = 1 a[0] [1] = 2 a[0] [2] = 0 a[1] [0] = 4 a[1] [1] = 5 a[1] [2] = 0 a[2] [0] = 7 a[2] [1] = 8 a[2] [2] = 9

In above example the value zero is assigned to a[0] [2] and a[1] [2] because no value assigned to these.

How to read the data and store it in 2D array? // say, a[3][3]
for (i=0; i<3; i++)            //for row
{
for (j=0; j<3; j++)        //for column
{
   scanf(“%d”, &a[i][j] ) ; 
}
    }


How to display the data stored in 2D array? // say, a[3][3]
for (i=0; i<3; i++)            //for row
{
for (j=0; j<3; j++)        //for column
{
   printf(“%d”, a[i] [j] ) ;
}
    }

Program to read & display 2×3 matrix

#include<stdio.h> 

void main( ) 
{ 
int matrix [2][3], i, j ;

printf(“Enter the elements of matrix:\n”); 
for (i=0 ; i<2 ; i++) 
{
for (j = 0 ; j<3 ; j++) 
{ 
printf(“Enter matrix [%d] [%d] : \t”, i, j) ; 
scanf(“%d”, &matrix[i][j] ) ; 
} 
}

printf (“\n Entered matrix is : \n”) ; 
for (i=0 ; i<2 ; i++) 
{ 
    for(j=0;j<3; j++)
    {
printf(“%d\t”, matrix [i] [j]) ; 
printf(“\n”) ; 
}
} 
} 

Output:
Enter matrix [0] [0] : 1 Enter matrix [0] [1] : 2 Enter matrix [0] [2] : 3 Enter matrix [1] [0] : 4 Enter matrix [1] [1] : 5 Enter matrix [1] [2] : 6 Entered matrix is: 1 2 3 4 5 6

Program to read two matrices and display their sum

void main( ) 
{ 
int a[3] [3], b[3] [3], s[3] [3], i, j ; 
printf(“Enter first matrix : \n”) ; 
for (i=0 ; i<3 ; i++) 
{
for (j=0 ; j<3 ; j++)
{ 
scanf(“%d”, &a[i] [j]) ; 
}
}

printf(“Enter second matrix : \n”) ; 
for (i=0 ; i<3 ; i++) 
{
for (j=0 ; j<3 ; j++) 
{
scanf(“%d”, &b[i] [j]) ;
}
    }

    for (i=0 ; i<3 ; i++) 
{
for (j=0 ; j<3 ; j++) 
{
s[i] [j] = a[i] [j] + b[i] [j] ; 
}
}

printf(“\n The sum matrix is : \n”) ; 
for (i=0 ; i<3; i++) 
{ 
for(j=0 ; j<3 ; j++) 
{ 
printf(“\t%d”, s[i] [j]) ; 
} 
printf(“\n”);
} 
}

Output: 
Enter first matrix:     1 2 3 
4 5 6 
7 8 9 

Enter second matrix:     9 8 7 
6 5 4 
3 2 1 

The sum matrix is:     10 10 10 
10 10 10 
10 10 10

Passing Array to Function

Program to illustrate passing array to function

#include<stdio.h> 
void display(int n) ; /* function prototype */
main( ) 
{ 
int num[5] = {100, 20, 40, 15, 33}, i ; 
printf (“\n The content of array is: \n”) ; 
for (i=0; i<5; i++) 
{
display (num[i]) ; display(20)
} 
}

void display(int n) 
{ 
printf (“\t%d”, n ) ; 
} 

Output: The content of array is 100 20 40 15 3

Program to read 10 numbers from keyboard to store these num into array and then calculate sum of these num using function

#include <stdio.h>
#include <stdlib.h>

int sum(int a[ ]);
int main()
{
    int num[10],i, result;
    printf("Enter 10 elements\n");
    for(i=0; i<10; i++)
    {
        scanf("%d", &num[i]);
    }
    result = sum(num);

    printf("The sum of 10 elements is:%d", result);

}

int sum(int a[])
{
    int i, sum;
    sum=0;
    for(i=0; i<10; i++)     
    {
        sum=sum+a[i]; 
    }
    return sum;
}

Output:    Enter 10 elements
        2 4 6 8 10 1 3 5 7 9
        The sum of 10 elements is: 55

Program to read two matrices A and B of order 2×2 and subtract B from A using function

#include <stdio.h>
#include <stdlib.h>

void subt(int a[2][2], int b[2][2]);

void main()
{
    int a[2][2], b[2][2], i, j;

    printf("Enter first 2*2 matrix\n");
    for(i=0;i<2;i++)
    {
        for(j=0; j<2; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    printf("Enter second 2*2 matrix\n");
    for(i=0;i<2;i++)
    {
        for(j=0; j<2; j++)
        {
            scanf("%d", &b[i][j]);
        }
    }

    subt(a,b);
}

void subt(int a[2][2], int b[2][2])
{
    int i,j;


 for(i=0;i<2;i++)
    {
        for(j=0; j<2; j++)
        {
            a[i][j] = a[i][j] – b[i][j];     
        }
    }

    printf("The subtracted matrix is:\n");
    for(i=0;i<2;i++)
    {
        for(j=0; j<2; j++)
        {
            printf("\t%d", a[i][j]);
        }
        printf("\n");
    }

}

String

  • Strings are array of characters. (ex: char name[20] )
  • A string is always terminated by a null character (i.e.\0). The terminating character is important because it is the only way the string handling functions can know where the string ends.

To declare a string of five characters, we should declare array size as: char str[6] Technically, in 6 char array we could only hold 5 letters and one null character at the end to terminate the string Alt text

1D String: Examples: char text[6] ; //Declaration char text[6]={‘H’,’E’,’L’,’L’,’O’, ‘\0’}; // ‘\0’ is optional to input char text[ ]={‘H’,’E’,’L’,’L’,’O’, ‘\0’}; //Declaration and Initialization char text[ ]=“HELLO” ;

2D String: Example: char name[2][7]; char name[2][7]={“Arti”, “Samita”}; char name[ ][7]={“Arti”, “Samita”};

Program to illustrate 1D string array declaration and accessing

#include<stdio.h> 
main() 
{
char name[20];
printf(“Enter the name\n”);
scanf(“%s”, name);

printf(“The name is :%s”, name); 
}

Program to illustrate 2D string array declaration and accessing

#include<stdio.h> 
main() 
{ 
char Day[7][10]; 
int i; 

printf("Enter name of Days:\n"); 
for(i=0;i<7;i++) 
{ 
scanf("%s",&Day[i]); 
}

printf("\nName of Days:"); 
for(i=0;i<7;i++) 
{ 
printf("\n%s",Day[i]); 
} 
printf("\n\nHoliday=%s",Day[6]); 
}

String Functions

There are various string library functions under the header file "string.h". It should be declared at the beginning (at the time of including library files/functions).

1. strlen( ): This function gives number of characters in the string as an output, excluding the null character. Syntax: strlen(string);

Program to count length of string

#include<stdio.h> 
#include<string.h> 
main() 
{ 
char text[30]; 
int len; 
printf("Enter a string: "); 
scanf("%s",&text); 

len= strlen(text); 

printf("The string %s has %d characters.",text, len); 
}

Output: Enter a string: Hello The string Hello has 5 characters

2. strcat( ): This function combines two strings to form a single string. It merges the two strings into the first string. Syntax: strcat(targetstring, sourcestring);

Program to concatenate the strings

#include<stdio.h>
#include<string.h>
main()
{
char source[50], target[50];
printf("Enter source string: ");
scanf("%s",&source);
printf("Enter target string: ");
scanf("%s",&target);

strcat(target,source);
printf("The concatenated string is: %s",target);
}

Output: Enter source string: Nepal Enter target string: Pride The concatenated string is: PrideNepal

3. strcpy( ): This function copies a string to another destination. Syntax: strcpy(destinationstring, sourcestring);

Program to copy string

#include<stdio.h>
#include<string.h>
main()
{
char str[30], copiedStr[30];
printf("Enter a string to copy: ");
scanf("%s",&str);

strcpy(copiedStr,str);
printf("The copied string is: %s", copiedStr);
}

Output: Enter a string to copy: peace The copied string is: peace

4. strcmp( ): This function compares two strings on the basis of ASCII value of characters. It returns 0 if the strings are equal; else it returns 1 or -1. Syntax: strcmp(string1, string2);

This function return values that are as follows: if Return value < 0 then it indicates str1 is less than str2. if Return value > 0 then it indicates str2 is less than str1. if Return value = 0 then it indicates str1 is equal to str2.

ASCII values for: a to z => 97 to 122 and A to Z => 65 to 90

Program to compare strings

#include<stdio.h>
#include<string.h>
main()
{
char s1[50],s2[50];
int y;
printf("Enter string s1: ");
scanf("%s",&s1);

printf("\nEnter string s2: ");
scanf("%s",&s2);

y=strcmp(s1,s2);

if(y<0)
printf("\nString1 < String2");
else if(y>0)
printf("\nString1 > String2");
else
printf("\nThe given strings are equal.");
}

Output: Enter string s1: Anjan
Enter string s2: Ankit String1 < String2

5. strlwr( ): This function changes the uppercase characters in the string to the lowercase character If any of the character, already in lowercase then the function skips that character and converts the other remaining character which is in uppercase. Syntax: strlwr(string);

Program to convert string into lowercase

#include<stdio.h>
#include<string.h>
main()
{
char text[50];
printf("Enter a string: ");
scanf("%s",&text);

strlwr(text);

printf("The lowercase string is: %s",text);
}

Output: Enter a string: GrAnD The lowercase string is: grand

6. strrev( ): This function reverses the given string. Syntax: strrev(string);

Program to reverse the string

#include<stdio.h>
#include<string.h>


int main()
{
char word[50];
printf("Enter a string to reverse: ");
scanf("%s", word);
strrev(word);
printf("The reversed string is: %s", word);
}

Output: Enter string to reverse: StrINg The reversed string is: gNIrtS

Passing String to Functions

We know that strings are saved in arrays so, to pass an one dimensional array to a function we have the following declaration: returnType functionName(char str[]);

Example: void displayString(char str[]);

Program:

#include <stdio.h>
void displayString(char str[ ]);
void main()
{
char message[ ] = "Hello World";
displayString(message);
}

void displayString(char str[])
{
printf("String: %s", str);
}

Output: String: Hello World

Another way we can print the string is by using a loop like for or while and print characters till we hit the NULL character.

Program:

#include <stdio.h>
void displayString(char str[ ]);
void main()
{
char message[] = "Hello World";
displayString(message);
}

void displayString(char str[])
{
int i = 0;
printf("String: ");
while (str[i] != '\0')
{
printf("%c", str[i]);
i++;
}
}

Output: String: Hello World

Solving String Problems without using Library Functions

[Important questions for exam]

1. To find length of string

#include <stdio.h>
#include <stdlib.h>

void main()
{
    char text[40];
    int length=0, i;
    printf("Enter a string: ");
    gets(text);                

    for(i=0; text[i]!='\0'; i++) 
    {
        length++;        
    }
    printf("\nThe length of string \“%s\” is: %d.", text, length);
}

2. To concatenate two strings

#include <stdio.h>
#include <stdlib.h>

void main()
{
char text1[40], text2[40], concat[60];
int length1=0, length2=0, i, j;

printf("Enter 1st string: ");
gets(text1);

printf("Enter 2nd string: ");
gets(text2);

for(i=0;text1[i]!='\0';i++)  //to find length of the string1
    {
        length1++;
    }

for(i=0;text2[i]!='\0';i++) //to find length of the string2
    {
        length2++;
    }

for(i=0;i<length1;i++)
    {
        concat[i]=text1[i];
    }

for(j=0,i=length1; i<(length1+length2); i++,j++)
    {
        concat[i]=text2[j];
    }
concat[i]='\0';
printf("The concatenated string is: %s",concat);
}

3. To copy string.

#include<stdio.h>
void main()
{
char text[40], copy[40];
int i;
printf("Enter a string: ");
gets(text);
for(i=0;text[i]!='\0';i++) //to find length of the string
{
copy[i]=text[i];
}
copy[i]='\0';
printf("The given string is: %s",copy);
}

4. To compare two strings.

#include<stdio.h>
void main()
{
char text1[40], text2[40];
int i, j;

printf("Enter 1st string: ");
gets(text1);

printf("Enter 2nd string: ");
gets(text2);

for(i=0;text1[i]!='\0';i++)
{
if(text1[i]==text2[i])
continue;
else
printf("The given strings are not same.");
break;
}

if(text1[i]==text2[i])
printf("The given strings are same.");
}

5. To reverse a string.

#include<stdio.h>
int main()
{
char text[40], reverse[40];
int length=0, i, j;

printf("Enter a string to reverse: ");
gets(text);


for(i=0;text[i]!='\0';i++) //to find length of the string
{
length++;        
}

i=length-1;                
for(j=0;j<length;j++,i--)        
{
reverse[j]=text[i];    
}
reverse[j]='\0';
printf("The reverse string is %s",reverse);
}

6. To change the case of string [Both cases are implement in one program].

#include<stdio.h>
main()
{
char text[40], copy[40];
int i;

printf("Enter a string: ");
gets(text);            

for(i=0 ; text[i]!='\0' ; i++)  
{
if(text[i]>=65&&text[i]<=90)            // 65-90 means uppercase
text[i]=text[i]+32;            //converting to lowercase

else if (text[i]>=97&&text[i]<=122)        // 97-122 means lowercase
text[i]=text[i]-32;            //converting to uppercase
}
printf("The string after conversion of case is: %s",text);
}

7. To check a string for palindrome.

#include<stdio.h>
int main()
{
char text[40], reverse[40];
int length=0, i, j, pal=0;

printf("Enter a string to check for palindrome: ");
gets(text);

for(i=0;text[i]!='\0';i++)     //to find length of the string
{
length++;
    }

i=length-1;

for(j=0;j<length;j++,i--)
{
reverse[j]=text[i];
}
reverse[j]='\0';            

for(i=0;text[i]!='\0';i++)        
{
if (text[i] == reverse[i])    
pal=0;            
else
    pal++;  
    break;      
}
if(pal==0)
printf("%s is palindrome",text);
else
printf("%s is not palindrome",text);
}

8. WAP to print following pattern:

C I V I L
C I V I
C I V
C I
C

int main()
{
    char data[]="CIVIL";
    int i,j;

    for(i=5; i>0; i--)            
    {
        for(j=0; j<i; j++)            
        {
            printf("%c", data[j]);     
        }
        printf("\n");
    }
}

9. WAP to print following pattern without using formatted input/output.

C I V I L                        int main()
C I V I                            {
C I V                                char data[]="CIVIL";
C I                                int i,j;
C                            
                                for(i=5;i>0;i--)
                                {
                                    for(j=0; j<i; j++)
                                    {
                                        putchar(data[j] );
                                    }
                                    printf("\n");
                                }
                            }

Exam solutions

Write a program to input two matrices ofsize mxn and pxq respectively. Pass these matrices to the function to calculate the product matrix. Display the product matrix in the main() function [076 Ashwin Back]

To return array to the main function we need to use the concept of pointer(i.e passing the address).As we know, the array name is the pointer to itself so we can either send pointer to user defined function to return answer to main function or simply perform the calculation by passing the array name to the user defined function. Here I have not used the pointer but keep one thing in mind that this question can be done using pointer as well.

#include <stdio.h>
void matrix_prod(int a[10][10],int n1,int n2,int b[10][10],int r1,int r2,int c[10][10]);
int main()
{
    int m,n,p,q,i,j;
    int mata[10][10], matb[10][10], matc[10][10]; //we will receive product matrix in matc
    printf("Enter the row & column (m*n) of first matrix\n");
    scanf("%d%d",&m,&n);

    printf("Enter the row & column (p*q) of first matrix\n");
    scanf("%d%d",&p,&q);

    printf("enter the content of first matrix\n");
    for(i=0; i<m; i++)
    {
        for(j=0; j<n; j++)
        {
            scanf("%d",&mata[i][j]);
        }
    }

    printf("enter the content of second matrix\n");
    for(i=0; i<p; i++)
    {
        for(j=0; j<q; j++)
        {
            scanf("%d",&matb[i][j]);
        }
    }

    matrix_prod(mata,m,n, matb,p,q, matc);
    printf("the product matrix is\n");
    for(i=0; i<m; i++)
    {
        for(j=0; j<q; j++)
        {
            printf("%d\t",matc[i][j]);
        }
        printf("\n");
    }

}

void matrix_prod(int a[10][10],int n1,int n2,int b[10][10],int r1,int r2,int c[10][10])
{
    int i,j,k;

    for(i=0; i<n1; i++)
    {
        for(j=0; j<r2; j++)
        {
            c[i][j]=0;
            for(k=0; k<n2; k++)
            {
                c[i][j] =  c[i][j] + a[i][k] * b[k][j] ;
            }
        }
    }
}

Write a program to print the following output pattern using unformatted output functions [069 chaitra]

       k
      ok
     wok
    hwok
   chwok
  lchwok
 ulchowk
pulchowk

int main()
{
    char str[]="pulchowk";
    char sp=' ';
    int i,j,k;
    for(i=7; i>=0; i--)
    {
        for(k=i; k>=0;k--)
        {
            putchar(sp);    //to print space
        }
        for(j=i; j<8; j++)
        {
            putchar(str[j]);
        }
        putchar(10);            //we need to add new line.The ascii value of new line is 10
                                //so, when we use putchar(10), it converts that 10 into new line
            //putchar(10) is similar to printf(“\n”)
    }
}

CH 8 – Structure [4 hrs]

Introduction

Structure: -Structure is a collection of data item. -The data item can be different type, some can be int, some can be float, some can be char and so on. -The data item of structure is called member of the structure.

The difference between array and structure is the element of an array has the same type while the element of structure can be of different type. Another difference is that each element of an array is referred to by its position while each element of structure has a unique name.

Declaring structure and creating structure variables

Structure Declaration The general syntax for declaration of a structure is

struct structure_name { 

data_type1 member1; 
data_type2 member2; 
- - - - - - - - - - 
data_typen membern; 
} ; 

The struct is a keyword. The name is written by the programmer. The rule for writing name is rule for identifier.

For example: 1) struct student{ char name[80]; int roll_no; char branch[10]; int semester ; };

2) static struct data { int day; char month_name[15]; int year; };

Creating structure variable: I. creating structure variable at the time of declaration: Example: struct student { char name[80]; int roll_no; char branch[10]; int semester; } var1, var2, var3;

In this example three structure variables name var1, var2, var3 are created. We can create one or more than one variable. The space is created like: Alt text

II. struct student { char name[80] ; int roll_no; char branch[10]; int semester; };

structure variable creation: struct student var1, var2, var3 ;

Initialization of structure: -A structure is initialized like other data type in C. -The values to be initialized must appear in order as in the definition of structure within braces and separated by commas. -C does not allow the initialization of individual structure member within its definition.

Its syntax is: struct structurename structurevariable = {value1, value2, value3 _ _ _ _ valuen}

(1) struct particular{ int rn ; int age ; char gender; };

We can initialize the structure at the time of variable creation like: struct particular pr = {10, 22, ‘m’};

By this: ‘10’ is assigned to roll number of pr; ‘22’ is assigned to age of pr and ‘m’ is assigned to gender of pr structure.


Accessing member of structure

The accessing concept of member is: structurevariablename. member The dot(.) operator is also known as as member operator or period. For example:

struct bio{ 
char name[80];
int age;
long phno;
};

struct bio b1, b2;
for accessing
b1.phno = 271280;

CA(Class Assignment): Create a structure named student that has name, roll and marks as members

Create a structure named student that has name, roll and marks as members. Assume appropriate types and size of member. WAP using structure to read and display the data entered by the user

# include <stdio.h>
int main()
{
    struct student
    {
    char name[20];
    int roll;
    float mark;
    };

struct student s;

printf("\nenter name:\t");
gets(s.name);

printf("\nenter marks: \t");
scanf("%f", &s.mark);

printf("\nenter roll:\t");
scanf("%d", &s.roll);


printf("\n\nThe student’s information is \n");
printf("\nName \t\t Roll \t Marks");
printf("\n - - - - - - - - - - - - - - - - - - - - - - - - -\n");

printf("%s \t %d \t %.2f", s.name, s.roll, s.mark);

}

Aray of Structure: Like array of int, float or char type, there may be array of structure

    struct employee         struct employee
    {                   {
        char name[20];          char name[20];
        int empid;              int empid;
        float salary;               float salary;
    } emp[10];              };
                        struct employee emp[10];


Create a structure named student that has name, roll and marks as members. Assume appropriate types and size of member. WAP using structure to read and display the data of 5 students

# include <stdio.h>
int main()
{
        struct student
        {
        char name[20];
        int roll;
        float mark;
        };

    struct student s[5];
    int i;

    for(i=0;i<5;i++)
    {
        printf("\nenter name:\t");
        scanf("%s", s[i].name);

        printf("\nenter roll:\t");
        scanf("%d", &s[i].roll);

        printf("\nenter marks: \t");
        scanf("%f", &s[i].mark);

    }
    printf("\n\nThe student’s information is \n");
    printf("\nName \t\t Roll \t Marks");
    printf("\n - - - - - - - - - - - - - - - - - - - - - - - - -\n");

    for(i=0;i<5;i++)
    {
        printf("%s \t\t %d \t %.2f\n", s[i].name, s[i].roll, s[i].mark);
    }
}


Structure within structure (Nested Structure):

-One structure can be nested within another structure in C. -In other words, the individual members of a structure can be other structure as well.

For example: Create a structure named date that has day, month and year as its members. Include this structure as a member in another structure named employee which has name, id, salary, as other members. Use this structure to read and display employee’s name, id, dob and salary

int main()
{
     struct date
        {
        int day;
        int month;
        int year;
        };

    struct employee
        {
        char name[20];
        int id;
        struct date dob;
        float salary;
        } emp;


    printf("Name of Employee: \t");
    scanf("%s", emp.name);

    printf("\nID of employee: \t");
    scanf("%d", & emp.id);

    printf("\nDay of Birthday: \t");
    scanf("%d", &emp.dob.day);

    printf("\nmonth of Birthday: \t");
    scanf("%d", &emp.dob.month);

    printf("\nYear of Birthday: \t");
    scanf("%d", &emp.dob.year);

    printf("\nsalary of Employee: \t");
    scanf("%f", &emp.salary);

    printf("\n\nThe Detail Information of Employee");
    printf("\nName \t id \t day \t month \t year \t salary");
    printf("\n - - - - - - - - - - - - - - - - - - - - - - - \n");

    printf("%s \t %d \t %d \t %d \t %d \t %.2f", emp.name, emp.id , emp.dob.day, emp.dob.month , emp.dob.year, emp.salary);

}

Processing a Structure:

WAP to read records of 5 employee(Enter relevant fields: Name, address, salary, Id).Display the records of the top three employees which have the highest salary

int main()
{
       struct employee
        {
            char name[20];
            char address[20];
            float salary;
            int ID;
        };

int i, j ;
float temp;
struct employee emp[5];


printf("enter 5 employee Information: \n");

for(i=0;i<5;i++)
{
    printf("Enter name:\n");
    scanf("%s", emp[i].name);

    printf("Enter address:\n");
    scanf("%s", emp[i].address);

    printf("Enter salary:\n");
    scanf("%f", &emp[i].salary);

    printf("Enter ID:\n");
    scanf("%d", &emp[i].ID);
    printf("\n");
}

for(i=0; i<5; i++)
{   for(j=i+1; j<5; j++)
    {
        if(emp[i].salary<emp[j].salary)
        {
            temp = emp[i].salary;
            emp[i].salary = emp[j].salary;
            emp[j].salary = temp;

        }
    }
}

printf("3 highest salary: \n");
printf("\n - - - - - - - - - - - - - - - - - - - - - - - - - \n");
for(i=0; i<3; i++)
{
    printf("%.2f\n", emp[i].salary);
}

}

Create a user defined array structure student record having members physics, chemistry and mathematics. Feed the marks obtained by three students in each subjects and calculate the total marks of each student

int main()
{
       struct student
        {
            int physics;
            int chemistry;
            int mathematics;
            int total;
        };
struct student std[3];
int i;

printf("Enter the marks of 3 subjects \n");
for(i=0;i<3;i++)
{
    printf("Enter the marks of PHY, CHEM & MATH respectively\n");
    scanf("%d%d%d", &std[i].physics,&std[i].chemistry,&std[i].mathematics);
    std[i].total = std[i].physics + std[i].chemistry +std[i].mathematics;   // calculating total marks
}

printf("\nThe marking distribution is as follows:\n");
printf("---------------------------------------\n");
printf("PHY \t CHEM \t MATH \n");
for(i=0; i<3; i++)
{
    printf("%d \t %d \t %d \n", std[i].physics, std[i].chemistry, std[i].mathematics);
}

}


Structures and pointers:

-Pointers can be used also with structure. -To store address of a structure type variable,we can define a structure type pointer variable as normal way.

Let us consider a structure ‘book’ that has members name, page and price. It can be declared as: struct book { char name[20]; int page; float price; }; Then we can define structure variable and pointer variable of structure type struct book b ; /* b is structure variable*/ struct book *p; /* p is pointer variable of structure type */

Where b is simple variable of structure type book where as p is pointer type variable which points or can store address of structure book type variable. To use structure’s members through pointer p, we need assignment as given below p = &b;

Here, the base address of b is assigned to pointer p. An individual structure member can be accessed in terms of its corresponding pointer variable by writing: ptr_variable -> member where ( ->) is called arrow operator and there must be pointer to the structure on the left side of this operator.

Now, the members name, pages, and price of book can be accessed as b.name p ->name (p).name b.pages p->pages (p).pages b.price p->price (*p).price

int main()
{
    struct book
    {
        char name[20];
        int pages;
        float price;
    };
    struct book b, *p;

    printf("Name?\t");
    scanf("%s", b.name);

    printf("Pages?\t");
    scanf("%d", &b.pages);

    printf("Price?\t");
    scanf("%f", &b.price);

    p=&b;

    printf("\n\n\nDisplaying information using (.) operator\n");
    printf("Name:%s \t Pages:%d \t Price:%.2f\n", b.name, b.pages, b.price);

    printf("\nDisplaying information using (->) operator\n");
    printf("Name:%s \t Pages:%d \t Price:%.2f\n", p->name, p->pages, p->price);

    printf("\nDisplaying info. using (*) operator\n");
    printf("Name:%s \t Pages:%d \t Price:%.2f\n", (*p).name, (*p).pages, (*p).price);
}


Passing Structure to functions:

Like any other variable, a structure variable can also be passed to a function. We can pass individual structure elements or the entire structure. The structure can be passed like following:

It’s syntax is:

struct struct_name
{
    ………..
    members;
    ………..
}

ret_type display_struct_members (struct struct_name a);    //function prototype
void main()
{
    struct struct_name n1;
    ------------------------
    ------------------------
    display_struct_members(n1);
}

ret_type display_struct_members (struct struct_name a)
{
    //now we can easily access
    //the members of structure variable ‘a’
}

Create a structure ‘book’ that has members name, pages and price. Write a program where you read the data into structure variable in main function then pass it another function and display the data in next function

struct book
    {
        char name[20];
        int pages;
        float price;
    };
void struct_book(struct book temp);
int main()
{

    struct book b;

    printf("Name?\t");
    scanf("%s", b.name);

    printf("Pages?\t");
    scanf("%d", &b.pages);

    printf("Price?\t");
    scanf("%f", &b.price);

    struct_book(b);

}

void struct_book(struct book temp)
{
    printf("\n\n\nDisplaying information inside function\n");
    printf("Name:%s \t Pages:%d \t Price:%.2f\n", temp.name, temp.pages, temp.price);
}

WAP which reads two complex numbers and then perform multiplication of these two. Read the numbers in main function, pass them to next function and finally you have to return the answer back to main function

So|n: If two complex no. are a1+ib1 and a2+ib2 then multiplication is (a1+ib1)*(a2+ib2) ⇒ a1a2 + i2b1b2 + a1b2i + a2b1i ⇒ (a1a2 – b1b2) + (a1b2 + a2b1)i (because i2 = -1)

struct complex
    {
        float real;
        float img;
    };

struct complex complex_mul(struct complex a, struct complex b);
int main()
{

    struct complex n1,n2,result;

    printf("Enter the real part of first complex number\n");
    scanf("%f", &n1.real);
    printf("Enter the imaginary part of first complex number\n");
    scanf("%f", &n1.img);

    printf("\nEnter the real part of second complex number\n");
    scanf("%f", &n2.real);
    printf("Enter the imaginary part of second complex number\n");
    scanf("%f", &n2.img);

    result = complex_mul(n1,n2);

    printf("\nThe first complex number is:\t%.2f + %.2fi\n", n1.real,n1.img);
    printf("\nThe second complex number is:\t%.2f + %.2fi\n", n2.real,n2.img);
    printf("\n\nThe product of two complex number is as below:\t");
    printf("%.2f + %.2fi\n\n", result.real, result.img);


}

struct complex complex_mul(struct complex a, struct complex b)
{
    struct complex temp;

    temp.real = a.real*b.real - a.img*b.img ;
    temp.img = a.real*b.img + a.img*b.real;

    return temp;
}

CH 9 : POINTERS 4 hrs]


Introduction

Pointer A pointer is a variable that contains a memory address of data or another variable. [In other word, a pointer is a variable that stores memory address]. Like all other variables it also has a name to be declared and occupies some space in memory. It is called a pointer because it points to a particular location in memory by storing the address of that location.

Pointer, variable and their storage We have studied that it is necessary to declare a variable before using it, since compiler has to reserve space for it. The data type of the variable also has to be mentioned so that the compiler knows how much space needs to be reserved. For example: int age;

The compiler reserves 2 consecutive bytes from memory for this variable and associates the name ‘age’ with it. Suppose compiler has reserved bytes numbered 65524 and 65525 for the storage of variable age, then the address of variable age will be 65524. Let us assign some value to this variable. age = 20;

Now this value will be stored in these 2 bytes. The number of bytes allocated will depend on the data type of variable. For example, 4 bytes would have been allocated for a float variable, and the address of first byte would be called the address of variable

Pointer Declaration The general syntax is: data_type *pname; ex:

int *iptr,sn=30;
iptr=&sn;         /*assigning of pointer*/

Now, iptr contains the address of variable sn i.e. it points to variable sn Alt text

-Pointer are also variables so compiler will reserve space for them and they will also have some address. -All pointers irrespective of their base type will occupy the same space in memory since all of them contain address only. -Generally 2 bytes are used to store an address(may vary in different computers), so the compiler allocates 2 bytes for a pointer variable.

Program to print address of variable using &

#include<stdio.h>
main( )
{
int sn = 30;
printf("value of sn=%d, Address of sn=%d\n", sn, &sn);

}

Can you answer the following questions? Suppose we have a pointer variable ( *p). Now, what does p and *p mean? Do they both contain the same content or are they different? Ex:

int main()
{
    int a, *p;
    a=10;
    p=&a;

    printf("Value of a is: %d\n", a);
    printf("Value of &a is: %d\n", &a);
    printf("Value of *p is: %d\n", *p);
    printf("Value of p is:%d\n", p);

}

What will be the output of above code?

Application of pointer Some uses of pointers are: -Accessing array elements -Returning more than one value from a function -Accessing dynamically allocated memory -Implementing data structure like linked lists, trees, and graphs. -Increasing the execution speed as they refer address.


Pointer Arithmetic

Lets say we have:

int a = 87;
float b = 4.5;
int *P1 = &a;
float *P2 = &b;

Its important to understand the following expressions:

*P1=9;     is equivalent to    a=9;
(*P1)++;     is equivalent to    a++;
x=*P2+10;     is equivalent to    x=b+10;

Can you guess the output of the following programs ?

int main()                            int main()
{                                {
    Int a, *p;                          Int a, *p;
    a=20;                               a=20;
    p=&a;                               p=&a;

    p++;                                (*p)++;
    printf(“%d”, p);                        printf(“%d”, *p);
}                                }

Output: ??? Output: ???

In the first case we have done p++, it means that the address which is stored in p will be incremented. Whereas in second case we have done (*p)++, which means that the content which is stored in the address held by p pointer will be incremented.


Pointer and Array

There is a close association between pointer and array. Array name is pointer to itself. For example:

int a[5],*p;
p=&a[0];

After statement: p=&a[0]; p points the array i.e. the p contains the address of a[0] (first address of array)

p++;

After this statement P points to a[1] element

Lets look at the output of following code:

int main()
{
    int a[5]={2,4,6,8,0};
    int *p;

    p=&a;

    printf("Address of a=%d\n", &a);
    printf("Address of a[0]=%d\n", &a[0]);
    printf("Address of a[1]=%d\n", &a[1]);  

}

Output: ???

int main()
{
    int a[5]={2,4,6,8,0};
    int *p;

    p=&a;

    printf("Address of a=%d\n", &a);
    printf("Address of a[0]=%d\n", &a[0]);
    printf("Address of a[1]=%d\n", &a[1]); 
    printf("p=%d\n", p); 

}

Output: ???

int main()
{
    int a[5]={2,4,6,8,0};
    int *p;

    p=&a;        //p=&a[0]

    printf("Address of a=%d\n", &a);
    printf("Address of a[0]=%d\n", &a[0]);
    printf("Address of a[1]=%d\n", &a[1]); 
    printf("p=%d\n", p); 
    p++;
    printf("After p++, p=%d\n", p);

}

Output: ???

Lets try to understand following example:

int main()
{
   int a[5] = {5, 6, 7, 8, 9};
   int *p, i;

    p = &a[0];

    for(i=0; i<=4; i++)
    {
        printf("%d\n",*(p+i));    
    }
}

We know that array name is also pointer so the above program can be written as

int main()
{
   int a[5] = {5, 6, 7, 8, 9};
   int *p, i;

    p = &a[0];
    for(i=0; i<=4; i++)
    {
        printf("%d\n",*(a+i));        
    }

}


Pointers and 2D array

To access ith element of 1D array we did : (a+i) for its address , & *(a+i) for its content

In 2D array we need to access jth element of ith index. For that we do: *(a+i)+j for its address, & *(*(a+i)+j) for its content

It means,

*(a+i)+j  is similar to  &a[i][j] 
*(*(a+i)+j)  is similar to  a[i][j]

Write a program where you read two matrices from user using the concept of pointer and finally add those matrices to create new matrix using pointer

int main()
{
    int a[3][2], b[3][2], c[3][2];
    int i,j;


    printf("Enter the elements for 1st matrix\n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<2; j++)
        {
            scanf("%d", *(a+i)+j);
        }
    }

    printf("Enter the elements for 2nd matrix\n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<2; j++)
        {
            scanf("%d", *(b+i)+j);
        }
    }

    for(i=0; i<3; i++)
    {
        for(j=0; j<2; j++)
        {
            *(*(c+i)+j) = *(*(a+i)+j) + *(*(b+i)+j);
        }
    }

    printf("\n\nThe sum matrix is:\n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<2; j++)
        {
            printf("%d\t", *(*(c+i)+j));
        }
        printf("\n");
    }

}


Passing Pointer to Function

A pointer can be passed to a function as an argument. Passing a pointer means passing the address of a variable instead of the value of the variable. As address is passed in this case, this mechanism is also known as call by address or call by reference.

Program to illustrate the use of passing pointer to a function

#include<stdio.h>

void addGraceMarks(int *m);    //function prototype
void main( )
{
int marks;
printf(“Enter actual marks: \n”);
scanf(“%d”,&marks);

addGraceMarks( &marks );         //Passing address
printf(“\n The graced marks is: \t%d”, marks);
}



void addGraceMarks(int *m)
{
*m = *m+10;
}

Program to convert upper case letter into lower and vice versa using passing pointer to a function

#include<stdio.h>

void conversion(char *c);     /*function prototype */
int main( )
{
char input;
printf(“Enter character of our choice:\n”);
scanf(“%c”,&input);

conversion(&input);
printf(“\n The corresponding character is:\t%c”,input);
}
void conversion(char *c)
{
if( *c>=97 && *c<=122 )
*c=*c-32;
else if ( *c>=65 && *c<=90)
*c=*c+32;
}


Dynamic Memory Allocation

Lets say we have declared an array of size 9 i.e int marks[9] But what if there is a requirement to change this length (size). For Example, -If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. -Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.

C provides some functions to achieve these tasks.This procedure is referred to as Dynamic Memory Allocation in C. There are 4 library functions provided by C defined under header file to facilitate dynamic memory allocation in C programming. They are: 1.malloc() 2.calloc() 3.free() 4.realloc()

1)malloc() “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.It initializes each block with default garbage value.

Syntax: ptr = (cast-type*) malloc(byte-size)

For Example: ptr = (int*) malloc(100 * sizeof(int));

If the size of int is 2 bytes, this statement will allocate 200 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a NULL pointer.

Example of malloc():

int main()
{
    int *ptr;
    int n, i;

    printf("Enter number of elements\n");
    scanf("%d", &n);

    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));

    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
    }
    else
    {

        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");

        // Get the elements of the array
        printf("Enter %d elements\n", n);
        for (i = 0; i < n; ++i)
        {
            scanf("%d", &ptr[i]);
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf("%d ", ptr[i]);
        }
    }

}

2) calloc() “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. Syntax: ptr = (cast-type*)calloc(n, element-size);

For Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float.

Example of calloc():

int main()
{
    int *ptr;
    int n, i;

    printf("Enter number of elements\n");
    scanf("%d", &n);

    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));

    // Check if the memory has been successfully
    // allocated by calloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
    }
    else
    {

        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");

        // Get the elements of the array
        printf("Enter %d elements\n", n);
        for (i = 0; i < n; ++i)
        {
            scanf("%d", &ptr[i]);
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf("%d ", ptr[i]);
        }
    }

}

3) free() “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax: free(ptr);

int main()
{
    int *ptr;
    int n, i;

    printf("Enter number of elements\n");
    scanf("%d", &n);

    // Dynamically allocate memory using malloc()
    ptr = (int*)calloc(n, sizeof(int));

    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
    }
    else
    {

        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");

        // Get the elements of the array
        printf("Enter %d elements\n", n);
        for (i = 0; i < n; ++i)
        {
            scanf("%d", &ptr[i]);
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf("%d ", ptr[i]);
        }

        free(ptr);
        printf("\nThe memory has been succesfully freed\n");
    }

}

4) realloc() “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory Syntax: ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize' If space is insufficient, allocation fails and returns a NULL pointer.

int main()
{
    int *ptr;
    int n, i, n1;

    printf("Enter number of elements\n");
    scanf("%d", &n);

    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));

    // Check if the memory has been successfully
    // allocated by calloc or not
    if (ptr == NULL)
    {
        printf("Memory not allocated.\n");
    }
    else
    {

        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");

        // Get the elements of the array
        printf("Enter %d elements\n", n);
        for (i = 0; i < n; ++i)
        {
            scanf("%d", &ptr[i]);
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf("%d ", ptr[i]);
        }

        printf("\nEnter the new number of elements\n");
        scanf("%d", &n1);

        ptr = realloc(ptr, n1);

        printf("Enter %d new elements\n", n1);
        for(i=n; i<(n+n1); i++)
        {
            scanf("%d", &ptr[i]);
        }

        printf("\n\nFinally all the elements are\n");
        for (i = 0; i < n+n1; ++i)
        {
            printf("%d ", ptr[i]);
        }

    }
}

Exam Solution

What is null pointer? What will be the output of following program, explain [075 Ashwin] #include<stdio.h> int main() { if( ! Null ) prinrf("C programming is easy"); else printf("C programming is not easy"); return 0; }

Ans: A Null Pointer is a pointer that does not point to any memory location.The null pointer basically stores the Null value. Example: int * pInt = NULL;

Explanation of program In computer programming, null is both a value and a pointer. Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer.

As we saw just before, null means 0. Lets see what happens inside the if condition and lets find out which statement gets executed: The ‘!’ operator is called ‘not’ operator in C. It converts everything into its negative. Inside if function we have (! Null). Null is 0, it means false. When we apply ! to False, it becomes True. Thus, we can say (! Null) is a True condition and we know that when the if condition is true, the statement that is inside the if block will be executed. Therefore, In the above program the output will be:

C programming is easy

Write a program that uses pointer to represent two 2d array of size mn & pq respectively. Find the product of these two matrices if possible otherwise display a message “Calculation cant be performed” using function

#include <stdio.h>
void prod(int m,int n, int p, int q);
int main()
{
    int m,n,p,q;

    printf("Enter the row for first matrix:\n");
    scanf("%d", &m);
    printf("Enter the column for first matrix:\n");
    scanf("%d", &n);

    printf("Enter the row for second matrix:\n");
    scanf("%d", &p);
    printf("Enter the column for second matrix:\n");
    scanf("%d", &q);

    prod(m,n,p,q);

}
void prod(int m,int n, int p, int q)
{
    int i,j,k;
    int a[5][5],b[5][5],c[5][5];
    if(n!=p)
    {
        printf("Calculation cant be performed!!\n");
    }
    else
    {
        printf("Enter the elements for 1st matrix\n");
        for(i=0; i<m; i++)
        {
            for(j=0; j<n; j++)
            {
                scanf("%d", *(a+i)+j);
            }
        }



        printf("Enter the elements for 2nd matrix\n");
        for(i=0; i<p; i++)
        {
            for(j=0; j<q; j++)
            {
                scanf("%d", *(b+i)+j);
            }
        }


        for(i=0; i<m; i++)
        {
            for(j=0; j<q; j++)
            {
                *(*(c+i)+j) =0;
                for(k=0; k<n; k++)
                {
                    *(*(c+i)+j) =*(*(c+i)+j) + (*(*(a+i)+k)) * (*(*(b+k)+j));
                }

            }
        }

        printf("\n\nThe product matrix is:\n");
        for(i=0; i<m; i++)
        {
            for(j=0; j<q; j++)
            {
                printf("%d\t", *(*(c+i)+j));
            }
            printf("\n");
        }


    }
}

Ch 10 : Data Files [4 hrs]

-printf( ), scanf( ), getchar( ), putchar( ), gets( ), puts( ) are known as console oriented I/O functions which always use keyboard for input device. -While using these library functions, the entire data is lost when either the program is terminated or the computer is turned off. -If the same data is to be entered again at some later stage, again we have to enter the same data. These problems invite the concept of data file in which data can be stored on the disks and read whenever necessary, without destroying data. A file is a place on the disk where a group of related data is stored.

Programming language C has various library functions for creating and processing data files. Mainly, there are two types of data files: 1.High level (standard or stream oriented) files 2.Low level (system oriented) files

Alt text

In high level data files, the available library functions do their own buffer management where as the programmer should do it explicitly in case of lower level files. The standard data files are again subdivided into: text files and binary files.

The text files consist of consecutive characters and these characters can be interpreted as individual data item. The binary files organize data into blocks containing contiguous bytes of information.


Opening and closing a data file

Before a program can write to a file or read from a file, the program must open it. Opening a file established a link between the program and the operating system. This provides the operating system, the name of the file and the mode in which the file is to be opened.

Syntax: FILE ptrvariable; //declaring a file pointer ptrvariable = fopen( filename, filemode) //opening the file using pointer

where fopen( ) function takes two strings as arguments, the first one is the name of the file to be opened and the second one is file_mode that decides which operations (read, write, append, etc) are to be performed on the file. On success, fopen( ) returns a pointer of type FILE and on error it returns NULL.

For example: FILE *fp1, *fp2 ; fp1 = fopen (“myfile.txt”, “w”); fp2 = fopen (“yourfile.dat”, “r”);

File Opening Modes

The file opening mode specifies the way in which a file should be opened (i.e. read, write, append, etc). In other word, it specifies the purpose of opening a file. They are:

1.“w” (write): -If the file dosen’t exist then this mode creates a new file for writing. -If the file already exists, then the previous data is erased and the new data entered is written to the file.

2. “a” (append): -If the file doesn’t exist then this mode creates a new file -If the file already exists then the new data entered is appended at the end of existing data. -In this mode, the data existing in the file is not erased as in “w” mode.

3. “r” (read): -This mode is used for opening an existing file for reading purpose only. -The file to be opened must exist and the previous data of file is not erased.

4. “w+” (write + read): -This mode is same as “w” mode but in this mode we can also read and modify the data. -If the file doesn’t exist then a new file is created and if the file exists then previous data is erased.

5. “r+” (read + write): -This mode is same as “r” mode but in this mode we can also write and modify existing data. -The file to be opened must exist and the previous data of file is not erased. -Since we can add new data and modify existing data so this mode is also called update mode.

6. “a+” (append + read): -This mode is same as the “a” mode but in this mode we can also read the data stored in the file. -If the file doesn’t exist, a new file is created and if the file already exists then new data is appended at the end of existing data in this mode.

To open a file in binary mode we can append ‘b’ to the mode and to open the file in text mode ‘t’ can be appended to the mode. But since text mode is the default mode, ‘t’ is generally omitted while opening files in text mode

For example: “wb” Binary file opened in write mode “ab+” or (“a+b”) Binary file opened in append mode “rt+” or (“r+t”) Text file opened in read mode “w” or (“wt”) Text file opened in write mode

The file that was opened using fopen( ) function must be closed when no more operations are to be performed on it. After closing the file, connection between file and program is broken. Its syntax is: fclose(ptr_variable); On closing the file, all the buffers associated with it are flushed and can be available for other files. For example: fclose(fp1); fclose(fp2);


Library functions

1. Unformatted I/O functions: a.Character I/O functions: fgetc( ): It is used to read a character from a file. Its syntax is: charvariable = fgetc(fileptr_variable);

fputc( ): It is used to write a character to a file. Its syntax is: fputc(charvariable, fileptr_variable);

b.String I/O functions: fgets( ): It is used to read string from file. Its syntax is: fgets(string, intvalue, fileptr_variable); int value : This is the maximum number of characters to be read

fputs( ): It is used to write a string to a file. Its syntax is: fputs(string, fileptrvariable);

2. Formatted I/O functions: fprintf( ): This function is used to write some integer, float, char or string to a file. Its syntax is: fprintf(fileptrvariable,”control string”, list variables);

fscanf( ): This function is used to read some integer, float char or string from a file. Its syntax is: fscanf(fileptrvariable,”control string”, & list_variables);

Creating and opening a file NOTE: To create or open the file you have to give proper location of the file.Lets say, you want to create a file named ‘test.txt’ inside folder named ‘demo’ inside ‘C’ directory then you have to give the location(path) as: C:\demo\test.txt or C://demo/test.txt (try on of these) This step is very important, if you location is not appropriate the file will not be created and you might not get what you want, so set the location very carefully

int main()
{
    FILE *fp;
    char ch;
    fp=fopen("/home/sandesh/datafiles/check.txt", "w");          //for windows: “C:\\check.txt”
    if(fp == NULL)
    {
        printf("File not created\n");
    }
    else
    {
        printf("File has been successfully created\n");
    }
    fclose(fp);
}

Writing a character into a file using fputc() Before you start writing any program make sure that you enter the correct/valid path/location

int main()
{
    FILE *fp;
    char ch;
    fp=fopen("/home/sandesh/datafiles/check.txt", "w");
    if(fp == NULL)
    {
        printf("File not created\n");
    }
    else
    {
        printf("File has been successfully created\n");
        ch='b';
        fputc(ch, fp);
        printf("character has been successfully written\n");

    }
    fclose(fp);
}

Reading a character from file using fgetc()

Int main()
{
    FILE *fp;
    char ch;
    fp=fopen("/home/sandesh/datafiles/check.txt", "r");
    if(fp == NULL)
    {
        printf("File donot exist\n");
    }
    else
    {
        printf("File has been opened\n");
        ch=fgetc(fp);
        printf("character is:%c\n", ch);
    }
    fclose(fp);
}

Writing a string

int main()
{
    FILE *fp;
    fp=fopen("/home/sandesh/datafiles/test.txt", "w");
    if(fp == NULL)
    {
        printf("File not created\n");
    }
    else
    {
        printf("File created\n");
        fputs("Hello people, how are you??", fp);
    }
    fclose(fp);
}

Reading string from file

Int main()
{
     FILE *fp;
     char str[30];
    fp=fopen("/home/sandesh/datafiles/test.txt", "r");
    if(fp == NULL)
    {
        printf("File doesn't exist\n");
    }
    else
    {
        printf("File opened\n");
        fgets(str,10, fp);    //if we keep int value 30 then while string will be fetched
        printf("%s", str);
    }
    fclose(fp);
}

To copy content of one file to another

int main()
{
     FILE *fp1, *fp2;
     char str[50];
     fp1= fopen("/home/sandesh/datafiles/test.txt", "r");
     fp2= fopen("/home/sandesh/datafiles/copied_test.txt", "w");

     if(fp1 == NULL || fp2 == NULL)
     {
        printf("Operation cant be performed\n");
     }
     else
     {
        fgets(str, 30, fp1);
        fputs(str, fp2);
        printf("Copy succesfull!!\n");
     }
     fclose(fp1);
     fclose(fp2);
}

To copy content of one file to another. Read source file and destination from user

int main()
{
     FILE *fp1, *fp2;
     char str[50];
     char src[50], dest[50];

     printf("Enter the location of source file\n");
     scanf("%s", src);

     printf("Enter the location of destination file\n");
     scanf("%s", dest);

     fp1= fopen(src, "r");
     fp2= fopen(dest, "w");

     if(fp1 == NULL || fp2 == NULL)
     {
        printf("Operation cant be performed\n");
     }
     else
     {
        fgets(str, 30, fp1);
        fputs(str, fp2);
        printf("Copy succesfull!!\n");
     }
     fclose(fp1);
     fclose(fp2);
}

Program to understand the use of fprintf()

int main()
{
    struct student
    {
        char name[30];
        int year;
    }std;

    FILE *fp;
    int n, i;
    fp=fopen("/home/sandesh/datafiles/student.txt", "w");
    if(fp==NULL)
    {
        printf("Operation cant be performed\n");
    }
    else
    {
        printf("Enter no of records:\t");
        scanf("%d", &n);

        for(i=0; i<n; i++)
        {
            printf("Enter the name\n");
            scanf("%s", std.name);
            printf("Enter the year\n");
            scanf("%d", &std.year);

            fprintf(fp, "%s %d", std.name,std.year);
        }
        fclose(fp);
    }
}

Use of fscanf()

int main()
{
    FILE *fp;
    char str[20], str1[20];
    fp=fopen("/home/sandesh/datafiles/student.txt", "r");
    if(fp==NULL)
    {
        printf("Operation cant be performed\n");
    }
    else
    {
        fscanf(fp, "%s%s", str, str1);
        printf("%s\n%s", str, str1);
        fclose(fp);
    }
}

use of fscanf() (reading the data through structure variable)

int main()
{
struct student
    {
        char name[30];
        int year;
    }std;

    FILE *fp;
    char str[20], str1[20];
    fp=fopen("/home/sandesh/datafiles/student.txt", "r");
    if(fp==NULL)
    {
        printf("Operation cant be performed\n");
    }
    else
    {
        while (fscanf(fp, "%s%d", std.name, &std.year) != EOF) 
        {
printf("%s%d \n", std.name, std.year);
            }
        fclose(fp);
    }
}

End of File (EOF): The file reading function need to know the end of file so that they can stop reading. When the end of file is reached, the opening system sends an end-of-file signal to the program. When the program receives this signal, the file reading function returns EOF, which is a constant defined in the file stdio.h and its value is -1.


Fread&Fwrite Function

Some other unformatted function: (i)fread( ) (ii)fwrite( )

fwrite( ): used for writing an entire block to a given file. fread( ): is used to read an entire block from a given file.

Their syntax are: fwrite(&ptr, sizeofarrayorstructure, numberofarrayorstructure, fptr); fread(&ptr, size_of _arrayorstructure, numberofstructureorarray, fptr);

Random Acess to File: We can acess the data stored in the file in two ways, sequently or random. So, far we have used only sequently acess in our programs. For example, if we want to acess the fortyfourth record then first forty three records should be read sequentially to reach the fortyforth record. In random acess, data can be accessed and processed randomly i.e. in this case the forty-forth record can be accessed directly. There is no need to read each record sequentially, if we want to acess a particularly record. Random acess takes takes less time than the sequential acess. C supports these functions for random acess file processing: -fseek( ) -ftell( ) -rewind( )

fseek( ): This function is used for setting the file position pointer at the specified byte. The syntax is: int fseek(FILE *fp, long displacement, int origin)

where fp is file pointer, displacement is long integer which can be positive or negative and it denotes the number of bytes which are skipped backward (if negative) or forward (if positive) from the position specified in the third argument. The third argument named origin is the position relative to which the displacement takes place. It can take one of these three values:

ConstantValuePosition
SEEK_SET0Beginning of file
SEEK_CURRENT1Current position
SEEK_END2End of File

Use of fseek()

int main () 
{ 
FILE *fp; 
fp = fopen("file.txt","w+"); 
fputs("This is our C Class", fp); 

fseek( fp, 7, SEEK_SET ); 
fputs(" C Programming Language", fp); 
fclose(fp); 
}

Output: This is C Programming Language

rewind( ): This function is used to move the file position pointer to the beginning of the file syntax: rewind(File fp);

ftell( ): This function returns the current position of the file pointer. The value is counted from the beginning of the file. The syntax is: *ftell(FILE fp);

Create a structure named employee having members: empName, age and salary. Use this structure to read the name, age and salary of employee and write entered information to a file ‘employee.dat’ in desktop in binary format. At last read the written information and display on the screen

Int main()
{
 struct employee
    {
        char empname[20];
        int age;
        float salary;
    }emp, emp_temp;

    FILE *fp;

    printf("Enter the name of employee\n");
    scanf("%s", emp.empname);

    printf("Enter the age\n");
    scanf("%d", &emp.age);

    printf("Enter the salary\n");
    scanf("%f", &emp.salary);

    fp = fopen("/home/sandesh/Desktop/employee.txt", "wb");
    if( fp == NULL )
    {
        printf("File cant be opened\n");
    }
    else
    {
        fwrite(&emp, sizeof(emp), 1, fp);
        fclose(fp);
    }

    fp=fopen("/home/sandesh/Desktop/employee.txt", "rb");
    fread( &emp_temp, sizeof(emp_temp), 1, fp);
    printf("Name=%s \t Age=%d", emp_temp.empname, emp_temp.age);
    fclose(fp);

}

Create a structure named student that has name, roll and marks as members. Assume appropriate types and size of member. Use this structure to read and display records of 3 students. Write an array of structure to a file & then read its content to display to the screen

int main()
{
  struct student
    {
        char name[20];
        int rn;
        float mark;
    }std[3], std1[3];

    FILE *fp;
    int i;

    for(i=0; i<3; i++)
    {
        printf("Enter the name\n");
        scanf("%s", std[i].name);

        printf("Enter the roll number\n");
        scanf("%d", &std[i].rn);

        printf("Enter the mark\n");
        scanf("%f", &std[i].mark);
    }

    printf("\n\nDisplaying the information before writing to file\n");
    for(i=0 ;i<3 ; i++)
    {
        printf("Name=%s\tRoll no.=%d\tMark=%f\n", std[i].name, std[i].rn, std[i].mark);
    }

    fp=fopen("/home/sandesh/datafiles/student_structure.txt", "w+b");
    if(fp==NULL)
    {
        printf("File cant be opened\n");
    }
    else
    {
        fwrite(&std, sizeof(std), 3, fp);
        printf("\n\nSuccessfully written to file!!\n");
        rewind(fp);

        fread(&std1, sizeof(std1), 3, fp);
        printf("\n\nReading from file\n");
        for(i=0; i<3; i++)
        {
            printf("Name=%s\tRoll number=%d\tMark=%f\n", std1[i].name, std1[i].rn,  std1[i].mark);
        }
        fclose(fp);
    }
}

Exam solution

Write a program to write any structure inforn:ation in a binary file and to read and display it later.Make a menu driven program to read and dispiay inforrnation from file [070 Chaitra]

struct info{        //assume any structure and assign the members to it
        char name[10];
        float price;
    }i;
FILE *fp;

void read_info();
void display_info();
int main()
{

    int choice;

    fp=fopen("/home/sandesh/datafiles/info_structure.txt", "w+b");
    if(fp==NULL)
    {
        printf("File could not be opened!!\n");
    }
    else
    {
        do
        {
            printf("\n\n-----MENU-----\n");
            printf("1.Enter 1 to enter new information\n");
            printf("2.Enter 2 to read and display the information\n");
            printf("3.Enter 3 to exit\n\n");
            scanf("%d", &choice);

            switch(choice)
            {
                case 1:
                    read_info();
                    break;

                case 2:
                    display_info();
                    break;

                case 3:
                    break;

                default:
                    printf("Unknown value!!\n");
             }
          }while(choice != 3);
    }

}

void read_info()
{
    printf("---Enter the following information:---\n");
    printf("Enter the name\n");
    scanf("%s", i.name);
    printf("Enter the price\n");
    scanf("%f", &i.price);

    fwrite(&i, sizeof(i), 1, fp);
    printf("--Read successful--\n\n");
}

void display_info()
{
    rewind(fp);
    fread(&i, sizeof(i), 1, fp);

    printf("---Entered information is:---\n");
    printf("Name:%s\n",i.name);
    printf("Price:%f\n", i.price);
    printf("--Display successful--\n\n");
}

CH 11: FORTRAN 8 hrs

Introduction

Fortran was originally developed by a team at IBM in 1957 for scientific calculations. Fortran, as derived from Formula Translating System, is a general-purpose, imperative programming language. It is used for numeric and scientific computing. Fortran allows both uppercase and lowercase letters.

Lets start from the basic structure of a fortran program: Program structure

program program_name 
implicit none 

! type declaration statements 
! executable statements             

end program program_name

All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program. Comment in fortran starts with (!)

The implicit none statement is used to inhibit a very old feature of Fortran that by default treats all variables that start with the letters i, j, k, l, m and n as integers and all other variables as real arguments. Implicit None should always be used. It prevents potential confusion in variable types, and makes detection of typographic errors easier.

Let’s write a program that adds two numbers and prints the result

program addNumbers 
implicit none 

! Type declarations 
real :: a, b, result 

! Executable statements 
a = 12.0 
b = 15.0 
result = a + b 
print *, 'The total is ', result 

end program addNumbers

Character Set The basic character set of Fortran contains − -the letters A … Z and a … z -the digits 0 … 9 -the underscore (_) character -the special characters = : + blank - * / ( ) [ ] , . $ ' ! " % & ; < > ?

Identifiers An identifier is a name used to identify a variable, procedure, or any other user-defined item. A name in Fortran must follow the following rules − -It cannot be longer than 31 characters. -It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_). -First character of a name must be a letter. -Names are case-insensitive

Data Types

Fortran provides five intrinsic data types. The five intrinsic types are − -Integer type -Real type -Complex type -Logical type -Character type

Integer type: The integer types can hold only integer values. Syntax: integer :: variable_name

Real type: It stores the floating point numbers, such as 2.0, 3.1415 etc Syntax: real :: variable_name

Complex type: This is used for storing complex numbers. For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i. The generic function cmplx() creates a complex number. Syntax: complex :: c

Logical Type: There are only two logical values: .true. and .false. Syntax: logical :: variable_name

Character Type: The character type stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. For example, character (len = 40) :: name name = “exam tomorrow” The expression, name(1:4) would give the substring “exam”

Constants: There are two types of constants − -Literal constants -Named constants

A literal constant have a value, but no name.A named constant has a value as well as a name. Named constants should be declared at the beginning of a program, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example, real, parameter :: pi = 3.1415927


Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Fortran provides the following types of operators − -Arithmetic Operators -Relational Operators -Logical Operators let us look at all these types of operators one by one.

Arithmetic Operators: Following table shows all the arithmetic operators supported by Fortran. Assume variable A holds 5 and variable B holds 3 then − Alt text

Relational Operators: Following table shows all the relational operators supported by Fortran. Assume variable A holds 10 and variable B holds 20, then − Alt text

Logical Operators: Logical operators in Fortran work only on logical values .true. and .false. The following table shows all the logical operators supported by Fortran. Assume variable A holds .true. and variable B holds .false. Then − Alt text


Input/Output Functions

We can read data from keyboard using the (read *) statement, and display output to the screen using the (print *) statement, respectively. This form of input-output is free format I/O, and it is called list-directed input-output. The free format simple I/O has the form − read *, item1, item2, item3… print *, item1, item2, item3…

However the formatted I/O gives you more flexibility over data transfer.

Formatted Input Output Formatted input output has the syntax as follows − read fmt, variable-list print fmt, variable-list

Where, fmt is the format specification variable-list is a list of the variables to be read from keyboard or written on screen

Format specification defines the way in which formatted data is displayed. It consists of a string, containing a list of edit descriptors in parentheses. An edit descriptor specifies the exact format, for example, width, digits after decimal point etc., in which characters and numbers are displayed.

Program to understand more about formatted output

program formattedPrint
implicit none

   real :: d=12.23432
   integer :: n = 300789, k = 45, i = 2
   character (len=18) :: str="hello guys morning"

   print "(i3)", k         
   print "(i6.3)", k         
   print "(3i10)", n, k, i     
   print "(i10,i3,i5)", n, k, i 
   print "(a18)",str 
   print "(f4.2)", d

end program formattedPrint


Control structures

(Goto, Do loop, If statements) GOTO 1. Unconditional GOTO statement: This statement is used to transfer the control to any other statement unconditionally. The general form is: GOTO n where n is the statement number to which the control must be transferred.In the GO TO statement, the number referenced cannot be a variable example: GOTO J is not valid.

2. Computed GOTO statement: Computed GOTO allows branching of the program according to the value of an integer expression. GOTO (label1, label2,… labeln) integer-expression If integer-expression is equal to 1 the program continues at statement label label1, if it is equal to 2 it goes to label2 and so on. If it is less then 1 or larger than n program continues on next line. Example:
ivar =2 … GOTO (10, 20, 30, 40) ivar It will jump to statement label 20

If statement 1. Arithmetic IF statement: This statement is used to transfer the control depending upon the value of an expression whether negative, zero or positive. General form: If (expression) n1,n2,n3 Where (expression) is a valid FORTRAN arithmetic expression enclosed within parenthesis. n1, n2, n3 are statement numbers. The value of the expression is evaluated first. If the value is negative the control goes to statement number n1, if it is zero, it goes to n2 and if it is positive, it goes to n3

2. Logical IF statement: The logical if condition checks any given logical condition and transfer the control accordingly. The general form of the statement is If (condn) Statement where condn is a logical condition, statement is an executable statement. If the condition is true the statement is executed and then goes to the next statement. If the condition is false the control goes to the next statement.

A program to print the fibonacci numbers using Logical If until the term exceeds 500

program fibonacci
implicit none

    integer :: F,S,T
    F=0
    S=1

20  T=F+S                    
    IF(T.GT.500) GOTO 11            
    PRINT *, T                    
    F=S                        
    S=T                        
    GOTO 20

11 end program fibonacci

3.If-then-else statement: The IF-THEN-ELSE statement is more useful and easy to handle than the logical if statement. The general form of the statement is

IF( condn) THEN 
S1 
S2
ELSE 
S1’ 
S2’ 
ENDIF

Where condn is a logical condition

A program to demonstrate the use of simple if else

program simpleifelse
implicit none

    integer :: t
    PRINT *,'ENTER THE NUMBER OF TERMS'
    read *, t

    if(t.eq.20) THEN
    print *, 'You cant enter number 20. Try entering sth else!!'
    ELSE
    print *, 'Seems like you did not enter the number 20. Well done!!'
    ENDIF

end program simpleifelse

A program to add the digits of number

program adddigits
implicit none

    integer :: n, rem
    integer :: suum=0 
    PRINT *,'ENTER THE NUMBER'
    read *, n

  10 rem=mod(n,10)        
    suum=suum+rem
    n=n/10

    if(n.ne.0) THEN
    goto 10
    ELSE
    print *, suum
    ENDIF

end program adddigits


DO LOOPS

The DO LOOP is used whenever a particular job is to be repeated number of times. The general form of the DO loop is DO I v=v1, v2, v3
………………… ………………… ………………… Where , I is the last statement in the DO loop, v is an integer variable. It is called the ruining variable for the DO loop. v1 is an integer variable or constant. This is the initial values for the running variable. v2 is an integer variable or constant quantity. The running variable will not take a value beyond v2. v3 is an integer variable or constant. This is the increment value. If the increment is 1 then this can be omitted.

A program to check whether an entered number is prime or not

program prime
implicit none

    INTEGER :: num, countt, i
    print *, 'Enter a number'
    READ *,num
    countt=0
DO 10 i=2,num-1,1
    IF(MOD(num,i).EQ.0) THEN        
    countt=countt+1                
    ENDIF
10 CONTINUE

IF(countt.EQ.0) THEN
PRINT *,num,'IS PRIME'
ELSE
PRINT *,num,'IS NOT PRIME'
ENDIF
end program prime


Implied Do Loop

Implied DO loops are DO loops in the sense that they control the execution of some iterative procedure, but are different than DO loops because they do not use the do statement to control the execution. Basically, these loops are a shorthand that was introduced in FORTRAN to provide a method for array initialization and to cut back on the number of lines of code that where required in the program. The general syntax of Implied Do Loop is: ( Do-var = initial, final, step ) ----------- end do

example of implied do loop we can use it to read arrays:

integer, dimenson(5):: arr
do i=1,5
    arr(i)=i*2
end do
Do loopImplied Do loop
The DO LOOP is used whenever a particular job is to be repeated number of timesThese loops are a shorthand that was introduced in FORTRAN to provide a method for array initialization and to cut back on the number of lines of code that where required in the program
It uses continue statementThere is no use of continue statement in Implied do loop
It does not end with end doIt ends with end do
Write its syntaxWrite its syntax


Array

Declaring Arrays Arrays are declared with the dimension attribute. For example, to declare a one-dimensional array named number, of real numbers containing 5 elements, you write, real, dimension(5) :: numbers // float number[5]; The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).

To create a 5 x 5 two-dimensional array of integers named matrix, you write− integer, dimension (5,5) :: matrix // int matrix[5][5]

You can also declare an array with some explicit lower bound, for example − real, dimension(2:6) :: numbers

Assigning Values You can either assign values to individual members, like, numbers(1) = 2.0
or, you can use a loop, do i =1,5 numbers(i) = i * 2.0 end do

One-dimensional array elements can be directly assigned values using a short hand symbol, called array constructor, like, numbers = (/1.5, 3.2,4.5,0.9,7.2 /)

please note that there are no spaces allowed between the brackets ‘( ‘and the backslash For two-dimensional array we have to use the do loop two time(one for row one for column), like ,

    do i=1,5
        do j=1,5
        Read *, mat(i,j)
        end do
    end do

A simple program to illustrate the concept of array in fortran

program arrayProg
implicit none

   real, dimension(5) :: numbers !one dimensional integer array
   integer, dimension(3,3) :: matrix !two dimensional real array
   integer ::  i , j 

   !assigning some values to the array numbers
   do i=1,5
      numbers(i) = i * 2.0
   end do

   !display the values
   do i = 1, 5
      Print *, numbers(i)
   end do

   !assigning some values to the array matrix
   do i=1,3
      do j = 1, 3
         matrix(i, j) = i+j
      end do
   end do
 !display the values
   do i=1,3
      do j = 1, 3
         Print *, matrix(i,j)
      end do
   end do
end program arrayProg

A program to read an array and sort it in fortran

program sortingarray
implicit none

real, dimension(5) :: numbers !one dimensional integer array
real :: temp     !temp variable is used for swapping
integer :: i,j

 !assigning some values to the array 
   do i=1,5
      read *, numbers(i)
   end do

   !sorting the values
   do i=1,5                
      do j = i+1, 5            
         if(numbers(i).gt.numbers(j)) THEN        
            temp = numbers(i)                        
            numbers(i)=numbers(j)
            numbers(j)=temp
         ENDIF
      end do
   end do

   !displaying the sorted array
   do i=1,5
        print *, numbers(i)
   end do
end program sortingarray

A program to read two matrices and add their elements in fortran

Program matrixadd
IMPLICIT NONE

integer, DIMENSION(3,3):: mata, matb, matc
integer :: i,j

print *, 'enter the elements of first matrix'
do i=1,3
    do j=1,3
    read *, mata(i,j)
    end do
end do

print *, 'enter the elements of second matrix'
do i=1,3
    do j=1,3
    read *, matb(i,j)
    end do
end do

do i=1,3
    do j=1,3                    
    matc(i,j) = mata(i,j) + matb(i,j)
    end do                    
end do

print *, 'the sum of two matrices is:'
do i=1,3
    do j=1,3
    print *, matc(i,j)
    end do
end do

End Program matrixadd


Derived data type:Structure

Fortran allows you to define derived data types. A derived data type is also called a structure, and it can consist of data objects of different types. Derived data types are used to represent a record. E.g. you want to keep track of your books in a library, you might want to track the following attributes about each book − Title Author Subject Book ID

Defining a Derived data type To define a derived data type, the type and end type statements are used . The type statement defines a new data type, with more than one member for your program. The format of the type statement is this − type typename declarations end type

Here is the way you would declare the Book structure −

type Books 
character(len = 50) :: title 
character(len = 50) :: author 
character(len = 150) :: subject 
integer :: book_id 
end type Books

Accessing Structure Members At first we have to create a variable of the structure: type(Books) :: book1 The components of the structure can be accessed using the component selector character (%) − book1%title = "Basics of C" book1%author = ”Sandesh Gyawali" book1%subject = "C Programming" book1%book_id = 122333

Note that there are no spaces before and after the % symbol.

The following program illustrates the above concepts −

program deriveDataType
implicit none

   !type declaration
   type Books
      character(len = 50) :: title
      character(len = 50) :: author
      character(len = 150) :: subject
      integer :: book_id
   end type Books

   !declaring type variables
   type(Books) :: book1 

   !accessing the components of the structure

   book1%title = "Basics of C"
   book1%author = "Sandesh Gyawali"
   book1%subject = "C Programming"
   book1%book_id = 122333 


   !display book info

   Print *, book1%title 
   Print *, book1%author 
   Print *, book1%subject 
   Print *, book1%book_id  
end program deriveDataType

Most frequently asked programming question from FORTRAN Write a program to read an array of size n and sort it in ascending(or descending) order. Then print the second largest number(or second smallest)

Other question to practise Write a program to check whether a number is palindrome or not Write a program to check whether a number is armstrong or not Write a program to read m*n matrix from the user and then find its transpose. Display both matrices Write a program to subtract matrixb from matrixa

Exam questions.

Write a FORTRAN program to sort 10 integers given from user and display the second largest integer [076 Ashwin Back]

program sortingarray
implicit none

real, dimension(10) :: numbers !one dimensional integer array
real :: temp     !temp variable is used for swapping
integer :: i,j

 !assigning some values to the array 
   do i=1,10
      read *, numbers(i)
   end do

   !sorting the values (ascending order)
   do i=1,10                
      do j = i+1, 10            
         if(numbers(i).gt.numbers(j)) THEN        
            temp = numbers(i)                        
            numbers(i)=numbers(j)
            numbers(j)=temp
         ENDIF
      end do
   end do

   !displaying the second largest integer
   print *,'Second largest number is: ',numbers(9)

end program sortingarray

Comments