100% found this document useful (2 votes)
3K views50 pages

22CSE14

The document discusses the basic structure of C programs including sections like documentation, definitions, global declarations, main function etc. It also explains various operators, data types, input/output functions and rules for naming variables in C language.

Uploaded by

GAT LIBRARY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
3K views50 pages

22CSE14

The document discusses the basic structure of C programs including sections like documentation, definitions, global declarations, main function etc. It also explains various operators, data types, input/output functions and rules for naming variables in C language.

Uploaded by

GAT LIBRARY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

MODULE 1

1) Explain the basic structure of C program with an example.


ANS:

• The documentation section consists of a set of comment lines


giving the name of the program, the author and other details, which
the programmer would like to use later.
• The link section provides instructions to the compiler to link
functions from the system library.
• The definition section defines all symbolic constants.
• There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the
global declaration section that is outside of all the functions.
• Every C program must have one main() function section. This
section contains two parts, declaration part and executable part.
The declaration part declares all the variables used in the
executable part.
• The closing brace of the main function section is the logical end of
the program.
1|Page GAT STUDENTS LIBARY
• All statements in the declaration and executable parts end with a
semicolon(;).
• The subprogram section contains all the user-defined functions that
are called in the main function

2)List the types of operators used in C Language. Explain relational and


logical operators.
ANS:
• Arithmetic operators +, -, *, /, %
• Relational operators <, <=, >, >=, ==, !=
• Logical operators &&, ||, !
• Assignment operator =
• Increment and Decrement operators ++, --
2|Page GAT STUDENTS LIBARY
• Conditional operator ?:
• Bitwise operators &, |, ^, ~, <<, >>
• Other operators sizeof, comma

Relational Operators
• Used to compare the values of two expressions.
• If the result is true, return 1. If the result is false, returns 0.
Example:
int a=4, b=78, c; Output:
c=a==b;printf(“%d”,c); 01
c=4!=78;printf(“%d”,c);
Logical Operators
Used to combine two expressions. The result will be either true or false.
Logical NOT !
It reverses the logical value of a variable or a constant or an expression.
Logical AND &&
• Works on 2 operands.
• Result is true if values of both expressions are true.
• Result is false, if any one expression value is false.
Logical OR ||
• Works on 2 operands.
• Result is false if values of both expressions are false.
• Result is true, if any one expression value is true.
Example:
3|Page GAT STUDENTS LIBARY
10!=10 || 5<4 && 8
(10!=10) || (5<4) && 8
false || false && true
false || (false && true)
false || false = false
3) Define token. List the tokens used in C Language and explain
Keywords and Strings with examples.
ANS: In a C program, the smallest individual units are known as C
tokens. Types of tokens are keywords, identifiers, constants, strings,
special symbols and operators.
Keywords:
Every C word is classified as either a keyword or an identifier. All
keywords have fixed meaning and these meaning cannot be changed.
Keyword serve as basic building blocks for program statement. All
keywords must be written in lower case.

Strings:
Strings in C are always represented as an array of character ‘\0’ at the end
of the string. This null character denotes the end of the strings. Strings in
C are enclosed in double quote,while charters are enclosed within single
character. The size of a string is a number of characters that the string
contains.

4|Page GAT STUDENTS LIBARY


char a[10]=”abcd”; //The compiler allocates the 10 bytes to the ‘a’ array.
char a[]=”abcd”; //The compiler allocates the memory at the same time.

4) Explain the primary data types used in C language.


ANS: FUNDAMENTAL DATATYPES
C supports 5 primary datatypes:
• int
• float
• char
• double
• void

int
• An int is a keyword which is used to define integers.
• Using int keyword, the programmer can inform the compiler that the
data associated with this keyword should be treated as integer.
• → int requires 2 bytes of storage space
• C has three classes of integer storage, namely short int, int, and long int
float
• A float is a keyword which is used to define floating point numbers.
• float provides an accuracy of 6 digits after the decimal point.
• It consumes 4 bytes of storage space.
• Floating point numbers are defined in C by the keyword float.
double
• A double is a keyword used to define long floating-point numbers.
• It gives an accuracy of 16 digits after the decimal point
• 8 bytes of storage space

5|Page GAT STUDENTS LIBARY


Character
• A char is a keyword which is used to define single character.
• Characters are usually stored in 8 bits (1 byte) of internal storage
Void
• void is an empty data type.
• Since no value is associated with this data type, it does not occupy any
space in the memory.

5) Explain the formatted I/O functions of C language with syntax and


example.
ANS: FORMATTED I/O
FORMATTED INPUT
scanf():
• The scanf standard library function is used to read one or more values
from the standard input (keyboard) and assign them to specified
variables
• Syntax:-
scanf(“Control String or format specifier”, address _ of _ variables);

Example:-
int a,b;
printf(“enter the values of a and b”);
scanf (“%d%d”,&a,&b);
• The field specification for reading an integer number is:
% wd
• The percentage sign (%) indicates that a conversion specification
follows.
• w is an integer number that specifies the field width of the number to
be read and
d, known as data type character, indicates that the number to be read is
in integer mode.
6|Page GAT STUDENTS LIBARY
• Consider the following example:
scanf (“%2d %5d”, &num1, &num2);
• Data line: 50 31426
• The value 50 is assigned to num1 and 31426 to num2.
• Suppose the input data is as follows: 31426 50
• The variable num1 will be assigned 31 (because of %2d) and num2
will be assigned 426 (unread part of 31426).
• The value 50 that is unread will be assigned to the fi rst variable in the
next scanf call.

Formatted output:
printf()
• The printf (print formatted) standard library function is used to print
the values of expressions on standard output (i.e, display) in a specifies
format
• Syntax:
printf(“ControlString”, arg1,arg2,…,argn);
• Control string consists of:
• Character that will be printed on the screen as they
• Format specifications that define the output format
for display of each item
• Escape sequence characters
Example:-
printf(“good morning\n”)’;
printf(“%d%d%d”,num1,num2,sum);
• The format specification for printing an integer number is:
%wd
• where w specifies the minimum fi eld width for the output. However,
if a number is greater than the specified fi eld width, it will be printed
7|Page GAT STUDENTS LIBARY
in full, overriding the minimum specification. d specifies that the
value to be printed is an integer. The number is written right-justified
in the given field width.
6) List the rules for naming a variable in C.
ANS: Rules for naming the variables
• The first character in the variable name should be a letter or an
underscore.
• The first character can be followed by any number of letters or
digits(0to9) or underscores.
• No extra symbols are allowed other than letter, digits and underscore.
• C Keywords must not be used.
• The maximum size of the characters supported for naming the internal
variable is 31.

7) Explain the following operators used in C Language:


i) Arithmetic ii) Relational iii) Logical iv) Bitwise v)Increment/decrement
vi) Conditional
ANS: Arithmetic Operators
• The operators that are used to perform arithmetic operation such as
addition, subtraction, multiplication, division and modulus operation
are called arithmetic operators.
• These operators perform operations on two operands and hence they
are all binary operators.
Increment operator:
• The ++(double plus) operator is also called as incrementation operator.
This
operator is used to increment the value of a variable by 1.
post and pre increment operators:
• If the ++ operator is placed before the operand then it is called as pre
increment operator.
• If the ++ operator is placed after the operand then it is called as post
increment operator
Example 1:
8|Page GAT STUDENTS LIBARY
• m = 5;
• y = ++m; (prefix)
• In this case the value m will be incremented to 6 first and then it will
be assigned to y
• Example 2:
• m = 5;
• y = m++; (postfix)
• In this case the values of m will gets assigned first to y and then it will
gets incremented. Therefore at the end of the execution, the value of
y will be 5 and m will be 6.
Decrement operator
• The --(double minus) operator is also called as decrementation operator.
This operator is used to decrement the value of a variable by 1.
post and pre decrement operators:
• If the -- operator is placed before the operand then it is called as pre
decrement operator.
• If the -- operator is placed after the operand then it is called as post
decrement operator

Example 1:
• m = 5;
• y = --m; (prefix)
• In this case the value m will be decremented to 4 first and then it will be
assigned to y. Therefore at the end of the execution, the value of y and m
will be 4.
Example 2:
• m = 5;
• y = m--; (postfix)
• In this case the values of m will gets assigned first to y and then it will
gets decremented. Therefore at the end of the execution, the value of y will
be 5 and m will be 4.
Relational Operators:
• The operators that are used to find the relationship between
two operands are called relational operators

9|Page GAT STUDENTS LIBARY


Logical Operators:
• The operators which are used to combine two or more relational
expression are known as logical operators.

Bit wise operators:


• Bitwise operators are operators which act on the individual bits of the
data stored in the memory location. The operators that are used to
manipulate the bits of given data are called bitwise operators

10 | P a g e GAT STUDENTS LIBARY


Left shift / right shift operator
• The operator that is used to shift the data by a specified number of
bit positions towards left or right is called shift operator.

Conditional Operators
• Conditional operator which is also known as ternary operator,
operates on three operands. Conditional operators return one value if
condition is true and returns another value if condition is false.
• The syntax is shown below:
(exp1)? exp2: exp3;
• where exp1 is an expression evaluated to true or false;
• If exp1 is evaluated to true, exp2 is executed;
• If exp1 is evaluated to false, exp3 is executed.
• Example
a=10 ;
b=15;
x=(a>b) ? a : b;

11 | P a g e GAT STUDENTS LIBARY


• Here x will have the value of b
8) Explain character set of C Language giving example for each.
ANS: CHARACTER SET
• The characters that can be used to form words, numbers and
expressions depend upon the computer on which the program is run.
However, a subset of characters is available that can be used on most
personal, micro, mini and mainframe computers.
• The characters in C are grouped into the following categories:
• 1. Letters
• 2. Digits
• 3. Special characters
• 4. White spaces

12 | P a g e GAT STUDENTS LIBARY


Module 2
1) Explain the working of while loop with example.
• The while is an entry-controlled loop statement.
• The test-condition is evaluated and if the condition is true, then the
body of the loop is executed.
• After execution of the body, the test condition is once again evaluated
and if it is true, the body is executed once again
while(test condition)
{
Body of the loop
}

Example program
#include<stdio.h>
main()
{
int i=1;
while(i<=5)
{
printf(“Welcome to C language\n”);
i=i+1;
}
}
Output:
Welcome to C language Welcome to C language
13 | P a g e GAT STUDENTS LIBARY
Welcome to C language
Welcome to C language
Welcome to C language
2) Explain the working of for loop with example.
• The for loop is another entry-controlled loop that provides a more
concise loop control structure. The general form of the for loop is
For(initialization; test-condition; increment)
{
body of the loop
}
• Initialization of the control variables is done first, using assignment
statements such as i = 1 and count = 0.
• The value of the control variable is tested using the test-condition. f the
condition is true, the body of the loop is executed; otherwise the loop is
terminated and the execution continues with the statement that
immediately follows the loop.
• When the body of the loop is executed, the control is transferred back
to the for statement after evaluating the last statement in the loop. Now,
the control variable is incremented using an assignment statement such
as i = i+1

Write a program to generate the Fibonacci sequence of first N


numbers.
# include <stdio.h>
void main()
{
int num 1=0, num2=1, n, i, fab;
printf(“\n\nEnter the value of n: “);
scanf (”%d”, &n);
for (i = 1; i <= n-2; i++)
{
fab=num1 + num2;
14 | P a g e GAT STUDENTS LIBARY
num1=num2;
num2=fab;
}
printf(“\n nth fibonacci number (for n = %d) = %d, n, fab);
}

3) Explain the working of do-while loop with example.


• On reaching the do statement, the program proceeds to evaluate the
body of the loop first. At the end of the loop, the test-condition in the
while statement is evaluated.
• If the condition is true, the program continues to evaluate the body of
the loop once again.
• This process continues as long as the condition is true
do
{
body of the loop
}
While(test-condition)

Write a program to find factorial using do while


#include <stdio.h>
void main()
{
int n,product,i;
printf("Enter a number\n");
scanf("%d",&n);
i=1;
product=1;
do
{
product=product*i;
i++;
15 | P a g e GAT STUDENTS LIBARY
}
while(i<=n);
printf("factorial is %d\n",product);
}

4) Differentiate between while and do-while with an example.


while loop do while loop
• while(test condition) • Syntax:
{ initialization;
Body of the loop do
} {
body of the loop
• Condition is tested before start of
}while(condition);
the loop body.
• Condition is tested after the loop
• Minimum no.of times loop body body.
is executed is zero. • Minimum no. of times loop body
(i.e if the condition is false, loop is executed is once. (i.e even if the
body is not executed). condition is false, loop body is
• Also called entry controlled or executed atleast once).
pre-test loop • Also called as exit controlled or
• Example program using while: post-test loop.
#include<stdio.h> void • Example program using do
main() while:
{ #include<stdio.h> void
int i; main()
printf(“Enter the value of n\n”); {
scanf(“%d”,&n); int n,i;
i=1; printf(“Enter the value of n:\n”);
while(i<=n) scanf(“%d”,&n);
i=1;
16 | P a g e GAT STUDENTS LIBARY
{ do
printf(“%d\t”,i); i++; {
} printf(“%d\t”,i); i++;
} }while(i<=n);
Output: }
Enter the value of n 3 Output:
123 Enter the value of n 3
123

17 | P a g e GAT STUDENTS LIBARY


5)Differentiate between break and continue with example.
The BREAK statement
When a break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement
immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it. That is, the break
will exit only a single loop

Skipping a Part of a Loop


• Skipping a part of the loop is done using continue statement.
• During execution of a loop, it may be necessary to skip a part of the
loop based on some condition. In such cases, use continue statement.
• The continue statement is used only in the loop to terminate the
current iteration.

18 | P a g e GAT STUDENTS LIBARY


Module 3
1)Define array. Explain the declaration and initialization of single
dimensional array with example.
Array is a collection of elements of same data type.
• The elements are stored sequentially one after the other in memory.
• Any element can be accessed by using
→ name of the array
→ position of element in the array (index)
Syntax of Declaring Single Dimensional Arrays
data_type array_name[array_size];
• where data_type can be int, float or char
• array_name is name of the array
• array_size indicates number of elements in the array
Eg: int age[5];

INITIALIZATION:
One dimensional arrays can be initialized in 2
ways
1)At compile time
2)At run time
1. Compile Time initialization
– Giving values to array at the time of array declaration itself is
called compile time initialization. Values are separated by commas.
• Syntax:
datatype arrayname[size]={v1,v2…vn};
• Example:
int a[3]={10,20,30};
float b[2]={1.1,2.2};
• Character arrays may be initialized in a similar
19 | P a g e GAT STUDENTS LIBARY
manner. Thus, the statement
char name[ ] = {‘J’,‘o’, ‘h’, ‘n’, ‘\0’};
• Alternatively, we can assign the string literal
directly as under:
char name [ ] = “John”
➢ The various ways of initializing arrays are as
follows:
1. Initializing all elements of array(Complete array initialization)
2. Partial array initialization
3. Initialization without size
4. Initialize individual elements
1. Initializing all elements of array:
➢ Arrays can be initialized at the time of declaration
when their initial values are known in advance.
➢ In this type of array initialization, initialize all the
elements of specified memory size.
➢ Example: int a[5]={10,20,30,40,50};

2. Partial array initialization


➢ If the number of values to be initialized is less than
the size of array then it is called as partial array
initialization.
➢ In such a case elements are initialized in the order
from 0th element.
➢ The remaining elements will be initialized to zero
automatically by the compiler.
➢ Example: int a[5]={10,20}

20 | P a g e GAT STUDENTS LIBARY


3. Initialization without size
➢ here the size of the array is optional
➢ The compiler will set the size based on the number of initial values.
➢ Example: int a[ ]={10,20,30,40,50};
➢ In the above example the size of an array is set to 5
4)Initialize individual elements:
We can initialize individual elements of the array.
Example: int a[3];
a[0] =10;
a[1] =20;
a[2] =30;
2)Run time Initialization:
• Array can be initialized at runtime using for loop.
Eg:
int a[3];
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}
Reading and writing single dimensional arrays.
• To read array elements from keyboard we can use scanf() function as
follows:
• To read 0 th element:
scanf(“%d”,&a[0]);
To read 1 st element:
scanf(“%d”,&a[1]);
To read 2 nd element:
scanf(“%d”,&a[2]);
…… ……
To read ‘n’th element :

21 | P a g e GAT STUDENTS LIBARY


scanf(“%d”,&a[n-1]);

2) Define array. Explain the declaration and initialization of two-


dimensional array with an example.
Declaration of two dimensional array:
data_type array_name[row_size][column_size];
data_type can be int, float, char, double.
array_name is the name of the array.
row_size and column_size indicates number of rows and columns
For example:
int a[2][3]:
Representation:- an array with 2 rows and 3 columns

INITIALIZING 2D ARRAYS
• Two dimensional arrays can be initialized in 2 ways
1)At compile time
2)At run time
1. Compile Time initialization
i)Basic initialization: Mentioning the array size and all the values at the
time of declaration.
Example: int a[2][3]={6,4,2,1,8,26};
ii)Initialization without size: While initializing a 2-D array it is
necessary to mention the second (column) dimension, whereas the first
dimension (row) is optional.
Example: int a[][3]={6,4,2,1,8,26};
22 | P a g e GAT STUDENTS LIBARY
iii)Partial initialization: can initialize the array elements partially
as in the below example.
int a[2][3]={{1,2},{5}}
• Initializing row wise
Example:- int a[3][3]= { {10,20,30},
{40,50,60},
{70,80,90} };
• Combining row elements and initializing
int a[3][3]= { 10,20,30,40,50,60,70,80,90 };

2. At run time:
• (reading 2D array elements)
Two for loops are needed to initialize two dimensional array at runtime.
for(i=0;i <m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
EXAMPLE PROGRAM:
Write a program to read and display matrix
#include<stdio.h>
void main()
{
int a[10][10],m,n,i,j;
printf("Enter number of rows and columns\n");

23 | P a g e GAT STUDENTS LIBARY


scanf("%d%d",&m,&n);
printf("Enter elements of matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
Output:

3) Define string. Explain declaration and initialization of string


variables with example.
• Array of character are called strings.
• A string is terminated by null character \0.
• Eg:
• “A String”
"A String"
➢ Declaration of String
24 | P a g e GAT STUDENTS LIBARY
Syntax:
char string_name[size];
Eg:
char name[21];
• //string variable name can hold maximum of 20 characters plus
NULL character('\0‘)
• Size of the string should always be number of characters plus 1
because string should end with '\0'.
• Length of the string: Number of characters stored in string up to “\0‟
but not including NULL character. Length of the string is different
from its declared size
Initialization
1.Initilaizing strings at compile time:
• Like numeric arrays, character arrays may be initialized
when they are declared.
• C permits a character array to be initialized in either of
the following two forms:
char city [9] = “NEW YORK”;
char city [9]={‘N’,‘E’,‘W’,‘ ‘,‘Y’,‘O’,‘R’,‘K’,‘\0’};
The reason that city had to be 9 elements long is that the string NEW
YORK contains 8 characters and one element space is provided for the
null terminator.
• Partial String Initialization
char name[6]={‘C,’P’,’S’,’\0’};

• Initialization without size


char name[]={‘C,’P’,’S’,’\0’};

defines the array string as a four element array


• String initialization
25 | P a g e GAT STUDENTS LIBARY
char name[9]=“computer”

➢ Using scanf and gets function (run time string initialization)


scanf()
• The familiar input function scanf can be used with %s format
specification to read in a string of characters.
Example: char s1[20];
scanf(“%s”, s1);
• scanf can read strings of only one word i.e it cannot includwhitespace.
gets():
• reads a sequence of characters from keyboard including white space.
– Syntax: gets(str);
– Eg: gets(s1);
WRITING STRINGS TO SCREEN
• Using printf function we can print strings. It prints all characters up
to '\0'
Eg: printf(“%s”,s1);
• Using putchar and puts Functions
• C supports another character handling function putchar to output the
values of character variables. It takes the following form:
char ch = ‘A’;
putchar (ch);
puts():
– puts( ) can display only one string at a time
– Syntax: puts(str);
– Eg: puts(s1);

Example Program: Example Program:


#include <stdio.h> #include <stdio.h>
void main() void main()
{ {
char s1[100]; char s1[100];
printf("Enter string\n"); printf("Enter string\n");
gets(s1);
scanf("%s",s1);
26 | P a g e G A T Sputs(s1);
TUDENTS LIBARY
printf("%s",s1);
}
} Output:
Output: Enter string
Enter string
4)Explain the following string handling functions with examples.
a) strcat() c) strcmp()
b) strcpy() d) strlen()

1)strlen() function
• This function counts the number of characters present in a string
Syntax:
length=strlen(string);
Example program using strlen()
#include <stdio.h>
#include<string.h>
void main()
{
char str[100];
int length;
printf("Enter string\n");
scanf("%s",str); //or use gets(str)
length=strlen(str);
printf("Length of the string is %d\n",length);
}
27 | P a g e GAT STUDENTS LIBARY
2)strcpy() function
• This function copies the contents of source string to destination string.
• Syntax: strcpy(dest, source);
Or
strcpy(string1, string2);
– and assigns the contents of string2 to string1.
• strcpy(city, “DELHI”);
– will assign the string “DELHI” to the string variable city.
Similarly, the statement
– strcpy(city1, city2);
– will assign the contents of the string variable city2 to
the string variable city1

Example program using strcpy()


#include <stdio.h>
#include<string.h>
void main()
{
char source[100],dest[100];
printf("Enter string\n");
gets(source);
strcpy(dest,source);
printf("Copied string is %s\n",dest);
}

3)strcat() function:
• strcat function is used to join two strings together.
• Syntax: strcat(string1,string2);
• Ex:-

28 | P a g e GAT STUDENTS LIBARY


strcat(part1, part2)

Example program using strcat()


#include <stdio.h>
#include<string.h>
void main()
{
char str1[100],str2[100];
printf("Enter first string\n");
scanf("%s",str1);
printf("Enter second string\n");
scanf("%s",str2);
strcat(str1,str2);
printf("Concatenated string is %s\n",str1);
}
4)strcmp() function
• This is a function which compares two strings to find out whether they
are same or different.
• The two strings are compared character by character until there is a
mismatch or end of one of the strings is reached, whichever occurs first.
• Syntax:
result=strcmp(string1, string2);
• Eg: result=strcmp(name1,name2);
– result=0 if string1 = string2
– result>0 if string1>string2
– result<0 if string1<string2
• The value of the mismatch is rarely important. For example, the
statement
strcmp(“their”, “there”);
• will return a value of –9 which is the numeric difference between
ASCII “i” and ASCII “r”.
• That is, “i” minus “r” in ASCII code is (105-114= –9).
29 | P a g e GAT STUDENTS LIBARY
• If the value is negative, string1 is alphabetically above string2
Example program using strcmp()
#include <stdio.h>
#include<string.h>
void main()
{
char str1[100],str2[100];
int result;
printf("Enter first string\n");
gets(str1);
printf("Enter second string\n");
gets(str2);
result =strcmp(str1,str2);
if(result ==0)
printf("Strings are equal");
else if(result >0)
printf("First string is greater than second string\n");
else
printf("Second string is greater than first string\n");
}

30 | P a g e GAT STUDENTS LIBARY


MODULE 4:
1. Explain elements/ components of function or Explain function
definition, function call and function declaration with example.
The three elements of user defined functions are:-
1. Function declaration
2. Function definition
3. Function Call
1. Function Declaration / Function prototype:
• Like variables, all functions in a C program must be declared,
before they are invoked. A function declaration (also known as
function prototype) consists of four parts.
• Function type or Return Type
• Name of the Function
• Parameter list.
• Terminating semicolon.
• Syntax of Function Declaration:
return_type function_name(parameter list with datatype);
Example: int add(int a, int b);
int – return type
add – function name
int a, int b – parameter list
2. Function Definition:
A function definition, also known as function implementation shall
include the following elements:
1. function name;
2. function type;
3. list of parameters;
4. local variable declarations;
5. function statements; and
6. a return statement.
• All the six elements are grouped into two parts, namely,
31 | P a g e GAT STUDENTS LIBARY
– function header (First three elements); and
– function body (Second three elements).
It provides the actual body of the function.
• It contains Executable Code (Executable statements).
• Syntax of function definition:
return_type function_name(parameter list with datatype)
{
Local variable declarations;
Statement(s);
return value;
}

Function Call :
• A function can be called by simply using the function name followed
by a list of actual parameters (or arguments) if any enclosed in
parentheses.
• Syntax: function_name(parameters);
• Example: add(a,b);
Write a function to find sum of two numbers.
#include<stdio.h>
int add(int a, int b ); -----------------→//function declaration
void main()
{
int a,b,c;
printf(“\n Enter the values of a and b\n”);

32 | P a g e GAT STUDENTS LIBARY


scanf(“%d %d”, &a,&b);
c=add(a, b ); ------------------------------→//function call
printf(“sum is %d”,c);
}
int add(int a, int b) ---------------------------→// function definition
{
int sum;
sum = a+b;
return sum;
}
Output:
Enter the values of a and b
2
3
Sum is 5

• The function which calls another function is called as calling


function
Example: main( )
• The function which is called by another function is called as called
function.
Example: add( )
2. What is a function. Explain types of function based on
parameters.
A function is a group or block of statements that perform a particular
task. The function can be classified into two categories:
1. Built in function or Library defined functions.
2. User defined functions.
Formal Parameter:
• Parameter written in function definition and function declaration is
called “formal parameter”.
• The formal parameters will receive the data sent by the calling program.
• Since these parameters formally represent the actual values and are not
the actual values, they are called formal parameters
33 | P a g e GAT STUDENTS LIBARY
Example
#include<stdio.h>
void display(int a); -------------→//function declaration
void main()
{
int x=10;
display (x); ---------→//function call
}
void display(int a)-----------------→ //function definition
{
printf(“%d”, a);
}
Here a is the formal parameter
Actual Parameter:
• Parameter written in function call is called “actual parameter” because
they are the actual values used for computation.
Example
#include<stdio.h>
void display(int a); --------→//function declaration
void main()
{
int x=10;
display (x); //function call
}
void display(int a) //function definition
{
printf(“%d”,a);
}
Here x is the actual parameter

3. Explain the concept of passing of 1-d array as function argument


with suitable example.
Passing One Dimensional Arrays : Like the values of simple variables
it is also possible to pass the values of an array to a function. To pass a

34 | P a g e GAT STUDENTS LIBARY


one dimensional array to a function it is sufficient to list the name of the
array, without any subscripts , and the size of the array as arguments.
Example:- int big(int a[ ], int n);
Consider the problem of finding the largest value in an array of elements
#include<stdio.h>
int big(int a[ ],int n)
{
int i,max;
max = a[0] ;
for(i =1;i<n ;i++)
{
if(a[i]>max)
max = a[i];
}
return max;
}
void main()
{
int i,n,a[100], large;
printf(“ Enter the value of n \n”);
scanf(“%d”, &n);
printf(“ Enter %d elements \n”, n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
large= big(a,n);
printf(“\n The largest element is %d\n”,large);

}
• Three Rules to pass an array to a function:
1. The function must be called by passing only the name of the array.
2. In the function definition the formal parameter must be an array type,
the size of the array does not need to be specified.
35 | P a g e GAT STUDENTS LIBARY
3. The function prototype must show that the argument in an array.
4. What is recursion? Write a C program to calculate factorial of a
number using recursion..
• Recursion refers to the process where a function calls itself repeatedly
until a certain exit condition is met.
• A function which calls itself repeatedly until a certain exit condition
is met is called recursive function.
#include<stdio.h>
int fact(int n);
void main( )
{
int k , a;
printf(“enter the value of number \n” );
scanf(“%d”, &k);
a= fact(k);
printf(“the factorial of a %d is %d”, k, a);
}
int fact(int n)
{
if(n==0)
return 1;
else
return( n * fact(n-1));
}
5. What is a pointer? Explain how the pointer variable is declared
and initialized.
• A pointer is a variable whose value is the address of another variable.
• Pointers contain memory addresses as their values.
Pointer Declaration:
Pointer variables should be declared before they are used.
Syntax: datatype *pointer_name;
Eg: int *p; /*pointer to an integer */
36 | P a g e GAT STUDENTS LIBARY
float *f; /*pointer to float*/
Initialization of Pointer :
• It is the process of assigning an address to the pointer variable.
• Syntax: pointer_name =&variable_name;
Eg: int a=10;
int *p ; //pointer declaration
p= &a; //Initialization of pointer variable
Categories of user defined functions:
1. Function with parameters and with return values.
2. Functions with parameters and without return values
3. Function without parameter and with return values.
4. Functions without parameters and without return values. (Void and
parameter less Functions).
6. List and explain the categories of user defined function
Categories of user defined functions
1. Function with parameters and with return values.
2. Functions with parameters and without return values
3. Function without parameter and with return values.
4. Functions without parameters and without return values. (Void and
parameter less Functions).
1. Function with parameters and with return values.
• Parameters are passed from calling function to the called function.
Based on the received parameter values called function performs
required action and returns a value back to the calling function.
Example:
//C program to find the cube of a given number
#include<stdio.h>
int cube(int k);
void main()
{
int n,
printf(“Enter a Number\n”);
scanf(“%d”,&n);
a=cube(n);
37 | P a g e GAT STUDENTS LIBARY
printf(“cube of %d is %d\n”,n,a);
}
int cube(int k)
{
int c;
c=k*k*k;
return c;
}
Output:
Enter a number
3
Cube of 3 is 27
2. Function with parameters and without return values
• Parameters are passed from calling function to called function and
called function does not return a value. It just performs the specified
action.
Example:
//C program to find the cube of a given number
#include<stdio.h>
void cube(int k);
void main()
{
int n;
printf(“Enter a Number\n”);
scanf(“%d”,&n);
cube(n);
}
void cube(int k)
{
int c;
c=k*k*k;
printf(“cube of %d is %d\n”,k,c);
}
3. Function without parameters and with return values

38 | P a g e GAT STUDENTS LIBARY


• function does not receive any parameter fromcalling function. It takes
the parameter within itself and performs specified action andreturns a
result to calling function.
Example:
#include<stdio.h>
int cube( );
void main()
{
int a;
a=cube( );
printf(“cube is %d\n”,a);
}
int cube( )
{
int n,c;
printf(“Enter a Number\n”);
scanf(“%d”,&n);
c=n*n*n;
return c;
}

4. Function without parameters and without return values


• No parameter is passed from the calling function to the called
function. Called function does not return any values to the calling
function. This type of function is also called as void and parameter less
Functions).
Example:
#include<stdio.h>
void cube( );
void main()
{
cube( );
}
void cube( )
{
39 | P a g e GAT STUDENTS LIBARY
int n,c;
printf(“Enter a Number\n”);
scanf(“%d”,&n);
c=n*n*n;
printf(“cube of %d is %d\n”,n,c);
}
7. Explain parameter passing techniques/ argument passing
techniques in functions ( call by value and call by reference) with an
example program.
Argument Passing – call by value, call by reference
There are two ways of passing parameters to the function
• Pass by Value (Call by value)
• Pass by Reference (Call by Reference)
• Pass by Value (Call by value): Here the values of actual parameters
are copied into formal parameters i.e. formal parameters contain only
the copy of actual parameters. So even if the value of the formal
parameters changes in the called function the values of the actual
parameters are not changed
#include<stdio.h>
void swap (int m , int n) ----------→// Formal Parameters m,n
{
int temp;
temp = m;
m = n;
n = temp;
}
void main()
{
int a,b;
a=10, b=20;
printf(“\n The values of a and b before calling swap\n”);
printf(“\n a=%d b= %d \n “,a,b);
swap(a,b); //Actual Parameters a,b
printf(“\n The values of a and b after calling swap()\n”);
40 | P a g e GAT STUDENTS LIBARY
printf(“\n a =%d and b = %d \n”,a,b);
}
• Pass by Reference (Call by Reference) :In pass by reference/ address
when a function is called the address of actual parameters are sent. In
the called function the formal parameters should be declared as pointers
with the same type as the actual parameters. Using these addresses the
values of the actual parameters can be changed. This way of changing
the actual parameters is called pass by addresses.
#include<stdio.h>
void swap (int *m , int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
void main()
{
int a,b;
a=10, b=20;
printf(“\n The values of a and b before calling swap is a=%d b=
%d \n“,a,b );
swap(&a,&b);
printf(“\n The values of a and b after calling swap()\n”);
printf(“\n a=%d and b = %d \n”,a,b);
}
8. Differentiate i) User defined and built-in functions ii) Recursion
and iteration
i) User defined function and built-in function
Library defined functions: User defined function:
• C Library that comes with C • C allows programmers to create
compiler has a collection of their own functions called as user
various functions which perform defined functions.
standard and predefined tasks. • These user defined functions are
required because built in functions
41 | P a g e GAT STUDENTS LIBARY
• C language provides many built provided by C are not sufficient
in functions such as, for performing customized
– Mathematical functions such as functions.
pow(x,y) , sqrt(x,y) etc.,
– String manipulation functions
such as strlen(),strcpy() etc.,
– Memory management functions
malloc(),calloc() etc.,

ii) Recursion and iteration.


Iteration not there in ppt
9. Explain pointer increments with an example
Increment operator on Pointer
• when we increment a pointer, its value is increased by the ‘length’
of the data type that it points to. This length called the scale factor
Final value of pointer = current value of the pointer + ( integer
value * size of the data type)

Eg:
int *ptr;
If ptr=1000,
ptr++ = ptr + (1*size of int)
= 1000+(1*2)=1002
float *ptr;
If ptr=1000,
ptr++ = ptr + (1*size of float)
= 1000+(1*4)=1004

#include<stdio.h>
main()
42 | P a g e GAT STUDENTS LIBARY
{
int a,*p;
p=&a;
printf(“value of pointer p before decrementation %u “, p);
p--;
printf(“value of pointer p after decrementation %u “, p);
}
Output:
value of pointer p before decrementation: 3472147
value of pointer p after decrementation : 3472145
10. Illustrate the use of indirection operator ‘*’ in accessing a value
pointed by a pointer with an example program

Module 5
1. Define a structure. Explain the syntax of structure declaration in
C with an example.
Structure is a collection of elements of same or different data types
under a single name.
Structure Definition:
Syntax:
struct tagName
{
datatype member1;
datatype member2;
------------
------------
datatype membern;
};
Example :
struct employee
43 | P a g e GAT STUDENTS LIBARY
{
char name[20];
float salary;
int empno;
};
2. Differentiate between Array and Structures.
Arrays Strings
1. An array is a collection of 1. Structure is a collection of
elements of the same data type elements of different data type.
2. An array is a derived data type 2. A structure is a user defined
3. Array uses index/subscript for data type
accessing elements of the array. 3. Structures uses (.) operator for
4. . An array is a pointer to the accessing the member of a
first element of it. structure.
5. Eg: int a[10] 4. Structure is not a pointer
5. Eg: struct employee
{
char name[20];
int empno;
float salary;
};
3. Explain with an example the different ways of declaring structure
variables.
Declaring Structure Variables:
• A structure variable declaration is similar to thedeclaration of
variables of any other data types. It includes the following elements:
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
Syntax: struct tagName variable1,variable2;
Eg: struct employee emp1,emp2;
Another way of structure variable declaration

44 | P a g e GAT STUDENTS LIBARY


• It is also allowed to combine both the structure definition and
variables declaration in one statement.
• The declaration
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
is valid. The use of tag name is optional here.
4. Explain with an example the way of accessing structure members.
Accessing Members of Structures
• The member of structure is identified and accessed using the dot
operator(.)
• The link between a member and a variable is established using the
member operator ‘.’ which is also known as ‘dot operator’ or‘period
operator’.
Syntax is :
struct_variable.membername;
Example : Consider the structure definition and initialization as shown
below:
struct employee
{
char name[10];
float salary ;
int empno;
};
struct employee e = { “Raj”,1000,1};
e.name can access the string “Raj”
e.salary can access the value 1000
e.empno can access the value of 1
45 | P a g e GAT STUDENTS LIBARY
Displaying the various members of Structures
printf(“%s”,e.name); //prints the name of the employee
printf(“%f”,e.salary); // prints the salary
printf(“%d”,e.empno); //prints the employee number

Reading the values for various members of structures


scanf(“%s”, e.name); //reads the employee name
scanf(“%f”, &e.salary); // reads the salary of employee
scanf(“%d”, &e.empno); // reads the employee id
5. Explain with an example the structure initialization.
Structure Initialization:
• Assigning the values to the structure member fields is known as
structure initialization.
• Syntax:
struct tagName variable = {value1,value2,…valuen};
• Eg:
struct employee emp1 = { “Raj”,1000,1};

6. Define the Rules for initializing structure variables


Rules for Initializing Structures
• We cannot initialize individual members inside the structure template.
• The order of values enclosed in braces must match the order of
members in the structure definition.
• It is permitted to have a partial initialization. We can initialize only the
first few members and leave the remaining blank. The uninitialized
members should be only at the end of the list.
• The uninitialized members will be assigned default values as follows:
• Zero for integer and floating point numbers.
• ‘\0’ for characters and strings.
46 | P a g e GAT STUDENTS LIBARY
10. Define a file. Explain with an example and syntax opening and
closing file operations.
A file is a place on the disk where a group of related data is stored.
Like most other languages, C supports a number of functions that
have the ability to perform basic file operations, which include:
• naming a file,
• opening a file,
• reading data from a file,
• writing data to a file, and
• closing a file
OPENING A FILE
• If we want to store data in a file in the secondary memory, we must
specify certain things about the file, to the operating system. They
include the following:
• Filename
• Data structure
• Purpose
• Filename is a string of characters that make up a valid filename for
the operating system. It may contain two parts, a primary name and
an optional period with the extension
• Data structure of a file is defined as FILE in the library of standard I/O
function definitions
• general format for declaring and opening a file:
FILE *fp;
fp = fopen(“filename”, “mode”);
• The first statement declares the variable fp as a “pointer to the data
type FILE”.
• The second statement opens the file filename and assigns an identifier
to the FILE type pointer fp. It also specifies the purpose of opening this
file. The mode does this job.
• Modes
• r open the file for reading only.
47 | P a g e GAT STUDENTS LIBARY
• w open the file for writing only.
• a open the file for appending (or adding) data to it.
Many recent compilers include additional modes of operation. They
include:
• r+ The existing file is opened to the beginning for both reading
and writing.
• w+ Same as w except both for reading and writing.
• a+ Same as a except both for reading and writing.
CLOSING A FILE
• A file must be closed as soon as all operations on it have been
completed. This ensures that all outstanding information associated with
the file is flushed out from the buffer sand all links to the file are broken
fclose(file_pointer);
EXAMPLE:-
FILE *p1, *p2;
p1 = fopen(“INPUT”, “w”);
p2 = fopen(“OUTPUT”, “r”);
…….
…….
fclose(p1);
fclose(p2);
11. Explain the different types of input/output operations that can
be carried out on files with an example for each operation.
The getc and putc Functions
• Assume that a file is opened with mode w and fi le pointer fp1. Then,
the statement
putc(c, fp1);
• writes the character contained in the character variable c to the file
associated with FILE pointer fp1.
• Similarly, getc is used to read a character from a fi le that has been
opened in read mode. For example, the statement
c = getc(fp2);
• would read a character from the fi le whose fi le pointer is fp2.
The getw and putw Functions
48 | P a g e GAT STUDENTS LIBARY
• The getw and putw are integer-oriented functions. They are used to
read and write integer values. These functions would be useful when
we deal with only integer data.
• The general forms of getw and putw are as follows:
putw(integer, fp);
getw( fp);
The fprintf and fscanf Functions
• The first argument of these functions is a file pointer which specifies
the file to be used. The general form of fprintf is
fprintf(fp, “control string”, list);
• where fp is a file pointer associated with a file that has been opened
for writing.
• The control string contains output specifications for the items in the
list.
• The list may include variables, constants and strings.
• Example:
fprintf(f1, “%s %d %f”, name, age, 7.5);
• The general format of fscanf is
fscanf(fp, “control string”, list);
• This statement would cause the reading of the items in the list from
the file specified by fp, according to the specifications contained in
the control string. Example:
fscanf(f2, “%s %d”, item, &quantity);
14. Explain how error handling is performed during I/O File
operations
ERROR HANDLING DURING I/O OPERATIONS
• It is possible that an error may occur during I/O operations on a fi le.
Typical error situations include the following:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a fi le that has not been opened.
4. Trying to perform an operation on a fi le, when the fi le is opened for
another type of operation.
5. Opening a fi le with an invalid filename.
49 | P a g e GAT STUDENTS LIBARY
6. Attempting to write to a write-protected file
• we have two status-inquiry library functions; feof and ferror that can
help us detect I/O errors in the files.
• The feof function can be used to test for an end of file condition. It
takes a FILE pointer as its only argument and returns a nonzero
integer value if all of the data from the specified file has been read,
and returns zero otherwise
if(feof(fp))
printf(“End of data.\n”);
• would display the message “End of data.” on reaching the end of file
condition.
• The ferror function reports the status of the file indicated. It also
takes a FILE pointer as its argument and returns a nonzero integer if
an error has been detected up to that point, during processing. It
returns zero otherwise. The statement
if(ferror(fp) != 0)
printf(“An error has occurred.\n”);
• would print the error message, if the reading is not successful.
• If the file cannot be opened for some reason, then the function returns
a NULL pointer. This facility can be used to test whether a file
has been opened or not. Example:
if(fp == NULL)
printf(“File could not be opened.\n”);

50 | P a g e GAT STUDENTS LIBARY

You might also like