Cs8251 - Programming in C Unit I Basics of C Programming 1. What Are The Different Programming Paradigms?
Cs8251 - Programming in C Unit I Basics of C Programming 1. What Are The Different Programming Paradigms?
net
CS8251 - PROGRAMMING IN C
UNIT I
BASICS OF C PROGRAMMING
Objects have their own internal (encapsulated) state and public interfaces. Object
orientation can be:
o Class-based: Objects get state and behavior based on membership in a class.
o Prototype-based: Objects get behavior from a prototype object.
www.AUNewsBlog.net
www.AUNewsBlog.net
organized, such as grouping a code into units along with the state that is modified by the
code. Yet others are concerned mainly with the style of syntax and grammar.
3.What is C language?
The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system. It was named 'C' because many of its
features were derived from an earlier language called 'B'.
4.Uses of C.
C language is primarily used for system programming. The portability, efficiency,
the ability to access specific hardware addresses and low runtime demand on
system resources makes it a good choice for implementing operating systems and
embedded system applications.
C has been so widely accepted by professionals that compilers, libraries and
interpreters of other programming languages are often implemented in C.
C is widely used to implement end-user applications.
C is a robust language.
Programs written in C can be reused.
Program written in C are fast and efficient.
It is machine independent and highly portable language.
C language allows manipulation of bits, bytes and addresses.
C is relatively small programming language. C has only 32 keywords.
C encourages users to write additional library function of their own.
Many other high level languages have been developed based on C. For example
C++ and PERL.
6.Structure of a C Program.
www.AUNewsBlog.net
www.AUNewsBlog.net
Link section :- The link section provides instructions to the compiler to link functions from
the system library such as using the #include directive.
Example :-
#include <stdio.h>
#include <conio.h>
Definition Section :- Sometime we require some fix values in the entire program,
called as constants. The definition section defines all these symbolic constants.
Example :-
#define pi 3.14
Global declaration section :- Some variables are required in more than one function.
These variable has to defined outside the main function, hence as global variable.
Global declaration section defines these variables.
Example :-
int globalX;
We will discuss more about variable, data types and their scope in upcoming sections.
main () function section :- Every C program must have one main() function section.
As the execution of the program always begins with the first executable statement of
the main function. This section contains two parts; declaration part and executable
part.
o Declaration part declares all the variable used in the executable part.
o Executable part consists of at least one statement and these two parts must
appear between the opening and the closing braces.
Example :-
www.AUNewsBlog.net
www.AUNewsBlog.net
void main()
{
int a=10; // declaration part
printf("%d",a); // executable part
}
7. Enlist Keywords in C.
C has a set of reserved words often known as keywords. These cannot be used as an
identifier. All keywords are basically a sequence of characters that have a fixed meaning. By
convention all keywords must be written in lowercase letters. following table contains a list
of keywords in C.
do if static while
When you complete this tutorial, the meaning and utility of each keyword will automatically
become clear.
During the execution of C program, three process are involved. They are :-
Compilation :- Compilation refers to the processing of source code files (.c, .cpp) and
the creation of an object file. This step doesn't create anything the user can actually
run. The object code contains the machine instructions for the CPU and calls to the
operating system application programming interface (API). Object file
has .obj extension.
Linking :- Linking refers to the creation of a single executable file ( .exe ) from
multiple object files.
www.AUNewsBlog.net
www.AUNewsBlog.net
Loading :- Loading is the process of put the executable file (.exe) into memory prior
to execution.
First a program written in c, called source code and the file is known as source file. It
has .c extension.
Then the source code is compiled by a Compiler. If there exists some syntax error(s),
it won't generate the object code. Go to editor and rectify the error(s). Otherwise, it
create a new file, called as object file (.obj).
Then a special program called linker is involved to link the object file with some
library files and other object files. The result of linking is saved into a new file called
as an executable file (.exe).
Now this executable file is loaded into primary memory for execution by a special
component of OS known as Loader.
Bring an executable file residing on disk into memory and start it running.
It creates new address space for the program before executing.
Copies instructions and data into address space.
www.AUNewsBlog.net
www.AUNewsBlog.net
An error is anything in our code that prevent a program from running correctly. In the
computer world, program errors are also called bugs and the art of pinpointing a bug and
fixing it is called debugging. When all the bugs are out, the program is correct.
Data types are means to identify the type of data along with set of rules for permissible
operations. The data type of a variable determines how much space it occupies in storage
(memory) and how the bit pattern stored is interpreted.
The two major aspects of data in C are data type and storage class . C language is rich in
its data types. It provides a predefined set of data types for handling the data of different
types such as character, integer, real, string etc. Data in C belongs to one of the following
types :-
Fundamental types
Derived types
C language provides very few basic data types. Following table lists the data type, their size,
range, and usage.
Keyword Size in
Data type Range Use
Used bytes
www.AUNewsBlog.net
www.AUNewsBlog.net
Floating
float 4 3.4E-38 to 3.4E+38 To store floating point numbers
point
Derived Types
The data type that has been constructed from the fundamental data types is called as derived
data type. The derived data types in C classified into two groups. They are :-
Built-in types
User-defined data types
1. Arrays
2. Pointers
3. Structure
4. Union
There are some derived data types that are defined by the user. These are called as user
defined derived data types. These are :-
1. typedef
2. enum
The constants refer to fixed values that the program may not alter during its
www.AUNewsBlog.net
www.AUNewsBlog.net
Keywords are certain reserved words that have standard and pre-defined meaning in ‘C’.
These keywords can be used only for their intended purpose.
These variables only exist inside the specific function that creates them. They are
unknown to other functions and to the main program. As such, they are normally
implemented using a stack. Local variables cease to exist once the function that created them
is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the
program. They are implemented by associating memory locations with variable names.
They do not get recreated if the function is recalled.
22. What are Operators? Mention their types in C.
www.AUNewsBlog.net
www.AUNewsBlog.net
operators:
a. Arithmetic Operators
b. Relational Operators
c. Logical Operators
d. Bitwise Operators
e. Assignment Operators
f. Misc Operators
Example:
int x,y;
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into
float.
25.What is the difference between ++a and a++?
Statement Description
www.AUNewsBlog.net
www.AUNewsBlog.net
nested if You can use one if or else if statement inside another if or else if
statements statement(s).
switch statement A switch statement allows a variable to be tested for equality against a
list of values.
www.AUNewsBlog.net
www.AUNewsBlog.net
( ) Parenthesis
[ ] Square Bracket
{ } Curly Brace
# Hash
, Comma
37.Differentiate between formatted and unformatted you input and output functions?
Formatted I/P functions:
These functions allow us to supply the input in a fixed format and let us obtain the
output in the specified form. Formatted output converts the internal binary representation of
the data to ASCII characters which are written to the output file.
Unformatted I/O functions:
There are several standard library functions available under this category-those that
can deal with a string of characters. Unformatted Input/Output is the most basic form of
input/output. Unformatted input/output transfers the internal binary representation of the data
directly between memory and the file.
38. What are the pre-processor directives?
1. Macro Inclusion
2. Conditional Inclusion
3. File Inclusion
39. What are conditional Inclusions in Preprocessor Directive?
Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif)
For example:
1 #ifdef TABLE_SIZE
2 int table[TABLE_SIZE];
3 #endif
www.AUNewsBlog.net
www.AUNewsBlog.net
UNIT II
ARRAYS AND STRINGS
1. What is an array?
An array is a group of similar data types stored under a common name. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
Example:
int a[10];
Here a[10] is an array with 10 values.
www.AUNewsBlog.net
www.AUNewsBlog.net
8. Define Strings.
Strings:
The group of characters, digit and symbols enclosed within quotes is called as Stirng
(or) character
Arrays. Strings are always terminated with ‘\0’ (NULL) character. The compiler
automatically adds ‘\0’ at the end of the strings.
Example:
char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’E’,’\0’};
www.AUNewsBlog.net
www.AUNewsBlog.net
1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost
item is stored in an array.
2. Re-establish the heap.
3. Repeat steps 1 and 2 until there are no more items left in the heap.
www.AUNewsBlog.net
www.AUNewsBlog.net
UNIT III
FUNCTIONS AND POINTERS
www.AUNewsBlog.net
www.AUNewsBlog.net
Union save memory space as the size of a union variable is equal to its largest sized
member. In contrast, the size of a structure variable is equal to the sum of the sizes
of all its individual member elements.
Unions are particularly useful in situation where there is a need to use only one of
its member elements at any given point of time.
5. What is a pointer?
A pointer is a memory variable that stores a memory address. It can have any name
that is legal for another variable and it is declared in the same fashion like other variables
but it is always denoted by pre fixing ‘*’ operator.
www.AUNewsBlog.net
www.AUNewsBlog.net
Features:
9. Differentiate call by value and call by reference.
www.AUNewsBlog.net
www.AUNewsBlog.net
Array Pointer
Array allocates space automatically Pointer is explicitly assigned to point to an
allocated space
It cannot be resized It can be resized using realloc()
It cannot be reassigned It can be reassigned
Size of array name gives the number of bytes Size of pointer name returns the number of
occupied by the array pointer used to store the pointer variable.
realloac() - Used to modify the size of the previously allocated memory space.
#include <stdio.h>
{
return 1;
}
return i * factorial(i - 1);
int main()
{
int i = 15;
}
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016
www.AUNewsBlog.net
www.AUNewsBlog.net
13. State the advantages of user defined functions over pre-defined functions.
A user defined function allows the programmer to define the exact function of the
module as per requirement. This may not be the case with predefined function. It may
or may not serve the desired purpose completely.
A user defined function gives flexibility to the programmer to use optimal
programming instructions, which is not possible in predefined function.
14. Write the syntax for pointers to structure.
Struct S
char datatype1;
int datatype2;
float datatype3;
};
Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion. Recursions use
more memory and are generally slow. Instead, you can use loop.
If a function calls itself again and again, then that function is called Recursive function.
Example:
void recursion()
{
www.AUNewsBlog.net
www.AUNewsBlog.net
int main()
{
recursion();
}
Macros are more efficient (and faster) than function, because their corresponding code
is inserted directly at the point where the macro is called. There is no overhead involved in
using a macro like there is in placing a call to a function. However, macros are generally
small and cannot handle large, complex coding constructs. In cases where large, complex
constructs are to handled, functions are more suited, additionally; macros are expanded
inline, which means that the code is replicated for each occurrence of a macro.
ceil(x)
sqrt(x)
log(x)
pow(x,y)
sin(x)
19. List the header files in ‘C’ language.
Function Definition:
The function definition block is used to define the user-defined functions with
statements.
www.AUNewsBlog.net
www.AUNewsBlog.net
UNIT IV
STRUCTURES
Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
All members occupy separate memory location, Different interpretations for the same memory
hence different interpretations of the same location are possible. Conservation of memory
memory is
location are not possible. Consumes more space possible
compared to union.
3. Define Structure in C.
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
Many structure variables can be declared for same structure and memory will be
allocated for each separately.
www.AUNewsBlog.net
www.AUNewsBlog.net
int year;
} student;
This defines a new type student variables of type student can be declared as follows.
student st_rec;
{
member
definition;
member
definition;
...
member definition;
} [one or more union variables];
www.AUNewsBlog.net
www.AUNewsBlog.net
RAM. This means that the variable has a maximum size equal to the register size (usually one
word) and cant have the unary '&' operator applied to it (as it does not have a memory
location).
{
register int Miles;
}
{
int Count;
auto int
Month;
}
The example above defines two variables with the same storage class. auto can only be used
within functions, i.e. local variables.
www.AUNewsBlog.net
www.AUNewsBlog.net
code files as well as the file name that we want that appears when an error takes place.
Its format is:
#line number "filename"
Where number is the new line number that will be assigned to the next code line.
The line numbers of successive lines will be increased one by one from this point on.
char datatype1;
int datatype2;
float datatype3;
};
www.AUNewsBlog.net
www.AUNewsBlog.net
pointer) is used. The end of the list is indicated by a NULLpointer. In order to create a linked
list of integers, we define each of its element (referred as node) using the following
declaration.
struct node_type {
int data;
struct node_type *next;
};
struct node_type *start = NULL;
Note: The second member points to a node of same type.
A linear linked list illustration:
2. Types of Files
www.AUNewsBlog.net
www.AUNewsBlog.net
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.
When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and
takes bigger storage space.
Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security
than text files.
File
Meaning of Mode During Inexistence of file
Mode
www.AUNewsBlog.net
www.AUNewsBlog.net
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in If the file exists, its contents are overwritten. If
wb+
binary mode. the file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
www.AUNewsBlog.net
www.AUNewsBlog.net
1. Sequential Access — The data are placed in the file in a sequence like beads on a
string. Data are processed in sequence, one after another. To reach a particular item of
data, all the data that proceeds it first must be read.
2. Random Access — The data are placed into the file by going directly to the location
in the file assigned to each data item. Data are processed in any order. A particular
item of data can be reached by going directly to it, without looking at any other data.
8. What is file?
A file is a semi-permanent, named collection of data. A File is usually stored on
magnetic media, such as a hard disk or magnetic tape.
Semi-permanent means that data saved in files stays safe until it is deleted or
modified.
Named means that a particular collection of data on a disk has a name,
like mydata.dat and access to the collection is done by using its name.
A very common data processing operation is report generation. This is when the
data in a file (or files) is processed by a program to generate a report of some kind. The report
might be a summary of the financial state of a corporation, or a series of bills for its
customers, or a series of checks to be mailed to its employees.
Large corporations have very large databases kept on many high capacity disks and
processed by programs running on large computers called mainframe
www.AUNewsBlog.net
www.AUNewsBlog.net
The picture shows the main file and the transaction file as input to a program. The
output is a new, updated main file. The previous version of the file can be kept as backup.
Management information science is the field that studies how to organize and
manage the information of a corporation using computers and files. Usually the business
school of a university has a management information science department.
You might think that all files should be random access. But random access files are much
more difficult to imp.
www.AUNewsBlog.net
www.AUNewsBlog.net
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
PART B
UNIT I
BASICS OF C PROGRAMMING
www.AUNewsBlog.net
www.AUNewsBlog.net
UNIT II
ARRAYS AND STRINGS
1. What is an array? Discuss how to initialize a one dimensional and two dimensional
arrays with suitable example? [RE][UN]
2. Write a C program to search an element in a given array using linear and binary
search. [AP]
3. Write a C program for sorting an array of numbers using selection sort. [AP]
4. Write a C program to addition, subtract and multiply two matrices. [AP]
5. Write a C program to scaling transformations of a matrix. [AP]
6. Write a C program to determinant a matrix. [AP]
7. Write a C program to transpose a matrix. [AP]
8. Write a C program to find mean, median and mode. [AP]
9. Explain in detail about string and list the various string operations with example.
[RE][UN]
10. Write a C program to find out the length and reverse of the string without using built-
in function. [AP][AN]
UNIT III
FUNCTIONS AND POINTERS
UNIT IV
STRUCTURES
1. What is a structure? Create a structure with data members of various types and
declare two structure variables. Write a program to read data into these and print the
same. Justify the need for structured data type. [RE][AP]
2. Write a C program to store the employee information using structure and search a
particular employee using Employee number. [AP]
3. Define and declare a nested structure to store date, which including day, month and
year. [RE][UN]
4. Explain about array of structures and pointers in structures with example program.
[RE]
5. Write a C program to create mark sheet for students using self referential structure.
[AP]
6. Discuss about dynamic memory allocation with suitable example C program.
[RE]
www.AUNewsBlog.net
www.AUNewsBlog.net
7. Explain about singly linked list with suitable example C program. [RE]
UNIT V
FILE PROCESSING
www.AUNewsBlog.net