H. Ateeq Ahmed,: B. Tech Iyearisem
H. Ateeq Ahmed,: B. Tech Iyearisem
As per R19
B. Tech
I Year I Sem
Syllabus
By
H. Ateeq Ahmed, M.Tech.,
Asst. Professor of CSE,
Kurnool.
First I thank Almighty God for giving me the knowledge to learn and teach
various students.
magical way…”
Website: engineeringdrive.blogspot.in
UNIT-I
COMPUTER FUNDAMENTALS
Classification of Computers
The computer systems can be classified on the following basis:
1. On the basis of size.
2. On the basis of functionality.
3. On the basis of data handling.
Classification on the basis of size
1. Super computers :
The super computers are the most high performing system. A supercomputer is a
computer with a high level of performance compared to a general-purpose computer.
Supercomputers actually play an important role in the field of computation, and are used
for intensive computation tasks in various fields, including quantum mechanics, weather
forecasting, climate research, oil and gas exploration, molecular modeling, and physical
simulations.
eg: PARAM, jaguar, roadrunner.
2. Mainframe computers :
These are commonly called as big iron, they are usually used by big organisations for
bulk data processing such as statics, census data processing, transaction processing and
are widely used as the severs as these systems has a higher processing capability as
compared to the other classes of computers, most of these mainframe architectures were
established in 1960s.
Eg: IBM z Series, System z9 and System z10 servers.
3. Mini computers :
These computers came into the market in mid 1960s and were sold at a much cheaper
price than the main frames, they were actually designed for control, instrumentation,
human interaction, and communication switching as distinct from calculation and record
keeping, later they became very popular for personal uses with evolution.
They usually took up one or a few inch rack cabinets, compared with the large
mainframes that could fill a room, there was a new term “MINICOMPUTERS” coined
Eg: Personal Laptop, PC etc.
4. Micro computers :
A microcomputer is a small, relatively inexpensive computer with a microprocessor as
its CPU. It includes a microprocessor, memory, and minimal I/O circuitry mounted on a
single printed circuit board.The previous to these computers, mainframes and
minicomputers, were comparatively much larger, hard to maintain and more expensive.
They actually formed the foundation for present day microcomputers and smart gadgets
that we use in day to day life.
Eg: Tablets, Smartwatches.
2. Workstation :
Those are the computers designed to primarily to be used by single user at a time. They
run multi-user operating systems. They are the ones which we use for our day to day
personal / commercial work.
3. Information Appliances :
They are the portable devices which are designed to perform a limited set of tasks like
basic calculations, playing multimedia, browsing internet etc. They are generally
referred as the mobile devices. They have very limited memory and flexibility and
generally run on “as-is” basis.
4. Embedded computers : They are the computing devices which are used in other
machines to serve limited set of requirements. They follow instructions from the non-
volatile memory and they are not required to execute reboot or reset.
2. Digital : A computer that performs calculations and logical operations with quantities
represented as digits, usually in the binary number system of “0” and “1”.
3. Hybrid : A computer that processes both analog and digital data, Hybrid computer is a
digital computer that accepts analog signals, converts them to digital and processes them
in digital form.
Anatomy of a Computer
The CPU is the heart and brain of a computer. It receives data input, executes instructions,
and processes information. It communicates with input/output (I/O) devices, which send and
receive data to and from the CPU.
Programming Languages
A computer programming language is a language used to write computer programs,
which involves a computer performing some kind of computation or algorithm and possibly
control external devices such as printers, disk drives, robots, and so on. For
example, PostScript programs are frequently created by another program to control a
computer printer or display.
More generally, a programming language may describe computation on some,
possibly abstract, machine. It is generally accepted that a complete specification for a
programming language includes a description, possibly idealized, of a machine or processor
for that language.
In most practical contexts, a programming language involves a computer;
consequently, programming languages are usually defined and studied this way.
Programming languages differ from natural languages in that natural languages are
only used for interaction between people, while programming languages also allow humans
to communicate instructions to machines.
function or set of similar functions is coded in a separate module or submodule, which means
that code can be loaded into memory more efficiently and that modules can be reused in other
programs. After a module has been tested individually, it is then integrated with other
modules into the overall program structure.
Almost any language can use structured programming techniques to avoid common
pitfalls of unstructured languages. Unstructured programming must rely upon the discipline
of the developer to avoid structural problems, and as a consequence may result in poorly
organized programs. Most modern procedural languages include features that encourage
structured programming. Object-oriented programming (OOP) can be thought of as a type of
structured programming, uses structured programming techniques for program flow, and adds
more structure for data to the model.
Compiler
A compiler is a computer program that transforms code written in a high-level
programming language into the machine code. It is a program which translates the human-
readable code to a language a computer processor understands (binary 1 and 0 bits). The
computer processes the machine code to perform the corresponding tasks.
A compiler should comply with the syntax rule of that programming language in
which it is written. However, the compiler is only a program and cannot fix errors found in
that program. So, if you make a mistake, you need to make changes in the syntax of your
program. Otherwise, it will not compile.
Interpreter
An interpreter is a computer program, which coverts each high-level program
statement into the machine code. This includes source code, pre-compiled code, and scripts.
Both compiler and interpreters do the same job which is converting higher level
programming language to machine code.
However, a compiler will convert the code into machine code (create an exe) before
program run. Interpreters convert code into machine code when the program is run.
Let us discuss the difference between Linker and loader with the help of a comparison chart.
Program Execution
Whenever a C program file is compiled and executed, the compiler generates some
files with the same name as that of the C program file but with different extensions. So, what
are these files and how are they created?
Below image shows the compilation process with the files created at each step of the
compilation process:
Every file that contains a C program must be saved with „.c‟ extension. This is
necessary for the compiler to understand that this is a C program file. Suppose a program file
is named, first.c. The file first.c is called the source file which keeps the code of the program.
Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no
error, then it stores the file as a .obj file of the same name, called the object file. So, here it
will create the first.obj. This .obj file is not executable. The process is continued by the
Linker which finally gives a .exe file which is executable.
Pseudocode
“Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations.“
It is used for creating an outline or a rough draft of a program.
Pseudocode summarizes a program‟s flow, but excludes underlying details.
System designers write pseudocode to ensure that programmers understand a software
project's requirements and align code accordingly.
Pseudocode is not an actual programming language.
So it cannot be compiled into an executable program.
It uses short terms or simple English language syntaxes to write code for programs
before it is actually converted into a specific programming language.
This is done to identify top level flow errors, and understand the programming data
flows that the final program is going to use.
This definitely helps save time during actual programming as conceptual errors have
been already corrected.
Firstly, program description and functionality is gathered and then pseudocode is used
to create statements to achieve the required results for a program.
Detailed pseudocode is inspected and verified by the designer‟s team or programmers
to match design specifications.
Catching errors or wrong program flow at the pseudocode stage is beneficial for
development as it is less costly than catching them later.
Once the pseudocode is accepted by the team, it is rewritten using the vocabulary and
syntax of a programming language.
Example
C code: if (i < 10) { i++; }
pseudocode: if i is less than 10, increment i by 1.
Example
Consider the algorithm to convert and display the distance from miles to kms.
1. Determine the outcome of your code. What is the specific problem you want to solve or
the task you want it to accomplish? Once you have a solid idea of what you're aiming to
accomplish, you can determine the steps it will take to get there.
2. Decide on a starting point. Finding your starting and ending point are crucial to listing the
steps of the process. To determine a starting point, determine the answers to these questions:
3. Find the ending point of the algorithm. As with the starting point, you can find the end
point of your algorithm by focusing on these questions:
What facts will we learn from the process?
What changes from the start to the end?
What will be added or no longer exist?
4. List the steps from start to finish. Start with broad steps. To use a real-world example,
let's say your goal is to have lasagna for dinner. You've determined that the starting point is to
find a recipe, and that the end result is that you'll have a lasagna fully cooked and ready to eat
by 7 PM.
5. Determine how you will accomplish each step. Now that you have a step-by-step outline,
it's time to think about how you might code each step. Which language will you use? What
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 26
resources are available? What's the most efficient way to accomplish each step in that
language? Incorporate some of that code into your algorithm. Expand each step until you've
detailed the entire process.
6. Review the algorithm. Now that you've written your algorithm, it's time to evaluate the
process. Your algorithm is designed to accomplish something specific, and you'll need it to
start writing your program.
*******
UNIT-II
INTRODUCTION TO COMPUTER PROBLEM SOLVING
Introduction
Top-down Design
Construction of Loops
Implementation of Algorithms
Documentation of programs
Debugging Programs
Redundant computations
Referencing array elements
Inefficiency due to late termination
Early detection of desired output conditions
FUNDAMENTAL ALGORITHMS
Exchanging the values of two variables
Counting
Thus
Finally
Factorial Computation
*******
UNIT-III
TYPES, OPERATORS AND EXPRESSIONS
Introduction to the C Language
C is a structured programming language.
It was developed by M. Dennis Ritchie in 1972 at Bell Laboratories.
It is considered a high-level language because it allows the programmer to concentrate
on the problem at hand and not worry about the machine that the program will be
using.
While many languages claim to be machine independent, C is one of the closest to
achieving that goal.
That is another reason why it is used by software developers whose applications have
to run on many different hardware platforms.
Variable Names
“A Variable is the name given to memory location to store data value in it.”
Unlike constant, the value of a variable can be changed.
A variable name must be chosen in such a way that it improves the readability of a program.
Syntax
Data_type var_name=var_value;
Example
int x=10;
The above variable „x‟ contains value 10 and it is of integer data type.
Identifiers
One feature present in all computer languages is the identifier.
Identifiers allow us to name data and other objects in the program.
Each identified object in the computer is stored at a unique address.
If we didn‟t have identifiers that we could use to symbolically represent data
locations, we would have to know and use object‟s addresses.
Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located.
Example
int x;
x is known as identifier.
Rules for Identifiers
An identifier must start with a letter or underscore: it may not have a space or a
hyphen.
An identifier must not be a keyword.
It can consist of letters, digits or underscore.
Identifier names are case sensitive.
The maximum length of identifier must be less than or equal to 31 characters.
Signed Integers:
Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and I bit for storing its sign.
The left most bit i.e. 16th bit is used for storing the sign.
1-> Negative number
0-> Positive number
Example:
signed int x=10;
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
Magnitude
Sign
0-> Positive number
Unsigned Integers
Unsigned integers uses all 16 bits to store the magnitude.
Example Program
Write a C program to display the value of an integer variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
clrscr();
printf("Value of a=%d",a);
getch();
}
Expected Output
Value of a=10
Example Program
Write a C program to display the value of a floating variable.
#include<stdio.h>
#include<conio.h>
void main()
{
float a=2.5;
clrscr();
printf("Value of a=%f",a);
getch();
}
Expected Output
Value of a=2.500000
Example Program
Write a C program to display a single character.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch=‟A‟;
clrscr();
printf("Character=%c",ch);
getch();
}
Expected Output
Character=A
Constants
Constants are data values that cannot be changed during the execution of a program.
Like variables, constants have a type.
In this section, we discuss Boolean, character, integer, real, complex, and string constants.
Character constants
A character constant is enclosed in single quotes.
Integer constants
Real constants
Complex constants
The two components of a complex constant must be of the same precision, that is, if the real
part is type double, then the imaginary part must also be type double.
Declarations
We are required to declare our variables to the C compiler before you use them.
You do this by providing a list of variables near the beginning of the program.
That way, the compiler knows what the variables are called and what type of variables
they are (what values they can contain).
Officially, this process is known as declaring your variables.
Example
int count;
char key;
char lastname[30];
Three variables are declared here: an integer variable, count; a character variable,
key; and a character variable, lastname, which is a string that can be as many as 30
characters long.
Doing this at the beginning of the program tells the compiler several things. First, it
says, "These things are variables!" That way, when the compiler sees lastname in a
program, it knows that it's a string variable.
Second, the declarations tell the compiler which type of variable is being used. The
compiler knows that integer values fit into the count variable, for example.
Third, the compiler knows how much storage space to set aside for the variables.
OPERATORS
Operators are C tokens which can join together individual constants, variables, array elements
etc.
C operators are classified into the following categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
Relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Assignment operators
It is used to assign the result of an expression to a variable.
It is denoted as „=‟.
Example Program
Write a C program to show the use of increment & decrement operators.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
x=5;
y=5;
clrscr();
x++;
printf("x=%d",x);
y--;
printf("\ny=%d",y);
getch();
}
Expected Output
x=6
y=4
Conditional operator
It is also known as ternary operator.
Syntax
exp1?exp2:exp3;
The value of exp1 is evaluated first, If it is true, value of exp2 is evaluated otherwise exp3 is
evaluated.
Example Program
Write a C program to find the biggest of two numbers using Conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,big;
clrscr();
a=20;
b=10;
big=(a>b)?a:b;
printf("Big number is %d",big);
getch();
}
Expected Output
Big number is 20
Bitwise operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR(XOR)
~ One‟s Complement
<< Shift left
>> Shift right
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 54
Special operators
(i) Comma operator(,)
It is used to separate the variables
Eg:
int a,b,c;
Example-1
x=a-b/3+c*2-1
Now let a=9, b=12, c=3 then
x=9-12/3+3*2-1
The above expression is evaluated as follows.
x=9-4+3*2-1
x=9-4+6-1
x=15-4-1
x=15-5
x=10
If parenthesis are used then expression within the parenthesis is evaluated first.
Example-2
x=9-12/6*(2-1)
x=9-12/6*1
x=9-2*1
x=9-2
x=7
When an expression contains two operators of equal priority then the tie between
them is settled using the associativity of operators.
Associativity are of two types
Left to Right
Right to Left
Left to Right associativity means that the left operand must not be involved in any
other sub expression.
Similarly, Right to Left associativity means that the right operand should not involved
in any sub expressions.
Evaluating Expressions
When an expression consists of different types of variables, compiler follows rules of type
conversions.
RULE:
If the operands are of different types, the lower type is automatically converted to higher type
and the result will be of higher type.
The result of expression is then converted to the type of variable present at the left hand side
of the assignment operator.
Example
int i;
float f;
double d;
int j=i*d+f/i;
int j=double type+float type
int j=double type.
Syntax
printf(“control string”,arg1,arg2,….,argn);
Examples
printf(“%d”,a);
printf(“%d%c”,num,ch);
Printing Characters
To print an individual character, use %c.
To print a string, use %s.
Printing Numbers
You can use either %d or %i to display a signed integer in decimal format.
These format specifiers are equivalent; both are supported for historical reasons, of
which one is the desire to maintain an equivalence relationship with the scanf( )
format specifiers.
To output an unsigned integer, use %u.
The %f format specifier displays numbers in floating point.
The matching argument must be of type double.
Displaying an Address
If you want to display an address, use %p.
This format specifier causes printf( ) to display a machine address in a format
compatible with the type of addressing used by the computer.
( b) scanf()
This function is used to read values for variables from keyboard.
Syntax
scanf(“control string”,address_list);
where control string specifies the type of values that have to read from the keyboard.
Examples
scanf(“%d”,&a);
scanf(“%d%f”,&a,&b);
scanf(“%d%f%c”,&a,&b,&c);
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 57
CONTROL FLOW
Expression Statements
The previous unit covers expressions thoroughly.
However, a few special points are mentioned here.
Remember, an expression statement is simply a valid expression followed by a
semicolon, as in
func(); /* a function call */
a = b+c; /* an assignment statement */
b+f(); /* a valid, but strange statement */
; /* an empty statement */
The first expression statement executes a function call.
The second is an assignment. T
The third expression, though strange, is still evaluated by the compiler because the
function f( ) may perform some necessary task.
The final example shows that a statement can be empty (sometimes called a null
statement).
Block Statements
Block statements are simply groups of related statements that are treated as a unit.
The statements that make up a block are logically bound together.
Block statements are also called compound statements.
A block is begun with a { and terminated by its matching }.
Programmers use block statements most commonly to create a multi statement target
for some other statement, such as if.
However, you may place a block statement anywhere you would put any other
statement.
For example, this is perfectly valid (although unusual) C code:
#include <stdio.h>
void main()
{
int i;
{ /* a free-standing block statement */
i = 120;
printf(''%d", i);
}
}
CONTROL STATEMENTS
Control statements are the statements that allow the programmer to specify the next statement
that must be executed depending on some conditions.
(i) Simple if
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
age=20;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
getch();
}
Expected Output
Eligible for voting.
(ii) if else
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
age=15;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
else
{
printf("\nNot eligible for voting.");
}
getch();
}
Expected Output
Not eligible for voting.
void main()
{
float per;
per=76;
clrscr();
if(per>=70 && per<=100)
{
printf("Distinction");
}
else if(per>=60 && per<70)
{
printf("\nFirst Class");
}
else if(per>=50 && per<60)
{
printf("\nSecond Class");
}
else
{
printf("\nFailed");
}
getch();
}
Expected Output
Distinction
(iv) switch
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
day=5;
clrscr();
switch(day)
{
case 0:
printf("SUNDAY");
break;
case 1:
printf("\nMONDAY");
break;
case 2:
printf("\nTUESDAY");
break;
case 3:
printf("\nWEDNESDAY");
break;
case 4:
printf("\nTHURSDAY");
break;
case 5:
printf("\nFRIDAY");
break;
case 6:
printf("\nSATURDAY");
break;
default:
printf("\nInvalid Day number");
}
getch();
}
Expected Output
FRIDAY
Basics of functions
A function is a self-contained block of statements that perform some specific task for the
program.
Functions are used to provide modularity to the software. By using functions, you can divide
complex tasks into small manageable tasks. The use of functions can also help avoid
duplication of work. For example, if you have written the function for calculating the square
root, you can use that function in multiple programs
Library Functions:
As the name suggests, library functions are nothing but commonly required functions
grouped together and stored in a Library.
This library of functions is present on the disk and is written for us by people who
write compilers for us.
Almost always a compiler comes with a library of standard functions.
Examples:
printf(), scanf() etc.
Syntax:
return-type function-name(parameter-list)
{
local variables;
statements;
}
Advantages of functions:
A function provides modularity and readability to the software.
To define the function, you have to define the function name, the return data type and
the formal parameters.
It is recommended to declare a function prototype before using a function.
If the function does not return any value, then you have to set the return data type as
void.
A call to a function should be compatible with the function definition.
Example Program
//Using userdefined function
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\nHow r u?");
message();
getch();
}
Expected Output
How r u?
I am fine!
Explanation
Here, main( ) itself is a function and through it we are calling the function
message( ). What do we mean when we say that main( ) „calls‟ the function message(
)? We mean that the control passes to the function message( ).
The activity of main( ) is temporarily suspended; it falls asleep while the message( )
function wakes up and goes to work.
When the message( ) function completes the execution of statements, the control
returns to main( ), which comes to life again and begins executing its code at the
exact point where it left off.
Thus, main( ) becomes the „calling‟ function, whereas message( ) becomes the
„called‟ function.
“Scope is defined as the area of the program in which the variable is visible or accessible.”
Consider the following function which contains the local variable „i‟ as follows.
void fun()
{
int i=10; // „i‟ is a local variable
printf(“i=%d”,i);
}
Hence the scope of variable „i‟ is within the function fun().
Default initial value − An unpredictable value, which is often called a garbage value.
Life − Till the control remains within the block in which the variable is
defined.
Example Program
void main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
getch();
}
The above program shows how an automatic storage class variable is
declared, and the fact that if the variable is not initialized it contains a garbage value.
Life - Till the control remains within the block in which the variable is
defined.
A value stored in a CPU register can always be accessed faster than the one that is
stored in memory. Therefore, if a variable is used at many places in a program it is better to
declare its storage class as register. A good example of frequently used variables is loop
counters. We can name their storage class as register.
Example Program
void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
getch();
}
Here, even though we have declared the storage class of i as register, we cannot say for
sure that the value of i would be stored in a CPU register. Why? Because the number of CPU
registers are limited, and they may be busy doing some other task. What happens in such an
event, the variable works as if its storage class is auto.
Let us now compare the two programs and their output given below to understand the
difference between the automatic and static storage classes
The above programs consist of two functions main( ) and increment( ). The function
increment( ) gets called from main( ) thrice. Each time it increments the value of i and prints
it. The only difference in the two programs is that one uses an auto storage class for variable
i, whereas the other uses static storage class.
Like auto variables, static variables are also local to the block in which they are
declared. The difference between them is that static variables don‟t disappear when the
function is no longer active. Their values persist. If the control comes back to the same
function again the static variables have the same values they had last time around.
Scope − Global.
External variables differ from those we have already discussed in that their scope is global,
not local. External variables are declared outside all functions, yet are available to all
functions that care to use them.
Example Program
int x = 21 ;
void main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ;
getch();
}
int y = 31 ;
Here, x and y both are global variables. Since both of them have been defined outside
all the functions both enjoy external storage class. Note the difference between the following:
extern int y ;
int y = 31 ;
Here the first statement is a declaration, whereas the second is the definition. When
we declare a variable no space is reserved for it, whereas, when we define it space gets
reserved for it in memory. We had to declare y since it is being used in printf( ) before it‟s
definition is encountered. There was no need to declare x since its definition is done before
its usage. Also remember that a variable can be declared several times but can be defined
only once.
Recursion
In C, it is possible for the functions to call themselves.
A function is called „recursive‟ if a statement within the body of a function calls the same
function.
Thus recursion is the process of defining something in terms of itself.
Example Program
Let us now see a simple example of recursion. Suppose we want to calculate the factorial
value of an integer. As we know, the factorial of a number is the product of all the integers
between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be
expressed as 4! = 4 * 3! where „!‟ stands for factorial. Thus factorial of a number can be
expressed in the form of itself. Hence this can be programmed using recursion as follows.
//Recursion Example
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f;
if(n==0 || n==1)
return(1);
void main()
{
int n,res;
clrscr();
printf("\nEnter the number:");
scanf("%d",&n);
res=fact(n);
printf("\nFactorial=%d",res);
getch();
}
Expected Output
Enter the number:5
Factorial=120
(i) #define
The #define directive defines an identifier and a character sequence (a set of characters) that
will be substituted for the identifier each time it is encountered in the source file. The
identifier is referred to as a macro name and the replacement process as macro replacement.
Example
#define UPPER 25
This statement is called „macro definition‟ or more commonly, just a „macro‟. What purpose
does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in
the program with 25.
Example Program
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of
UPPER, which has already been defined before main( ) through the statement.
(ii) #include
The second preprocessor directive is file inclusion. This directive causes one file to be
included in another.
The preprocessor command for file inclusion looks like this:
#include "filename"
and it simply causes the entire contents of filename to be inserted into the source code at that
point in the program.
It is common for the files that are to be included to have a .h extension. This
extension stands for „header file‟, possibly because it contains statements which when
included go to the head of your program. The prototypes of all the library functions are
grouped into different categories and then stored in different header files. For example
prototypes of all mathematics related functions are stored in the header file „math.h‟,
prototypes of console input/output functions are stored in the header file „conio.h‟, and so on.
Actually there exist two ways to write #include statement. These are:
#include "filename"
#include <filename>
The meaning of each of these forms is given below:
This command would look for the file goto.c in the current directory
#include "goto.c" as well as the specified list of directories as mentioned in the include
search path that might have been set up.
This command would look for the file goto.c in the specified list of
#include <goto.c>
directories only.
*******
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 79
UNIT-IV
FACTORING METHODS
int i = 3 ;
Expected Output
Address of i = 65524
Value of i = 3
Value of i=3
Pointer Operators
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C‟s
‘address of’ operator. The expression &i returns the address of the variable i, which in this
case happens to be 65524. Since 65524 represents an address, there is no question of a sign
being associated with it. Hence it is printed out using %u, which is a format specifier for
printing an unsigned integer. We have been using the „&‟ operator all the time in the scanf( )
statement.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives
the value stored at a particular address. The „value at address‟ operator is also called
‘indirection’ operator.
Pointer
“A Pointer is a variable that can store the address of another variable”.
Syntax
Data-type *variable;
Example
int *i;
In the above declaration, „*‟ indicates that „i‟ is a pointer variable.
Example Program
//Program to show the use of pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,*ptr;
clrscr();
ptr=&a; // address of a is stored in ptr
printf("\nAddress of a is %u",ptr); // displaying the address of a
printf("\nValue of a is %d",*ptr); // displaying the value of a
getch();
}
Memory Representation
a ptr
10 65524
The expression &a gives the address of the variable a. This address can be collected in a
variable, by saying,
ptr = &a ;
But remember that ptr is not an ordinary variable like any other integer variable. It is a
variable that contains the address of other variable (a in this case). Since ptr is a variable the
compiler must provide it space in the memory.
Expected Output
Address of a is 65524
Value of a is 10
Pointers to Functions
A particularly confusing yet powerful feature of C is the function pointer.
A function has a physical location in memory that can be assigned to a pointer.
This address is the entry point of the function and it is the address used when the
function is called.
Once a pointer points to a function, the function can be called through that pointer.
Function pointers also allow functions to be passed as arguments to other functions.
“A pointer to function is a variable that can store the address of functions in c
language”.
Along with storing the address of a variable, a pointer has the ability to store the
address of functions that are used in the program.
Example Programs
(1)
//Pointer to built in function
#include<stdio.h>
#include<conio.h>
void main()
{
int (*ptr)(); // declaration of a pointer to function variable
ptr=&clrscr;
(*ptr)();
printf("\nAddress of clrscr()=%u",ptr);
getch();
}
Expected Output
Address of clrscr()=2813
Pointer Arithmetic
Like normal variables, pointers can also be used to perform various arithmetic operations like
addition, subtraction etc.
//Program to show the use Arithmetic operations on pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*res,*ptr1,*ptr2;
clrscr();
*res=*ptr1+*ptr2; // addition
printf("\nSum=%d",*res);
*res=*ptr1-*ptr2; // subtraction
printf("\nDifference=%d",*res);
*res=*ptr1**ptr2; // multiplication
printf("\nProduct=%d",*res);
*res=*ptr1/(*ptr2); // division
printf("\nDivision=%d",*res);
*res=*ptr1%*ptr2; // mod
printf("\nRemainder=%d",*res);
getch();
}
Expected Output
Enter any two numbers:
20
10
Sum=30
Difference=10
Product=200
Division=2
Remainder=0
Both statements will return the fifth element. Remember, arrays start at 0. To access the fifth
element, you must use 4 to index str. You also add 4 to the pointer p1 to access the fifth
element because p1 currently points to the first element of str. (Recall that an array name
without an index returns the starting address of the array, which is the address of the first
element.)
Example Program
Pointer to Pointer
You can have a pointer point to another pointer that points to the target value. This situation
is called multiple indirection, or pointers to pointers. Pointers to pointers can be confusing.
Figure 5-3 helps clarify the concept of multiple indirection. As you can see, the value of a
normal pointer is the address of the object that contains the desired value. In the case of a
pointer to a pointer, the first pointer contains the address of the second pointer, which points
to the object that contains the desired value.
Figure 5-3
Single and multiple indirection
“A pointer to pointer is a variable that can store the address of another pointer
variable.”
Example Program
//pointer to pointer
void main()
{
int a=10,*ptr1,*ptr2;
clrscr();
ptr1=&a;
printf("\nAddress of a is %u",ptr1);
printf("\nValue of a is %d",*ptr1);
ptr2=&ptr1; // a ponter ptr2 storing the address of another pointer ptr1
printf("\nAddress of ptr1 is %u",ptr2);
printf("\nValue of ptr1 is %u",*ptr2);
getch();
}
Memory Representation
a ptr1 ptr2
10 65524 65522
Arrays
“An array is collection of similar elements that are stored in sequential memory locations.”
An ordinary variable can hold only one value at a time where as an array can store
multiple values of same type.
An array is a collection of variables of the same type that are referred to through a
common name.
A specific element in an array is accessed by an index. In C, all arrays consist of
contiguous memory locations.
The lowest address corresponds to the first element and the highest address to the last
element.
Arrays can have from one to several dimensions.
The most common array is the string, which is simply an array of characters
terminated by a null.
Array Initialization methods
Like other variables, arrays must be explicitly declared so that the compiler can
allocate space for them in memory. Here, type declares the base type of the array, which is
the type of each element in the array, and size defines how many elements the array will hold.
For example, to declare a 100- element array called balance of type float, use this statement:
float balance[100];
Example
int a[5];
a
Here, int specifies the type of the variable, just as it does with ordinary variables and
„a‟ specifies the name of the variable.
The [5] however is new. The number 5 tells how many elements of the type int will
be in our array. This number is often called the „dimension‟ of the array.
The bracket ( [ ] ) tells the compiler that we are dealing with an array.
a[0] refers to the first element in the array whereas the whole number 65516 is its
address in memory.
Array Initialization
So far we have used arrays that did not have any values in them to begin with.
We managed to store values in them during program execution.
Let us now see how to initialize an array while declaring it.
Example
Array elements are referred to using subscript; the lowest subscript is always 0 and
the highest subscript is (size –1). If you refer to an array element by using an out-of-range
subscript, you will get an error. You can refer to any element as a[0], a[1], a[2], etc
Thus, an array is a collection of similar elements. These similar elements could be all
ints, or all floats, or all chars, etc. Usually, the array of characters is called a „string‟,
whereas an array of ints or floats is called simply an array. Remember that all elements of
any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of
which 5 are ints and 5 are floats.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={2,4,6,8,10};
clrscr();
printf("\nFirst element=%d",a[0]);
printf("\nFifth element=%d",a[4]);
getch();
}
Expected Output
First element=2
Fifth element=10
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 96
Row Index
Memory Representation:
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[0][1]
2 4 6 8 10 12
65516 65518 65520 65522 65524 65526
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{2,4},{6,8},{10,12}},i,j;
clrscr();
printf("The array elements are");
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 97
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n%d",a[i][j]);
}
}
getch();
}
Expected Output
The array elements are
2
4
6
8
10
12
Example Program
void main(int argc,char *arg[])
{
int a,b,c;
clrscr();
a=atoi(arg[1]); // atoi() converts string to number
b=atoi(arg[2]);
c=a+b;
printf("\nSum=%d",c);
getch();
}
Expected Output
C:\TC>sum 10 20
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 98
Sum=30
Number of arguments=3
Explanation
In the above output, the three arguments are sum, 10 and 20.
By default, the argument “sum” is stored in arg[0] whereas 10 and 20 are stored in arg[1],
arg[2] respectively.
The argument in the main i.e argc counts the number of arguments.
Complicated Declarations
Most of the times declarations are simple to read, but it is hard to read some declarations
which involve pointer to functions. For example, consider the following declaration from
“signal.h”.
Example
int (*fp) ();
fp * () int
ARRAY TECHNIQUES
*******
UNIT-V
SORTING AND SEARCHING
Sorting refers to ordering data in an increasing or decreasing fashion according to
some linear relationship among the data items.
Searching is a process of locating a particular element present in a given set of
elements. The element may be a record, a table, or a file.
Searching Algorithms are designed to check for an element or retrieve an element
from any data structure where it is stored.
Based on the type of search operation, these algorithms are generally classified into two
categories:
1. Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search
is made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data
collection.
2. Binary Search
Binary search is a fast search algorithm. This search algorithm works on the principle of
divide and conquer. For this algorithm to work properly, the data collection should be in
the sorted form.
Sorting by selection
Selection sort is a simple sorting algorithm.
This sorting algorithm is an in-place comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left end and the unsorted part at the right
end.
Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the
leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets.
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the lowest
value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in
the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Insertion Sort
This is an in-place comparison-based sorting algorithm.
Here, a sub-list is maintained which is always sorted.
For example, the lower part of an array is maintained to be sorted.
An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate
place and then it has to be inserted there.
Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array).
This algorithm is not suitable for large data sets.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
So we swap them.
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list.
Sorting by Partitioning
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array
of data into smaller arrays.
A large array is partitioned into two arrays one of which holds values smaller than the
specified value, say pivot, based on which the partition is made and another array
holds values greater than the pivot value.
Quick sort partitions an array and then calls itself recursively twice to sort the two
resulting subarrays.
This algorithm is quite efficient for large-sized data sets.
The pivot value divides the list into two parts. And recursively, we find the pivot for each
sub-lists until all lists contains only one element.
Binary Search
Binary search looks for a particular item by comparing the middle most item of the
collection.
If a match occurs, then the index of item is returned.
If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the subarray reduces
to zero.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is more than what we are looking for.
So, the value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a match.
STRUCTURES
We have seen earlier how ordinary variables can hold one piece of information and
how arrays can hold a number of pieces of information of the same data type. These two data
types can handle a great variety of situations. But quite often we deal with entities that are
collection of dissimilar data types.
(a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
(b) Use a structure variable.
In the first approach, the program becomes more difficult to handle as the number of
items relating to the book go on increasing. For example, we would be required to use a
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 114
number of arrays, if we also decide to store name of the publisher, date of purchase of book,
etc. To solve this problem, C provides a special data type—the structure.
Structure Definition
A structure contains a number of data types grouped together.
These data types may or may not be of the same type.
Unlike arrays which can store elements of same data type, a structure can hold data of
different data types.
Declaring a Structure
The general form of a structure declaration statement is given below:
Syntax
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};
Example
struct book
{
char name ;
float price ;
int pages ;
};
The above statement defines a new data type called struct book. Each variable of this
data type will consist of a character variable called name, a float variable called price and an
integer variable called pages.
Once the new structure data type has been defined one or more variables can be
declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the
type struct book, as,
This statement sets aside space in memory. It makes available space to hold all the
elements in the structure—in this case, 7 bytes—one for name, four for price and two for
pages. These bytes are always in adjacent memory locations.
If we so desire, we can combine the declaration of the structure type and the structure
variables in one statement.
For example,
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2, b3 ;
(or)
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
Important points about structure declaration
The closing brace in the structure type declaration must be followed by a semicolon.
It is important to understand that a structure type declaration does not tell the compiler
to reserve any space in memory. All a structure declaration does is, it defines the
„form‟ of the structure.
Usually structure type declaration appears at the top of the source code file, before
any variables or functions are defined. In very large programs they are usually put in a
separate header file, and the file is included (using the preprocessor directive
#include) in whichever program we want to use this structure type.
Initialization of structures
Like primary variables and arrays, structure variables can also be initialized where they are
declared. The format used is quite similar to that used to initiate arrays.
struct book
{
char name[10] ;
float price ;
int pages ;
};
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;
So to refer to pages of the structure defined in our sample program we have to use,
b1.pages
Similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable and after the dot there must
always be a structure element.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b1={"C Language",275.50,450}; // Initialization of structure variable
clrscr();
printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.pages);
getch();
}
Expected Output
Book Name=C Language
Price=275.50
Pages=450
Expected Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Example Program
void main()
{
struct book
{
char name[20];
float price;
int page;
}b1;
clrscr();
printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.page);
getch();
}
Expected Output
Enter the name, price, pages of book
CP
275.50
370
Book Name=CP
Price=275.50
Pages=370
Arrays of Structures
If we want to store data of 100 books we would be required to use 100 different
structure variables from b1 to b100, which is definitely not very convenient.
A better approach would be to use an array of structures.
The syntax we use to reference each element of the array b is similar to the syntax
used for arrays of ints and chars.
For example, we refer to zeroth book‟s price as b[0].price. Similarly, we refer first
book‟s pages as b[1].pages.
Example Program
//Array of structures
struct student
{
int rno;
char name[20];
};
void main()
{
struct student s[2]={{25,"Ritchie"},{20,"Babbage"}}; // structure array initialization
int i;
clrscr();
printf("\n***Students Details***");
for(i=0;i<2;i++)
{
printf("\nRoll no=%d \nName=%s",s[i].rno,s[i].name);
printf("\n-----------------\n");
getch();
}
Expected Output
***Students Details***
Roll no=25
Name=Ritchie
-----------------
Roll no=20
Name=Babbage
-----------------
void main()
{
struct book
{
char name[20];
char author[20];
int price;
};
struct book b={"Computer","Ateeq",250};
clrscr();
display(b.name,b.author,b.price); // passing individual structure elements to display()
getch();
}
void display(char *n,char *a,int p)
{
printf("\nBook Name:%s \nAuthor:%s \nPrice:%d",n,a,p);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250
In the above program, we are passing the base addresses of the arrays name and
author, and the value stored in price.
Thus, this is a mixed call—a call by reference as well as a call by value.
Example Program
//to pass an entire structure
void display(); // function prototype
void main()
{
struct book b={"Computer","Ateeq",200};
clrscr();
display(b); // passing entire structure variable „b‟
getch();
}
void display(struct book b1)
{
printf("\nName=%s \nAuthor=%s \nPrice=%d",b1.name,b1.author,b1.price);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250
Example Program
void display(); // function prototype
struct book // structure definition outside the main()
{
char name[20];
char author[20];
int price;
};
void main()
{
struct book b={"Computer","Ateeq",200};
clrscr();
display(&b); // passing address of structure variable „b‟ to display()
getch();
}
void display(struct book *b1)
{
printf("\nName=%s \nAuthor=%s \nPrice=%d",b1->name,b1->author,b1->price);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250
Pointers to structures
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly
we can have a pointer pointing to a struct.
Such pointers are known as „structure pointers‟.
//Pointer to structure
void main()
{
struct student
{
char name[20];
int rno;
float per;
};
struct student s={"Taufeeq",25,71.00};
struct student *ptr;
ptr=&s; // pointer “ptr” pointing to structure variable „s‟
We can‟t use ptr.name or ptr.rno because ptr is not a structure variable but a pointer
to a structure, and the dot operator requires a structure variable on its left.
In such cases C provides an operator ->, called an arrow operator to refer to the
structure elements.
Remember that on the left hand side of the ‘.’ structure operator, there must always be
a structure variable, whereas on the left hand side of the „->’ operator there must
always be a pointer to a structure.
Memory Representation
b1.name b1.rno b1.per
Taufeeq 25 71.00
65472
65498
Example
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example „link‟ is a pointer to a structure of type „node‟.
Hence, the structure „node‟ is a self-referential structure with „link‟ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Table Lookup
A lookup table, also known as LUT, is an array used in computer programming that
holds values which would otherwise need to be calculated.
The table may be manually populated when the program is written, or the program
may populate the table with values as it calculates them.
When the values are needed later, the program can look them up,
saving CPU resources.
Typedef
“typedef provides the facility of providing alternative names for the basic data types in C
such as int, pointers and structures”.
A program that carries out so many tasks would be very big in size. In such a program if we
start using the normal integer data type to represent variables that hold different entities we
would soon lose track of what that integer value actually represents. This can be overcome by
using typdef.
Example Programs
(1)
//using typdef with simple data types
void main()
{
typedef int integer; // using integer instead of int
integer a;
a=10;
clrscr();
printf("\na=%d",a);
getch();
}
Expected Output
a=10
(2)
//Using typedef with pointers
void main()
{
int a=10;
typedef int* integer;
integer ptr; // ptr is a pointer to int
clrscr();
ptr=&a;
printf("\nAddress of a is %u",ptr);
printf("\nValue of a is %d",*ptr);
getch();
}
Expected Output
Address of a is 65524
Value of a is 10
(3)
//using typedef with structure
struct student
{
int rno;
char name[15];
};
void main()
{
typedef struct student profile;
profile s={25,"Ahmed"};
clrscr();
printf("\nRollno=%d \nName=%s",s.rno,s.name);
getch();
}
Expected Output
Rollno=25
Name=Ahmed
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 124
Bit Fields
Bit field provides exact amount of bits required for storage of values.
If the variable value is 1 or 0, we need a single bit to store it.
Similarly, if the variable value is between 0 and 3, the two bits are sufficient for
storing these values.
In the same what, if the variable value is between 0 and 7 the three bits are enough to
hold the values.
To hold the information we use variables.
The variables occupy a minimum of one byte for char and two bytes for integer.
Instead of using complete integer if bits are used, space of memory can be saved.
Syntax
struct numbers
{
unsigned int first:2;
unsigned int second:3;
};
The colon(:) in the above declaration tells the compiler that bit
fields are used in the structure and the number after it indicates how many bits are required to
allot to the field.
Example Program
struct numbers
{
unsigned int first:2;
unsigned int second:3;
};
void main()
{
struct numbers n;
clrscr();
n.first=3;
n.second=7;
printf("\nFirst Number:%d",n.first);
printf("\nSecond Number:%d",n.second);
getch();
}
Expected Output
First Number:3
Second Number:7
Unions
Like structure, a union can hold data belonging to different data types but it hold only
one object at a time.
In the structure each member has its own memory locations whereas, members of
unions have same memory locations.
The union requires bytes that are equal to the number of bytes required for the largest
member.
For example, if the union contains char, integer and float then the number of bytes
reserved in the memory is 4 bytes (i.e. the size of float).
Unlike structure members which can be initialized all at the same time, only one
union member should be initialized at a time.
Syntax
The syntax of union is similar to the structure which is shown below
Example Program
//To show the difference between structure & union
struct student1 // structure
{
int rno;
char grade;
};
union student2 //union
{
int rno;
char grade;
};
void main()
{
struct student1 s={25,'A'}; // initialization of structure members at a time
union student2 u;
clrscr();
printf("\nRollno=%d",s.rno);
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 126
printf("\nGrade=%c",s.grade);
Example Program
Rollno=25
Grade=A
Rollno=50
Grade=B
Size of Structure=3 Bytes
Size of Union=2 Bytes
In the above, the size of structure is sum of the sizes of all its
members i.e. int & char which is (2+1)=3 bytes whereas the size of union is the size of the
member which belongs to largest data type i.e. int which is of 2 bytes.
Formatted input-Scanf
[Refer UNIT-III, Page No.]
File access
In C, a file may be anything from a disk file to a terminal or printer. You associate a
stream with a specific file by performing an open operation. Once a file is open, information
can be exchanged between it and your program. Not all files have the same capabilities. For
example, a disk file can support random access, while some printers cannot. This brings up an
important point about the C I/O system: All streams are the same, but all files are not.
Opening a File
The fopen( ) function opens a stream for use and links a file with that stream.
Then it returns the file pointer associated with that file.
Most often (and for the rest of this discussion), the file is a disk file.
where filename is a pointer to a string of characters that make up a valid filename and
may include a path specification.
The string pointed to by mode determines how the file will be opened.
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 128
The following code uses fopen( ) to open a file named TEST for output.
FILE *fp;
fp = fopen("test", "w");
Although the preceding code is technically correct, you will usually see it written like this:
FILE *fp;
if ((fp = fopen("test","w"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
This method will detect any error in opening a file, such as a write-protected or a full
disk, before your program attempts to write to it. In general, you will always want to confirm
that fopen( ) succeeded before attempting any other operations on the file.
Closing a File
The fclose( ) function closes a stream that was opened by a call to fopen( ). It writes
any data still remaining in the disk buffer to the file and does a formal operating-system-level
close on the file. Failure to close a stream invites all kinds of trouble, including lost data,
destroyed files, and possible intermittent errors in your program. fclose( ) also frees the file
control block associated with the stream, making it available for reuse. Since there is a limit
to the number of files you can have open at any one time, you may have to close one file
before opening another.
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 129
Example Program
/* Write some non-character data to a disk file and read it back. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
double d = 12.23;
int i = 101;
long 1 = 123023L;
if((fp=fopen("test", "wb+"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, fp);
fwrite(&i, sizeof(int), 1, fp);
fwrite(&l, sizeof(long), 1, fp);
rewind(fp);
fread(&d, sizeof
(double), 1, fp);
fread(&i, sizeof(int), 1, fp);
fread(&l, sizeof(long), 1, fp);
printf("%f %d %ld", d, i, 1);
fclose(fp);
return 0;
}
Miscellaneous Functions
Miscellaneous functions use the address letter M followed by two digits.
They perform a group of instructions such as coolant on/off, spindle on/off, tool
change, program stop, or program end.
They are often referred to as machine functions or M-functions.
*******