Unit i Basics of c Programming
Unit i Basics of c Programming
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has
become such a popular language that a variety of software programs are written using this
language. The greatest advantage of using C for programming is that it can be easily used on
different types of computers. Many other programming languages such as C++ and Java are also
based on C which means that you will be able to learn them easily in the future. Today, C is
widely used with the UNIX operating system.
Programming Languages
The purpose of using computers is to solve problems, which are difficult to solve manually. So
the computer user must concentrate on the development of good algorithms for solving
problems. After preparing the algorithms, the programmer or user has to concentrate the
programming language which is understandable by the computer.
Computer programming languages are developed with the primary objectives of facilitating a
large number of people to use computer without the need to know the details of internal structure
of the computer.
Application of C programming Language
The C programming language has been instrumental in the development of a wide array of
software applications due to its efficiency, portability, and close-to-hardware capabilities. Some
notable applications include:
1. Operating Systems: C has been fundamental in creating robust operating systems. For
instance, the UNIX operating system was developed using C, and many modern operating
systems, including various versions of Windows and Linux, have components implemented in C.
CS3251 Programming in C – UNIT I
2. Embedded Systems: Due to its ability to interact directly with hardware, C is extensively
used in embedded systems. This includes programming microcontrollers and developing
firmware for devices like automotive controllers, medical instruments, and consumer electronics.
3. Compilers and Interpreters: C's performance and low-level capabilities make it an ideal
choice for developing compilers and interpreters for various programming languages. Many
prominent compilers, such as Clang and GCC, are implemented in C.
4. Database Systems: Several database engines are developed using C due to its efficiency and
control over system resources. For example, MySQL, a widely used relational database
management system, is written in C.
7. System Utilities and Command-Line Tools: C is a top choice for developing system utilities
and command-line tools due to its efficiency and control over system resources. Many essential
tools in various operating systems are implemented in C.
These applications highlight C's versatility and enduring relevance in software development. Its
balance of low-level hardware access and high-level programming constructs makes it a
powerful tool across various domains.
Structure of C program
A C program contains one or more functions, where a function is defined as a group of
statements that perform a well-defined task. Figure 1.1 shows the structure of a C program. The
statements in a function are written in a logical sequence to perform a specific task. The main()
CS3251 Programming in C – UNIT I
function is the most important function and is a part of every C program. Rather, the execution
of a C program begins with this function.
From the structure given in Fig. 1.1, we can conclude that a C program can have any number of
functions depending on the tasks that have to be performed, and each function can have any
number of statements arranged according to specific meaningful sequence. Note that
programmers can choose any name for functions. It is not mandatory to write Function1,
Function2, etc., with an exception that every program must contain one function that has its
name as main().
Page 2
CS3251 Programming in C – UNIT I
Data type determines the set of values that a data item can take and the operations that can be
performed on the item. C language provides four basic data types. Table 1.2 lists the data types,
their size, range, and usage for a C programmer.
Constants
A constant is an entity whose value can‟t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point
number, character or a string.
The rules for writing Floating point Literal constants in an exponential form:
A Floating point Literal constants in an exponential form has two parts: the mantissa
part and the exponent part. Both are separated by e or E.
The mantissa part can be either positive or negative. The default sign is positive.
The mantissa part should have at least one digit.
The exponent part should have at least one digit
The exponent part cannot have a decimal point.
No special characters and blank spaces are allowed.
CS3251 Programming in C – UNIT I
All characters except quotation mark, backslash and new line characters enclosed within single
on-Printable character literal constants are represented with the help of escape sequences. An
escape sequence consists of a backward slash (i.e. \) followed by a character and both enclosed
A String Literal constant consist of a sequence of characters enclosed within double quotes. Each
E.g. “ABC”
Qualified constants:
CS3251 Programming in C – UNIT I
Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive. For ex #define
PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is
replaced by its actual value during the pre-processing stage.
Keywords
Keyword is a reserved word that has a particular meaning in the programming language. The
meaning of a keyword is predefined. It can‟t be used as an identifier.
The associativity rule is applied when two or more operators are having same precedence in the
sub expression.
An operator can be left-to-right associative or right-to-left associative.
sub expression.
CS3251 Programming in C – UNIT I
Expressions
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
Size of Size of operator
2. Binary Operator: A binary operator operates on two operands. Some of the binary
operators are,
Operator Meaning
+ Addition
CS3251 Programming in C – UNIT I
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary operator.
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction, multiplication, division
etc.
A=10 & B=20
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give
200
/ The division operator is used to find the quotient. B / A will give 2
% Modulus operator is used to find the remainder B%A will give 0
+,- Unary plus & minus is used to indicate the algebraic +A, -A
sign of a value.
Increment operator
CS3251 Programming in C – UNIT I
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement(--- -2)operator will decrement the variable BEFORE
the expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the expression
evaluation.
E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented and then
it is assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d before it
is decremented.
2. Relational Operators
Relational operators are used to compare two operands. There are 6 relational
operators in C, they are
If the relation is true, it returns value 1 and if the relation is false, it returns value
0.
An expression that involves a relational operator is called as a condition. For e.g
a<b is a condition.
3. Logical Operators
Logical operators are used to logically relate the sub-expressions. There are 3
logical operators in C, they are
If the relation is true it will returns value 1 and is false, it returns value 0.
Operator Meaning of Example
Operator Description
&& Logial AND If c=5 and d=2 then,((c==5) && (d>5)) It returns true when
returns false. both conditions are
true
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) It returns true when
returns true. at-least one of the
condition is true
! Logical NOT If c=5 then, !(c==5) returns false. It reverses the state
of the operand
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~
Bitwise compliment
<< Shift left
>> Shift right
Truth tables
00001100
& 00011001
5. Assignment Operators
To assign a value to the variable assignment operator is used.
Operators Example Explanation
Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This is same as sum=sum+10
-= sum-=10 sum = sum-10
E.g.
6. Miscellaneous Operators
f. Size of operator
a) Comma operator
E.g.
Int i,j;
CS3251 Programming in C – UNIT I
i=(j=10,j+20);
In the above declaration, right hand side consists of two expressions separated by
comma. The first expression is j=10 and second is j+20. These expressions are evaluated from
left to right. ie first the value 10 is assigned to j and then expression j+20 is evaluated so the final
b) Size of Operator
c) Conditional Operator
d) Address-of Operator
It is used to find the address of a data object.
Syntax
&operand
E.g.
Input/Output statements
Formatted Functions
Unformatted functions
printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()
Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
CS3251 Programming in C – UNIT I
1. getchar() This function reads a single character data from the standard
input. (E.g. Keyboard)
Syntax :
variable_name=getchar();
eg:
char c;
c=getchar();
eg
char
c=„C‟;
putchar(c);
Example Program
#include <stdio.h>
main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
}
Output:
A
A
3. getch() and getche() :getch accepts only single keyword from the keyboard. The character
get
entered through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
Like getch(), getche() also accepts only single character, but getche() displays the entered
CS3251 Programming in C – UNIT I
variable_name = getche();
4 putch(): putch displays any alphanumeric characters to the standard output device. It displays
only one character at a time.
Syntax
putch(variable_name);
b) String I/O
c) gets() – This function is used for accepting any string through stdin (keyboard) until enter key is pressed.
Syntax
gets(variable_name);
puts(variable_name);
cputs(char *st);
CS3251 Programming in C – UNIT I
Example Program
void main()
{
char ch[30];
clrscr();
printf(“Enter the String : “);
gets(ch);
puts(“\n Entered String : %s”,ch);
puts(ch);
}
Output:
Enter the String : WELCOME
Entered String : WELCOME
Conversion Codes
Data type Conversion Symbol
Char %c
Int %d
CS3251 Programming in C – UNIT I
Float %f
Unsigned octal %o
Pointer %p
Width Modifier: It specifies the total number of characters used to display the value.
Precision: It specifies the number of characters used after the decimal point.
E.g: printf(“ Number=%7.2\n”,5.4321);
Width=7
Precesion=2
Output: Number = 5.43(3 spaces added in front of 5)
Flag: It is used to specify one or more print modifications.
Flag Meaning
- Left justify the display
+ Display +Ve or –Ve sign of value
E.g:
Space Display space if there is no sign
0 Pad with leading 0s
printf(“Number=%07.2\n”,5.4321)
Output: Number=0005.43
3. Control Codes
They are also known as Escape Sequences.E.g:
Flow of control: The order in which the program statements are executed is known as flow of
control. By default, statements in a c program are executed in a sequential order
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another based
on the result of some condition
Ex) if, if-else, switch
b) Unconditional Branching:- program control is transferred from one point to another
without checking any condition
Ex) goto, break, continue, return
The if statement
if-else statement
The
C uses the keyword if to execute a statement or set of statements when the logical condition is
true.
Syntax:
Test
expres
F
if (test expression)
Statement;
Statement
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
printf(“enter the
number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output:
CS3251 Programming in C – UNIT I
if (test expression)
Statement T;
else
Statement F;
#include <stdio.h>
void main(){
int n,r;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
r=n%2;
if(r==0)
printf(“The number is
even”); else
printf(“The number is odd”);
getch();
}
Output:
Enter a number:15
The number is
odd
CS3251 Programming in C – UNIT I
printf(“a is greatest”);
}else
{ if(b>c)
{
printf(“b is greatest”);
}
else
{
printf(“C is greatest”);
}
}
}
Output
Enter three numbers 2 4 6
C is greatest
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending upon
some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current state
Flowchart
switch(expression)
case: break
statement
constant 0
CS3251 Programming in C – UNIT I
End of switch
Syntax
switch(expression)
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
…
case value n:
program statement;
program statement;
……
Exampl e1 break;
default:
void main() program statement;
{ program statement;
}
char ch;
printf(“Enter a character\
n”); scanf(“%c”,&ch);
switch(ch)
{
case „A‟:
printf(“you entered an A\
n”);
break;
case „B‟:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
CS3251 Programming in C – UNIT I
CS3251 Programming in C – UNIT I
}
Output
Enter a
character A
You entered an A
Example2
void main()
{
int n;
printf(“Enter a number\n”);
scanf(“%d”,&n); switch(n
%2)
{
case 0:printf(“EVEN\n”);
break
case 1:printf(“ODD\n”);
break;
}
getch();
}
Output:
Enter a
number 5
ODD
Syntax:
goto label;
Example:1
#include<stdio.h>
void main()
{
CS3251 Programming in C – UNIT I
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4
iii) continue statement
A continue statement can appear only inside a loop.
A continue statement terminates the current iteration of the nearest enclosing
loop.
Syntax:
continue;
CS3251 Programming in C – UNIT I
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
#include<stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}
Output :1 2 3 4 6 7 8 9 10
iv) return statement:
A return statement terminates the execution of a function and returns the control to the
calling function.
CS3251 Programming in C – UNIT I
Syntax:
return;
(or)
return expression;
Looping statements
Iteration is a process of repeating the same set of statements again and again until the condition
holds true.
1. for
2. while
Counter controlled loops of iterations is known in advance. They use a control variable called loop
counter.
E.g: for
The number of iterations is not known in advance. The execution or termination of the
E.g: while
1. for loop
Statements;
}
2. Condition is evaluated
void main()
int i;
clrscr();
for(i=1;i<=10;i++)
printf(“%d”,i);
getch();
}
CS3251 Programming in C – UNIT I
Output:
1 2 3 4 5 6 7 8 9 10
void main()
int n, i, sum=0;
clrscr();
scanf(“%d”,&n);
for(i=1;i<=n;i++)
sum=sum+i;
printf(“Sum=%d”, sum);
getch();
Output:
4
CS3251 Programming in C – UNIT I
CS3251 Programming in C – UNIT I
2. while statement
They are also known as Entry controlled loops because here the condition is checked
before the execution of loop body.
Syntax:
while (expression)
{
statements;
}
3. do while statement
They are also known as Exit controlled loops because here the condition is checked after
the execution of loop body.
Syntax:
do
{
statements;
}
while(expression);
CS3251 Programming in C – UNIT I
The body of do-while is executed once, even when the condition is initially false.
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are
nested.
Loops within a loop are known as nested loop.
Syntax
while(condition)
{
While(conditio)
{
Statements;
}
Statements;
}
ENUMERATION CONSTANTS
CS3251 Programming in C – UNIT I
In C programming, enumeration constants are integral constants that are defined within an enum (enumeration) data type.
These constants provide meaningful names to a set of related integer values, enhancing code readability and
maintainability.
Defining Enumeration Constants:
To define enumeration constants, use the enum keyword followed by a name for the enumeration and a list of identifiers
enclosed in curly braces:
enum Color {
RED,
GREEN,
BLUE
};
In this example, Color is an enumeration with three constants: RED, GREEN, and BLUE. By default, RED is assigned the
integer value 0, GREEN is 1, and BLUE is 2.
Assigning Specific Values:
You can assign specific integer values to enumeration constants:
enum Fruit {
APPLE = 5,
BANANA = 10,
CHERRY = 15
};
Here, APPLE is assigned the value 5, BANANA is 10, and CHERRY is 15. If subsequent constants are not explicitly
assigned values, they will continue incrementing from the last specified value.
Using Enumeration Constants:
Enumeration constants can be used to declare variables and control program flow:
#include <stdio.h>
enum Direction {
NORTH = 1,
EAST,
SOUTH,
WEST
};
int main() {
enum Direction dir;
dir = SOUTH;
CS3251 Programming in C – UNIT I
if (dir == SOUTH) {
printf("Heading South.\n");
}
return 0;
}
In this program, the Direction enumeration defines four constants with NORTH assigned the value 1. The variable dir is of
type enum Direction and is assigned the value SOUTH. The if statement checks if dir equals SOUTH and prints a
corresponding message.
Key Points:
Default Values: If not explicitly assigned, enumeration constants start at 0 and increment by 1 for each subsequent
constant.
Type Compatibility: Enumeration constants are of type int in C. They can be used anywhere an integer is valid.
Scope: Enumeration constants share the same scope as other identifiers in C. Ensure that their names do not
conflict with other variables or functions.
oduction to Arrays: Declaration, Initialization – One dimensional array – Example Program: Computin
n, Median and Mode - Two dimensional arrays – Example Program: Matrix Operations (Addition, Sca
rminant and Transpose) - String operations: length, compare, concatenate, copy – Selection sort, linear
ry search
roduction to Arrays
CS3251 Programming in C – UNIT I
An Array is a collection of similar data elements. These data elements have the same data type. The
ments of the array are stored in consecutive memory locations and are referenced by an index (also known as
script). Subscript indicates an ordinal number of the elements counted from the beginning of the
ay.
Definition:
An array is a data structure that is used to store data of the same type. The position
of an element is specified with an integer value known as index or subscript.
E.g.
1 3 5 2
a(integer array)
ii) The individual elements of an array are referred based on their position.
2. Multi-dimensional array
Declarations of Arrays
type name[size]
Here the type can be either int, float, double, char or any other valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum
number of elements that can be stored in the array.
The values are written with curly brackets and every value is separated by a
comma. It is a compiler error to specify more number of values than the number of
elements in the array.
a
[0] [1] [2] [3] subscripts or indices
char b[5]={‘A’.’r’,’r’};
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
}
Output:
Example Programs
C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100
#include"stdio.h"
float mean_function(float[],int);
float median_function(float[],int);
float mode_function(float[],int);
int main()
{
int i,n,choice;
float array[SIZE],mean,median,mode;
No of Elements”);
printf(“Enter
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i
scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit");
scanf("%d",&choice);
switch(choice)
{
case 1:
mean=mean_function(array,n);
printf("\n\tMean = %f\n",mean);
break;
CS3251 Programming in C UNIT II
case 2:
median=median_function(array,n);
printf("\n\tMedian = %f\n",median);
break;
case 3:
mode=mode_function(array,n);
printf("\n\tMode = %f\n",mode);
break;
case 4: break;
default:printf("Wrong Option");
break;
}
}while(choice!=4);
}
float mean_function(float array[],int n)
{
int i;
float sum=0;
for(i=0;i
sum=sum+array[i];
return (sum/n);
}
float median_function(float a[],int n)
{
float temp;
int i,j;
for(i=0;i
for(j=i+1;j
{
CS3251 Programming in C UNIT II
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
} if(n
%2==0)
return (a[n/2]+a[n/2-1])/2;
else
return a[n/2];
}
float mode_function(float a[],int n)
{
return (3*median_function(a,n)-2*mean_function(a,n));
}
Output
Enter Elements
2
3
4
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
CS3251 Programming in C UNIT II
1
Mean = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
2
Median =
3.000000 Enter
Choice 1.Mean
2.Median
3.Mode
4.Exit
3
Mode = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
4
CS3251 Programming in C UNIT II
Declaration
datatype arrayname [row size][column size]
Initialization
1 4 6
2 0 0
a
Example Programs
printf("\n 2 . A d d i t i o n o f
matrix:\n”);
printf("\n 3. Multiplication of Matrix:-\n");
printf("\n 4. Exit\n");
printf("\n Enter your choice:-");
scanf("%d",&a);
switch(a)
{
case 1 :
printf("\n Enter the number of row and coloum:-"); scanf("%d
%d",&r1,&c1);
printf("\n Enter the element :-");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
CS3251 Programming in C UNIT II
{
scanf("%d",&m1[i][j]);
m2[j][i]=m1[i][j];
}
}
/*Displaying transpose of matrix*/ printf("\
n Transpose of Matrix is:-\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("\t%d",m2[i][j]);
printf("\n");
}
reak;
case 2:
printf("\n how many row and coloum in Matrix one:-"); scanf("%d
%d",&r1,&c1);
printf("\n How amny row and coloum in Matrix two:-"); scanf("%d
%d",&r2,&c2);
if((r1==r2)&&(c1==c2))
{
printf("\n Addition is possible:-");
printf("\n Input Matrix one:-");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&m1[i][j]);
CS3251 Programming in C UNIT II
}
printf("\n Input Matrix two:-");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&m2[i][j]);
}
/* Addition of Matrix*/
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
m3[i][j]=m1[i][j]+ m2[i][j];
}
Printf(“The sum is:”\n);
for(i=0;i<c1;i++)
{
for(j=0;j<r1;j++)
printf("%5d",m3[i][j]);
printf("\n");
}
}
else
break;
case 3:
CS3251 Programming in C UNIT II
break;
case 4:
exit(0);
break;
}
getch();
}
}
String Operations
Definition:
The group of characters, digits, & symbols enclosed within double quotes is
called as Strings. Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of
memory. The last character is always ‘\0’.
CS3251 Programming in C UNIT II
Declaration:
char stringname[size];
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not
counted.
Syntax
temp_variable = strlen(string_name);
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
It copies the source string to the destination string
Syntax
CS3251 Programming in C UNIT II
strcpy(destination,source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
3. strcat() function
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. Program:
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
int len ;
strcpy(str3, str1);
printf("Copied String= %s\n", str3 );
CS3251 Programming in C UNIT II
strcat( str1, str2);
printf("Concatenated String is= %s\n", str1 );
len = strlen(str1);
printf("Length of string str1 is= %d\n", len );
return 0;
}
Output:
Copied String=Hello
Concatenated String
is=HelloWorld Length of string
str1is
4. strcmp() function
It is used to compare 2 strings.
Syntax
temp_varaible=strcmp(string1,string2)
If the first string is greater than the second string a positive number
is returned.
If the first string is less than the second string a negative number
is returned.
If the first and the second string are equal 0 is returned.
5. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax
strlwr(string_name);
CS3251 Programming in C UNIT II
E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello
6. strupr() function
It converts all the lowercase characters in that string to uppercase characters.
Syntax
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str);
puts(str);
Output: HELLO
7. strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
CS3251 Programming in C UNIT II
String functions
Functions Descriptions
strlen() Determines the length of a String
strcpy() Copies a String from source to destination
strcmp() Compares two strings
strlwr() Converts uppercase characters to lowercase
strupr() Converts lowercase characters to uppercase
strdup() Duplicates a String
strstr() Determines the first occurrence of a given String in another string
strcat() Appends source string to destination string
strrev() Reverses all characters of a string
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
printf(“Student Names\n”);
for(i=0;i<3;i++)
printf(“%s”, s[i]);
}
Sorting
Sorting is the process of arranging elements either in ascending or in descending
order.
Sorting Methods
1. Selection Sort
2. Bubble Sort
3. Merge sort
4. Quick sort
1. Selection sort
It finds the smallest element in the list & swaps it with the element present
at the head of the list.
E.g.
25 20 15 10 5
5 20 15 10 25
5 10 15 20 25
CS3251 Programming in C UNIT II
2. Bubble Sort
In this method, each data item is compared with its neighbour element. If
they are not in order, elements are exchanged.
With each pass, the largest of the list is "bubbled" to the end of the list.
E.g.
Pass 1:
25 20 15 10 5
20 25 15 10 5
20 15 25 10 5
20 15 10 25 5
20 15 10 5 25
25 is the largest element
Repeat same steps until the list is sorted
3. Merge Sort:
Merge sort is based on Divide and conquer method.
It takes the list to be sorted and divide it in half to create two
unsorted lists.
The two unsorted lists are then sorted and merged to get a sorted list.
CS3251 Programming in C UNIT II
4. Quick Sort
This method also uses the technique of Divide and conqure.
Pivot element is selected from the list, it partitions the rest of the list into
two parts – a sub-list that contains elements less than the pivot and other
sub-list containing elements greater than the pivot.
The pivot is inserted between the two sub-lists. The algorithm is recursively
applied to sort the elements.
CS3251 Programming in C UNIT II
Program:
#include <stdio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
CS3251 Programming in C UNIT II
a[i] = a[j];
a[j] =
temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \
n"); for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
}
Output:
Enter the value of
N4
Enter the
numbers 10 2 5 3
The numbers arranged in ascending order are given below
2
3
5
10
The numbers arranged in descending order are given below
10
5
3
2
CS3251 Programming in C UNIT II
Searching
Searching is an operation in which a given list is searched for a particular
value. If the value is found its position is returned.
Types:
1. Linear Search
2. Binary Search
1. Linear Search
The search is linear. The search starts from the first element & continues in a
sequential fashion till the end of the list is reached. It is slower method.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array:
"); for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
CS3251 Programming in C UNIT II
Output:
2. Binary Search
If a list is already sorted then we can easily find the element
using binary serach.
It uses divide and conquer technique.
Steps:
#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
CS3251 Programming in C UNIT II
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.
Example:
3 5 7 9 11
Search key=7 middle element=7
Searching element=middle element.
Search key=11
Middle element=7
Searching element>middle
So go to right half: 9 11. Repeat steps until 11 is found or list ends.
CS3251 Programming in C UNIT 3
Introduction to functions
A function is a subprogram of one or more statements that performs a specific task
when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
Library functions are predefined functions. These functions are already developed
by someone and are available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program.
Ex. sum( ), square( )
Using Functions
A function can be compared to a black box that takes in inputs, processes it, and
then outputs the
result. Terminologies using functions are:
A function f that uses another function g is known as the calling function,
and g is known as the called function.
The inputs that a function takes are known as arguments.
When a called functions returns some result back to the calling function, it
is said to return that result.
The calling function may or may not pass parameters to the called function.
If the called function accepts arguments, the calling function will pass
parameters, else not.
Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
Function Prototype
Before using a function, the compiler must know the number of parameters
and the type of parameters that the function expects to receive and the data type of
CS3251 Programming in C UNIT III
value that it will return to the calling program. Placing the function declaration
statement prior to its use enables the compiler to make a check on the arguments
used while calling that function.
Syntax:
Function definition
When a function is defined, space is allocated for that function in the memory. A
function definition comprises of two parts:
Function header
Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statement
CS3251 Programming in C UNIT
.............
return(variable);
}
While return_data_type function_name(data_type variable1, data_type
variable2,...) is known as the function header, the rest of the portion comprising of
program statements within the curly brackets { } is the function body which
contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only
difference between the two is that a function header is not followed by a semi-
colon.
Function Call
The function call statement invokes the function. When a function is invoked, the
compiler jumps to the called function to execute the statements that are a part
of
that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax:
9
0
CS3251 Programming in C UNIT
If the return type of the function is not void, then the value returned by the
called function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments
…
}
9
1
CS3251 Programming in C UNIT III
Actual arguments – The arguments of the calling function are called as actual
arguments.
Formal arguments – The arguments of called function are called as formal
arguments.
2 scanf() This function is used to read a character, string, and numeric data
from keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard
#include <stdio.h>
int main() {
char input_str[20];
char *output_str;
strcpy(input_str, "Hello");
printf("input_str: %s\n", input_str);
output_str = strcpy(input_str, "World");
CS3251 Programming in C UNIT
Output:
input_str: Hello
input_str: World
output_str: World
Output:
The names are different
#include<stdio.h>
#include<string.h>
int main( )
{
char str[] = “ String Functions”;
printf(“%s \n”, strupr(str));
printf(“%s \n”, strlwr(str));
return 0;
}
Output:
STRING FUNCTIONS
string functions
Recursion
A( )
{
…
…
B( )
;
…
}
B(
)
{
…
…
A( );// function B calls A
…
}
Consider the calculation of 6! ( 6 factorial )
ie 6! = 6 * 5 * 4 * 3 * 2 * 1
6! = 6 * 5!
6! = 6 * ( 6 - 1 )!
n! = n * ( n - 1 )!
{
CS3251 Programming in C UNIT
if (n == 0) return n;
else
return (Func (n–1));
}
Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function
which ultimately calls it. These two functions are indirectly recursive as they both
call each other.
Int Funcl (int n)
{
if (n == 0)
return n; else
return Func2(n);
}
int Func2(int x)
{
return Func1(x–1);
Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed
when the recursive function returns to its caller. When the called function returns, the returned
value is immediately returned from the calling function.
CS3251 Programming in C UNITIII
int Fact(int n)
{
if (n == 1)
return 1;
else
return (n * Fact(n–1));
}
The above function is a nontail-recursive function, because there is a
pending operation of multiplication to be performed on return from each recursive
call. Whenever there is a pending operation to be performed, the function becomes
non-tail recursive. In such a non-tail recursive function, information about each
pending operation must be stored, so the amount of information directly depends
on the number of calls.
int Fact(n)
{
return Fact1(n, 1);
}
int Fact1(int n, int res)
{ if (n == 1) return res;
else
return Fact1(n–1, n*res);
}
The same factorial function can be written in a tail recursive manner. In the code, Fact1 function
preserves the syntax of Fact(n). Here the recursion occurs in the Fact1 function and not in
performed on return from recursive calls. The value computed by the recursive call
is simply returned without any modification. So in this case, the amount of
information to be stored on the system stack is constant (only the values of n and
res need to be stored) and is independent of the number of recursive calls.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int n,f;
printf(“Enter the number \n”);
scanf(“%d”,&n);
f=fact(n);
printf(“The factorial of a number =%d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return(1);
else
return n*fact(n-1);
}
OUTPUT
5
The factorial of a number=120
return 1;
Observe the series of function calls. When the function pending operations in turn
calls the function
Fibonacci(7) = Fibonacci(6) + Fibonacci(5)
Fibonacci(6) = Fibonacci(5) + Fibonacci(4)
Fibonacci(5) = Fibonacci(4) + Fibonacci(3)
Fibonacci(4) = Fibonacci(3) + Fibonacci(2)
Fibonacci(3) = Fibonacci(2) + Fibonacci(1)
Fibonacci(2) = Fibonacci(1) + Fibonacci(0)
Now we have, Fibonacci(2) = 1 + 0 = 1
Fibonacci(4) = 2 + 1 = 3
Fibonacci(5) = 3 + 2 = 5
Fibonacci(6) = 3 + 5 = 8
Fibonacci(7) = 5 + 8 = 13
Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion. It says, ‘if
you can solve n–1 cases, then you can easily solve the nth case’. The figure (a)
below shows three rings mounted on pole A. The problem is to move all these
rings from pole A to pole C while maintaining the same order. The main issue is
that the smaller disk must always come above the larger disk.
CS3251 Programming in C UNIT
In our case, A is the source pole, C is the destination pole, and B is the spare
pole. To transfer all the three rings from A to C, we will first shift the upper two
rings (n–1 rings) from the source pole to the spare pole. We move the first two
rings from pole A to B as shown in figure (b) .
Now that n–1 rings have been removed from pole A, the nth ring can be
easily moved from the source pole (A) to the destination pole (C). Figure (c) shows
this step.
The final step is to move the n–1 rings from the spare pole (B) to the
destination pole (C). This is shown in Fig. (d)
To summarize, the solution to our problem of moving n rings from A to C using B
as spare can be given as:
Base case: if n=1
Move the ring from A to C using B as spare
Recursive case:
Figure (a)
10
4
CS3251 Programming in C UNIT
Figure (b)
Figure (c)
Figure (d)
Example Program
10
5
CS3251 Programming in C UNIT
{
int i, n ;
float x, val, sum, t ;
clrscr() ;
printf("Enter the value for x : ") ;
scanf("%f", &x) ;
printf("\nEnter the value for n : ") ;
scanf("%d", &n) ;
val = x ;
x = x * 3.14159 / 180 ;
t=x;
sum = x
;
for(i = 1 ; i < n + 1 ; i++)
{
t = (t * pow((double) (-1), (double) (2 * i - 1)) * x * x) / (2 * i * (2 * i + 1)) ;
sum = sum + t ;
}
printf("\nSine value of %f is : %8.4f", val, sum) ;
getch() ;
}
Output:
int a[10],i,n,m,c,l,u;
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
10
7
CS3251 Programming in C UNIT
return 0;
}
int mid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
}
else if(m<a[mid])
{
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}
Output:
Pointers Definition:
A pointer is a variable that stores the address of a variable or a function
Advantages
1. Pointers save memory space
2. Faster execution
3. Memory is accessed efficiently.
Declaration
datatype *pointername;
int a=10; p a
int *p=&a;
2000 10
4000 2000
p is an integer pointer & holds the address of an int variable a.
Pointer to pointer
A pointer that holds the address of another pointer variable is known as a
pointer to pointer.
E.g: int **p;
CS3251 Programming in C UNIT
6000
6000 pptr
8000
So **pptr=12
Operations on pointers
a 12.5
1000 1000
P
2000
2. Dereferencing a pointer
The object referenced by a pointer can be indirectly accessed by
dereferencing the pointer. Dereferencing operator (*) is used for this .This
operator is also known as indirection operator or value- at-operator
Eg) int b;
int a=12;
a 12 int *p;
23 B. Shanmuga Sundari
1000
1000 p=&a;
b=*p; \\value pointed by
p(or)value at 1000=12,
p so
b=12
Example program 2000
#include<stdio.h>
void main() Note
{
int a=12; %p is used for addresses; %u
int *p; can also be used.
int **pptr;
p=&a; *p=value at p
=value at (1000)=12
pptr=&p;
printf(“a value=%d”,a); *pptr=value at(pptr)
printf(“value by dereferencing p is %d \n”,*p); =value at(value at (2000))
printf(“value by dereferencing pptr is %d \ ); =value at (1000)=12
n”,**pptr printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output:
a value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
a 12
1000 p 1000
3000
Pointer arithmetic- Arithmetic operations on pointer variables are also possible.
24
CS3251 Programming in C UNIT
1. Addition
(i) An addition of int type can be added to an expression of pointer type. The
result is pointer type.(or)A pointer and an int can be added.
Pre-
increment
Result =
initial value
of pointer +
sizeof (T)
Eg. post float* - float* ftr=p++ ftr=? ftr=2000
CS3251 Programming in C UNIT
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)
Eg.pre float* - float* ftr=--p ftr=? ftr=1996
decrement p=2000 p=1996 Value of ptr
CS3251 Programming in C UNIT
= Value of
ptr –
sizeof(T)
E.g.) E1[E2]=>*(E1+E2)
Example
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf(“Elements are %d %d %d\n”, a[0],a[1],a[2]);
printf(“Elements are %d %d %d\n”, *(a+0),*(a+1),*(a+2);
}
Output:
Elements are 10 15 20
Elements are 10 15 20
Array of pointers
10 20 30
Example:
Now look at another code in which we store the address of three individual arrays
in the array of pointers:
int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
int arr3[]={1,3,5,7,9};
int *parr[3] = {arr1, arr2, arr3};
int i;
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Output
101
char *x[20];
int i,n=0;
void reorder(int n,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char
*)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x); printf("\
nreorder list is : \n");
for(i=0;i<n;i++)
{
Output:
Parameter passing
Whenever we call a function then sequence of executable statements gets executed. We
can pass some of the information to the function for processing
called argument. There are two ways in which arguments can be passed from
calling function to called function. They are:
1. Pass by value
2. Pass by reference
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping a=%d and b=%d”,a,b);
getch();
}
int temp;
temp=a1;
a1=b1;
b1=temp;
}
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
CS3251 Programming in C UNIT
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
Example Program:
CS3251 Programming in C UNIT
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
Main function
a b
35
CS3251 Programming in C UNIT
10 20
1000 1002
Swap function
a1 b1
1000 1002
2000 2002
After swap
function a b
20 10
1000 1002
Example Program: Swapping of two numbers and changing the value ofa variable using pass by reference
#include<stdio.h>
#include<conio.h>
void swap(int *num1, int *num2);
void main() {
int x, y;
printf("\nEnter First number : ");
scanf("%d", &x);
printf("\nEnter Second number : ");
scanf("%d", &y);
36
Downloaded from
CS3251 Programming in C UNIT
Output:
Enter First number : 12 Enter Second number : 21
UNION
Union is derived data type contains collection of different data type or dissimilar elements. All
definition declaration of union variable and accessing member is similar to structure, but instead
of keyword struct the keyword union is used, the main difference between union and structure is
Each member of structure occupy the memory location, but in the unions members share
memory. Union is used for saving memory and concept is useful when it is not necessary
to use all members of union at a time.
Where union offers a memory treated as variable of one type on one occasion where
(struct), it read number of different variables stored at different place of memory.
Syntax of union:
union student
datatype member1;
datatype member2;
};
Like structure variable, union variable can be declared with definition or separately such
as
Datatype member1;
}var1;
Union members can also be accessed by the dot operator with union variable and if we
have pointer to union then member can be accessed by using (arrow) operator as with
structure.
Example:- struct student struct
student
int i;
char ch[10];
};struct student s;
Nested of Union
When one union is inside the another union it is called nested of union.
Example:-
union a
};
union b
{
a aa;
}; union b bb;
Example:-
void main()
struct a
int i;
char ch[20];
};
struct b
int i;
char d[10];
};
union z
b b1;
}; union z z1; z1.b1.j=20;
z1.a1.i=10; z1.a1.ch[10]= “
i“;
z1.b1.d[0]=”j “;
printf(“ “);
Storage classes
Storage classes of a variable determine:
1. Storage area of the variable
2. Initial value of variable if not initialized
3. Lifetime of the variable
4. Linkage of a function or variable
{
int b=20; printf(“b=
%d”,b);
}
printf(“Here b is not visible\n”); printf(“a=
%d”,a);
}
Output
a=10
b=20
Here b is not visible
a=10
Example:
extern int
v=10; void
call1()
void main()
{
call1();
printf(“In main v=%d”,v);
}
void call1()
{
printf(“In call1() v=%d”,v);
}
Output:
In main v=10
In call1( )
v=10
Since v is a external variable it is visible and accessed in all functions.
Page 7
Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store variables,
its initial value and scope of the variables in a program. Or attributes of variable is known as
storage class or in compiler point of view a variable identify some physical location within a
computer where its string of bits value can be stored is known as storage class.
The kind of location in the computer, where value can be stored is either in the memory or in
the register. There are various storage class which determined, in which of the two location
value would be stored.
There are four types of storage classes and all are keywords:-
1) Automatic (auto)
2) Register (register)
3) Static (static)
4) External (extern)
Examples:-
auto float x; or float x;
extern int x;
register char c;
static int y;
If initial value not assigned, then what value taken by uninitialized variable.
3) Scope of the variable:-what would be the value of the variable of the program.
4) Life time :- It is the time between the creation and distribution of a variable
or how long would variable exists.
Its features:-
Storage-memory location
Default initial value:-unpredictable value or garbage value.
Scope:-local to the block or function in which variable is defined.
Life time:-Till the control remains within function or block in which it is defined. It
terminates when function is released.
The variable without any storage class specifier is called automatic variable.
Example:-
main( )
features are:-
Storage:-CPU register.
Life time :-till controls remains within function or blocks in which it is defined.
Register variable don’t have memory address so we can’t apply address operator on it.
CPU register generally of 16 bits or 2 bytes. So we can apply storage classes only for
integers, characters, pointer type.
Variable stored in register storage class always access faster than,which is always stored
in the memory. But to store all variable in the CPU register is not possible because of
limitation of the register pair.
And when variable is used at many places like loop counter, then it is better to declare it
as register class.
Example:- main(
printf(“%d”,i);
feature are:-
Storage:-memory location
Life time:- value of the variable persist or remain between different function call.
Example:-
main( )
{
reduce( );
reduce( );
reduce ( );
reduce( )
printf(“%d”,x); x++;
Output:-10,11,12
Features are:-
Scope :- global
Example:-
int i,j;
void main( )
printf( “i=
%d”,i );
receive( );
receive ( );
reduce( );
reduce( );
receive( )
i=i+2;
reduce( )
i=i-1;
}
Output:-i=0,2,4,3,2.
When there is large program i.e divided into several files, then external variable
should be preferred. External variable extend the scope of variable.
Programming in C – UNIT IV
UNIT IV STRUCTURES
Structure - Nested structures – Pointer and Structures – Array of structures – Example
Program using structures and pointers – Self referential structures – Dynamic memory
allocation - Singly linked list - typedef
4.1 Introduction
Using C language we can create new data types. These data types are known as
User Defined data types & can be created by using Structures, Unions &
Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of
different data types. For this Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It
is used for storing different types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
3. Using & performing operations.
4.1.1 Structure Definition
The structure can be defined with the keyword struct followed by the name of
structure and opening brace with data elements of different type then closing brace
with semicolon.
General Form
struct book
{
char title[25];
int pages;
float price;
};
Structure definition does not reserve any space in the memory.
It is not possible to initialize the structure members during the structure
definition.
A structure definition must always be terminated with a semicolon.
There are two types of operators used for accessing members of a structure.
1. Direct member access operator (dot operator) (.)
2. Indirect member access operator (arrow operator) (->)
Using Dot operator General form:
Example program:
#include<stdio.h>
struct name
{
char fname[20],lastname[20];
};
Programming in C – UNIT IV
struct student
{
int sno,m1,m2,m3;
int tot;
float avg;
struct name sname;
};
void main()
{
struct student s[10];
float,avg;
int n,i;
printf(“Enter the number of students \n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
E.g) s[i].sname.lastname
student
sn
m1
m2
m3
tot
nested structure
avg
name
fname
lastname
Example:
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr;
OR
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
Programming in C – UNIT IV
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of Student: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
Output:
Records of Student:
Id is: 1
Name is: Sankar
Percentage is: 90.500000
E.g. Program:
#include<stdio.h>
#include<conio.h>
struct employee
{
char
name[15]; int
empid,bsal;
float net,gross;
};
void main()
{
struct employee emp[10];
float hra,da,tax;
int n,i,j;
clrscr();
printf("Enter the number of employees\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter the employee name");
scanf("%s",emp[i].name); printf("\
nEnter the employee id");
Programming in C – UNIT IV
scanf("%d",&emp[i].empid);
printf("\nEnter the basic salary");
scanf("%d",&emp[i].bsal);
hra=((10*emp[i].bsal)/100);
da=((35*emp[i].bsal)/100);
tax=((15*emp[i].bsal)/100);
emp[i].gross=emp[i].bsal+hra+da;
emp[i].net=emp[i].gross-tax;
}
printf("Employee Name Employee ID Employee Net Salary \n");
for(i=1;i<=n;i++) printf("%s\t\t%d\t\t%f\
n",emp[i].name,emp[i].empid,emp[i].net); getch();
}
Output:
Enter the number of Employees
2
Enter the employee name
Anu
Enter the employee id
01
Enter the basic salary
1000
Enter the employee name
Meena
Enter the employee id 02
Enter the basic salary
2000
Employee Name Employee ID Net Salary
Anu 01 1300.000
Meena 02 2600.000
int main()
{
/*declare structure variable*/
struct employee emp;
1. malloc() function
malloc() allocates N bytes in memory and return pointer to allocated memory. The
returned pointer contains link/handle to the allocated memory.
void * malloc(number_of_bytes);
It returns void pointer (generic pointer). Which means we can easily typecast it
to any other pointer types.
It accepts an integer number_of_bytes, i.e. total bytes to allocate in memory.
Note: malloc() returns NULL pointer on failure.
Example
Here,
ptr is a pointer to integer to store address of the allocated memory.
(int *) is typecast required. As, I mentioned above that malloc() return void *.
Hence, to work with void pointer we must typecast it to suitable type.
N * sizeof(int) - Since size of int is not fixed on all compilers. Hence, to get
size of integer on current compiler I have used sizeof() operator.
2. calloc() function
int *ptr;
ptr = (int *) calloc(N, sizeof(int));
Here, all memory blocks are initialized with 0.
3. realloc() function
When working with h u g e d a t a a n d i f t h e a l l o c a t e d m e m o r y i s n o t
sufficient to store data. In that case, we need to alter/update the size of an existing
allocated memory blocks (which has been created by either malloc() or calloc()).
We use realloc() function to alter/update the size of exiting allocated memory blocks.
The function may resize or move the allocated memory blocks to a new location.
Syntax
void* realloc(ptr, updated_memory_size);
Similar to all other functions for Dynamic Memory Allocation in C, it returns
void pointer. Which points to the address of existing or newly allocated
memory.
ptr is a pointer to memory block of previously allocated memory.
updated_memory_size is new (existing + new) size of the memory block.
Example
4. free() function
C programming has a built-in library function free() to clear or release the unused
memory.
The free() function clears the pointer (assigns NULL to the pointer) to clear the
dynamically allocated memory. If pointer contains NULL, then free() does nothing
(because pointer will not be pointing at any memory addresses). If it contains any
address of dynamically allocated memory free(),pointer by assigning NULL.
Syntax
free(ptr);
The function accepts a void pointer ptr. It points to previously allocated memory using
any of Dynamic Memory Allocation functions in C.
Example:
int N=10;
int *ptr;
// Allocate memory using malloc
ptr=(int *) malloc (N* size of (int));
//Free allocated memory
free(ptr);
START
1 2 3 4 5 6 7 X
In the above linked list, every node contains two parts- one integer and the other a
pointer to the next node. The left part of the node which contains data may include a
simple data type, an array or a structure. The right part of the node contains a pointer
to the next node (or address of the next node in sequence). The last node will have no
next node connected to it, so it will store a special value called NULL.
A singly linked list is the simplest type of linked list in which every node contains some
data and a pointer to the next node of the same data type. By saying that the node
contains a pointer to t h e n e x t n o d e w e m e a n t h a t t h e n o d e s t o r e the
address of the next node in sequence.
We will traverse each and every node of the list and while traversing every individual
node, we will increment the counter by 1. Once we reach NULL, that is when all the
nodes of the linked list have been traversed, the final value of the counter will be
displayed. Figure below shows the algorithm to print the number of nodes in a linked
list.
Consider the linked list shown in figure we have val=4, then the flow of the algorithm
can be explained as shown in figure
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
17
Programming in C – UNIT
IV
Insert a new node at the head of the list is straightforward. The main idea is that we
create a new node, set its next link to refer to the current head, and then set head to
point to the new node.
Algorithm addFirst(String newData):
create a new node v containing newData
v.setNext(head)
head = v
size = size + 1
18
Algorithm removeFirst()
if (head = = null) then
Indicate an error: the list is empty
tmp = head
head = head.getNext()
tmp.setNext(null)
size = size - 1
Example:
include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
19
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
20
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{ printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{ curr->next = ptr; curr = ptr;
}
else { ptr->next = head; head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
21
if(ptr->val == val)
{ found = true; break;
}
else
{
tmp = ptr; ptr = ptr->next;
}
}
if(true == found)
{
if(prev) *prev = tmp;
return ptr;
}
else
{
return NULL; } }
int delete_from_list(int val)
{
22
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL) { return -1; }
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{ curr = prev;
}
else if(del == head)
23
head = del->next;
}}
free(del);
del = NULL; return 0;
}
void print_list(void) {
struct test_struct *ptr = head;
printf("\n -------Printing list Start-------\n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End-------\n"); return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true); print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{ ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
24
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val); }
print_list(); ret = delete_from_list(i);
if(ret != 0) { printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i); } print_list(); } return 0;
}
4.9 Typedef
The typedef keyword enables the programmer to create a new data type name by using
an existing data type.
By using typedef, no new data is created, rather an alternate name is given to a known
data type.
Syntax: typedef existing_data_type new_data_type;
25
Answer: all of these
2. A data structure that can store related information of different data types together is
A. array
B. string
C. Structure
D. all of these
Answer: Structure
26
6. A union number variable is generally accessed using the
A. address operator
B. dot operator
C. comma operator
D. ternary operator
Answer: dot operator
27
c) Dynamic allocation of memory for structure
d) All of the mentioned
Answer: Typecasting of structure
28
15. What is the output of C program with structure array pointers.? int main()
{
struct car
{
int km;
}*p1[2];
struct car c1={1234};
p1[0]=&c1;
printf("%d ",p1[0]->km);
return 0;
}
A) 0
B) 1
C) c
D) Compiler
error Answer:
1234
29
CS3251 Programming in C - UNIT V
5.1 Introduction
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 file represents a sequence of bytes on the disk where a group of related data
is stored. File is created for permanent storage of data. It is a readymade structure.
1. Text files
2. Binary files
1. Text Files
Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate
set of library functions is there to process such data 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.
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
3. Closing a file
Function description
Opening a file means creating a new file with specified file name and with accessing
mode.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the
opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
Mode Purpose
2. Closing a File
A file must be closed after all the operation of the file have been completed. The
fclose() function is used to close an already opened file.
Syntax:
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
c=fgetc(p1);
The fscanf function is used to read data from a file. It is similar to the scanf function
except that fscanf() is used to read data from the disk.
Syntax:
where fb refers to the file pointer. v1, v2, … vn refers variables whose values are read
from the disk “format string” refers the control string which represents the conversion
specification.
Syntax:
fputc(x,fp1);
where fp1 is the file pointer.
fprintf() function is used to write data to a file. It is similar to the printf() function
except that fprintf() is used to write data to the disk.
Syntax:
2. Random Access — In this type of file, the data can be read and modified
randomly. If it is desired to read the last record of a file, directly the same record can
be read. Due to random access of data, it takes less access time as compared to the
sequential file.
A Sequential file is characterized by the fact that individual data items are
arranged serially in a sequence, one after another. They can only be processed in serial
order from the beginning. In other words, the records can be accessed in the same
manner in which they have been stored. It is not possible to start reading or writing a
sequential file from anywhere except at the beginning.
The second and better method of arranging records of a file is called direct
access or random access. In this arrangement one can have access to any record which
is situated at the middle of the file without reading or passing through other records in
the file.
Data is stored in files so that the data can be retrieved for processing when needed
Example:
Program:
#include <stdio.h>
5
#include <stdlib.h>
int main(void) {
exit(0);
} // end while
} // end main
Output:
6
400 Bala 2344.00
/* Program to read from the num.dat file and find the average of the numbers */
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
int n[50], i = 0;
float sum = 0;
exit(0);
while (!feof(fp)) {
sum += n[i];
i++;
}fclose(fp); // if no data is available in the file
if (i == 0)
printf("No data available in %s", DATAFILE);
7
float average = sum / i;
return 0;
Output:
8
} byte offsets
}
}
}
}
}
}
100 100 100 100 100 100
bytes bytes bytes bytes bytes bytes
9
5.4.1 Functions For Selecting A Record Randomly
The functions used to randomly access a record stored in a file are fseek(), ftell(),
rewind(), fgetpos(), and fsetpos().
1. fseek()
• fseek() is used to set the file position pointer for the given stream. Offset is an
integer value that gives the number of bytes to move forward or backward in
the file. Offset may be positive or negative, provided it makes sense. For
example, you cannot specify a negative offset if you are starting at the
beginning of the file. The origin value should have one of the following values
(defined in stdio.h):
• SEEK_SET: to perform input or output on offset bytes from start of the file
• fseek() can be used to move the file pointer beyond a file, but not before the
beginning.
Example:
Write a program to print the records in reverse order. The file must be opened in binary mode. Use fseek()
#include<stdio.h>
#include<conio.h>
main()
10
{ int emp_code;
char name[20];
int hra;
int da;
int ta;
};
FILE *fp;
struct employee e;
int result, i;
fp = fopen("employee.txt", "rb");
if(fp==NULL)
exit(1);
}
for(i=5;i>=0;i--)
fclose(fp);
getch();
return 0;
2. rewind()
11
• rewind() is used to adjust the position of file pointer so that the next I/O
operation will take place at the beginning of the file. It’s prototype can be given
as
3. fgetpos()
• The fgetpos() is used to determine the current position of the stream. It’s
prototype can be given as
int fgetpos(FILE *stream, fpos_t *pos);
• Here, stream is the file whose current file pointer position has to be determined.
pos is used to point to the location where fgetpos() can store the position
information. The pos variable is of type fops_t which is defined in stdio.h and
is basically an object that can hold every possible position in a FILE.
• The fsetpos() is used to move the file position indicator of a stream to the
location indicated by the information obtained in "pos" by making a call to the
fgetpos(). Its prototype is
• Here, stream points to the file whose file pointer indicator has to be re-
positioned. pos points to positioning information as returned by "fgetpos".
• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case
of failure it returns a non-zero value
The program opens a file and reads bytes at several different locations.
#include <stdio.h>
main()
12
FILE *fp;
fpos_t pos;
char feedback[20];
fp = fopen(“comments.txt”, “rb”);
if(fp == NULL)
exit(1);
{
printf(“\n error in fgetpos()”);
exit(1);
pos = 90;
exit(1);
13
printf( "\n 20 bytes at byte %ld: %s", pos, feedback);
fclose(fp);
4. ftell()
The ftell function is used to know the current position of file pointer. It is at this
position at which the next I/O will be performed. The syntax of the ftell() defined in
stdio.h can be given as:
On successful, ftell() function returns the current file position (in bytes) for stream.
However, in case of error, ftell() returns -1.
When using ftell(), error can occur either because of two reasons:
First, using ftell() with a device that cannot store data (for example, keyboard)
Second, when the position is larger than that can be represented in a long integer. This
will usually happen when dealing with very large files
FILE *fp;
char c;
int n;
fp=fopen("abc","w");
if(fp==NULL)
{ printf("\n Error Opening The File");
exit(1);
while((c=getchar())!=EOF)
putc(c,fp);
n = ftell(fp);
fclose(fp);
fp=fopen("abc","r");
14
if(fp==NULL)
exit(1);
while(ftell(fp)<n)
{ c= fgetc(fp);
printf('%c", c);
fclose(fp);
Option 1
calls function textFile to store a formatted list of all the accounts (typically called a
report) in a text file called accounts.txt that may be printed later. The function
uses fread and the sequential file access techniques used in the program of Section
below.
15
Option 2
calls the function updateRecord to update an account. The function will update only
a record that already exists, so the function first checks whether the record specified
by the user is empty. The record is read into structure client with fread, then member
acctNum is compared to 0. If it’s 0, the record contains no information, and a message
is printed stating that the record is empty. Then the menu choices are displayed. If the
record contains information, function updateRecord inputs the transaction amount,
calculates the new balance and rewrites the record to the file.
Option 3
calls the function newRecord to add a new account to the file. If the user enters an
account number for an existing account, newRecord displays an error message
indicating that the record already contains information, and the menu choices are
printed again
calls function deleteRecord to delete a record from the file. Deletion is accomplished
by asking the user for the account number and re-initialising the record. If the account
contains no information, deleteRecord displays an error message indicating that the
account does not exist.
Option 5
Example Program:
16
// Bank-account program reads a random-access file sequentially, updates data already
written to the file, creates new data to be placed in the file, and deletes data previously
in the file. //
#include <stdio.h>
#include <stdlib.h>
struct clientData {
// prototypes
exit(-1);
17
}
{ switch (choice) {
case 1:
textFile(cfPtr); break;
// update record
case 2:
updateRecord(cfPtr); break;
// create record
case 3:
newRecord(cfPtr); break;
// delete existing r e c ord
case 4:
deleteRecord(cfPtr); break;
default:
} // end switch
} // end while
} // end main
18
int result; // used to test whether fread read any bytes
} // end if
else {
while (!feof(readPtr)) {
result = fread(&client, sizeof(struct clientData),1,readPtr);
// write single record to text file
} // end if
} // end while
} // end else
19
unsigned int account; // account number
scanf("%d", &account);
if (client.acctNum == 0) {
client.firstName, client.balance);
20
// write updated record over old record in file
} // end else
if (client.acctNum == 0) {
} // end if
21
// replace existing record with blank record
} // end else
scanf("%d", &accountNum);
if (client.acctNum != 0) {
} // end if
else { // create record user enters last name, first name and balance
= accountNum;
22
// move file pointer to correct record in file
} // end else
return menuChoice;
23
www.EnggTree.co
m
Syntax:
24
Here argc counts the number of arguments on the command line and argv[ ] is a
pointer array which holds pointers of type char which points to the arguments passed
to the program
Example:
#include <stdio.h>
#include <conio.h>
int i;
{
printf("%s\t", argv[i]);
else
return 0;
Remember that argv[0] holds the name of the program and argv[1] points to the first
command line argument and argv[n] gives the last argument. If no argument is
25
Multiple Choice Questions
1. is a collection of data.
A. Buffer
B. Stream
C. File
Answer: File
2. If the mode includes b after the initial letter, what does it indicates?
a) text file
b) big text file
c) binary file
Answer: binary file
a) input streams
b) output streams
c) previous contents
d) appended text
Answer: output streams
5. What is the keyword used to declare a C file pointer.?
A) file
B) FILE
C) FILEFP
D) filefp
Answer: FILE
A. fseek()
B. fsetpos()
C. ftell()
D. Rewind()
Answer: ftell()
A. fwrite()
B.fprintf()fputc()
B. fputs()
Answer: fwrite()
A. stdin
B. stdout
C. stderr
D. all of these
A. Stdin
B. stdout
C. stderr
D. all of these
Answer: stderr
A. file pointer
28
B. buffer
C. stdout
D. stdin
Answer: buffer
A. fread()
29
B. fopen()
C. floes()
D. fflush()
Answer: fopen()
14. Which function returns the next character from stream, EOF if the end of file is reached, or if
there is an error?
A. fgetc()
B. fgets()
C. fputs()
D. fwrite()
Answer: fgetc()
30
Programming in C
Unit-I
Introduction to C programming
2 Marks
1. Define identifier.
Int
Char
Float
Double
Enum, pointer. array, structure, union, void
1
5. What is meant by constants?
6. Define Variables.
A variable is 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 variables memory.
9. Define Statements?
2
11.Define Arithmetic operator.
5 Marks
3
No keyword should access variable name (int for <- invalid because
for is keyword).
Syntax
4
4. Explain the concept of Expressions.
5
10 Marks
They are arithmetic types and are further classified into: (a)
integer types and (b) floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values
throughout the program.
3 The type void
They include (a) Pointer types, (b) Array types, (c) Structure
types, (d) Union types and (e) Function types.
Integer Types
6
Floating-Point Types
SOURCE CODE
#include <stdio.h> int
main()
{
int first, second, add, subtract, multiply; float
divide;
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting
printf("Sum = %d\n",add); printf("Difference
= %d\n",subtract); printf("Multiplication =
%d\n",multiply); printf("Division = %.2f\
n",divide);
return 0;
}
OUTPUT
7
4. Discuss about Constants in C.
8
Unit-II
Loops and Statements
2 Marks
1. Define Branching
While loop
Do...while loop
For loop
Nested loops
If (condition) Program
statement 1; Else
Program statement 2;
9
6. Define Switch Statement.
while(condition)
{
statement(s);
}
10
5 Marks
Syntax
switch(expression)
{
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
default :
statement(s);
}
The following rules apply to a switch statement
The expression used in a switch statement must have an integral or
enumerated type.
The constant-expression for a case must be the same data type as
the variable in the switch
When a break statement is reached, the switch terminates
Not every case needs to contain a break
A switch statement can have an optional default case, which must
appear at the end of the switch
11
2. Explain the loop with its types.
2 for loop
Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the
condition at the end of the loop body.
4 nested loops
You can use one or more loops inside any other while, for, or
do..while loop.
12
10 Marks
13
relational test is simple one or more simple relational tests joined together by either
the the logical OR operators or logical AND.
The syntax of the Compound Relational tests is as follows:
a> if (condition1 && condition2 && condition3)
b> if (condition1 // condition2 // condition3)
14
Unit-
III
2Mark
s
1. Define Functions.
Return type
Function name
Parameters
Function Body
15
5. Define Function Prototype.
16
9. What is meant by global variables?
int main(){
10.Define Recursion.
void recursion()
{
recursion();
}
int main()
{
recursion();
}
17
5 Marks
Syntax:
static data_type var_name = var_value;
Example program:
#include<stdio.h> int
fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
OUTPUT
12
18
2. Describe Multi-file programs.
Each of the files can be compiled separately, into a *.o file. Later, all
the *.o files can be linked together (still using gcc) into a running program,
an executable object program.
Each file can have access to a set of names that are private to that file,
and to other names that are shared across all the files of the complete
program.
The programmer determines which names are local to each file, and
which are shared, and indicates his/her decisions by constructing
declarations appropriately.
The storage class specifies extern and static play a role in this, as
does the position of each declaration, and whether a declaration is in fact a
“definition”.
19
10 Marks
20
2. Describe the Functions in C.
21
Unit-IV
2 Marks
1.Define Array.
22
5.Define Structure.
the basic set of data types defined in the C language such as int,
float etc. may be insufficient for your application.
In circumstances such as these, you can create your own data
types which are based on the standard ones
7. What is meant by union?
23
5 Marks
24
You can define a union with many members, but only one member
can contain a value at any given time. Unions provide an efficient way
of using the same memory location for multiple-purpose.
Defining a Union: To define a union, you must use the union
statement in the same way as you did while defining a structure. The
union statement defines a new data type with more than one member
for your program. The format of the union statement is as follows −
25
S.N. Concept & Description
Multi-dimensional arrays
1 C supports multidimensional arrays. The simplest form of the multidimensional
array is the two-dimensional array.
Passing arrays to functions
2 You can pass to the function a pointer to an array by specifying the array's name
without an index.
Return array from a function
3
C allows a function to return an array.
Pointer to an array
4 You can generate a pointer to the first element of an array by simply specifying the
array name, without any index.
26
Unit-V
2 Marks
1. Define pointers.
3. Define File.
27
5. Define pointer to pointer
Create
OPen
Process
Delete
Close
5 Marks
28
mode Description
"r" Opens a file for reading. The file must exist.
Creates an empty file for writing. If a file with the same name already
"w" exists, its content is erased and the file is considered as a new empty
file.
Appends to a file. Writing operations, append data at the end of
"a"
the file. The file is created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.
29
FILE *fopen( const char * filename, const
char * mode );
Mode Description
r Opens an existing text file for reading purpose.
Opens a text file for writing. If it does not exist, then a new file is created. Here
w
your program will start writing content from the beginning of the file.
Opens a text file for writing in appending mode. If it does not exist, then a new file
a is created. Here your program will start appending content in the existing file
content.
r+ Opens a text file for both reading and writing.
Opens a text file for both reading and writing. It first truncates the file to zero
w+
length if it exists, otherwise creates a file if it does not exist.
a+ Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.
10 Marks
Example Program
#include <stdio.h>
int main () {
int var1; char
var2[10];
30
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
OUTPUT
Address of var1 variable: bff5a400 Address
of var2 variable: bff5a3f6
Advantage of File
It will contain the data even after program exit. Normally we use
variable or array to store data, but data is lost after program exit. Variables
and arrays are non-permanent storage medium whereas file is permanent
storage medium.
31
3. Explain Structures and Pointers.
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of
person1
32
scanf("%d",&(*personPtr).age);
return 0;
}