Download as pdf or txt
Download as pdf or txt
You are on page 1of 96

Programming in 'C'

Practical: 1
 Process of creating C program:
The process of creating C programs is starting with writing the code and executing the binary,
which can be divided into 6 steps. These steps group into three: writing the code (Step-1),
building the program (Step- 2 to 4) and running the program (Step- 5 to 6). The steps are as
follows:

1. Writing source code

2. Preprocessing

3. Compiling

4. Linking

5. Loading

6. Executing

 How to Compile and Run a C Program on Ubuntu Linux using the gcc compiler
Step 1. Open up a terminal

Step 2. Use a text editor to create the C source code.

Type the command: gedithello.c

and in file, enter the C source code

Step 3. Compile the program.

Type the command: gcc -o hello hello.c

This command will invoke the GNU C compiler to compile the file hello.c and output (-o)
the result to an executable called hello.

Step 4. Execute the program.

Type the command : ./hello

1
Programming in 'C'

 Data types
Data types specify how we enter data into our programs and what type of data we enter.

These datatypes have different storage capacities.


C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.

2. Derived data types:


Derived data types are nothing but primary datatypes but a little twisted or grouped
together like array, stucture, union and pointer.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be
declared as what data-type it is.

Following are the examples of some very common data types used in C:

 char: It stores a single character and requires a single byte of memory in almost all
compilers.
 int: An int variable is used to store an integer.
 float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
 double: It is used to store decimal numbers (numbers with floating point value) with
double precision.
 void type: void type means no value. This is usually used to specify the type of functions
which returns nothing.

 Different data types also have different ranges up to which they can store numbers.

Integer type

Type Size(bytes) Range


int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295

2
Programming in 'C'

Floating point type


Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Character type
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255

3
Programming in 'C'

Practical: 1
Aim: a) Introduction to Linux programming and compiling process of C program.

4
Programming in 'C'

Practical: 1
Aim: b) Write a program to print "Hello World".

Code:

Output:

5
Programming in 'C'

Practical: 1
Aim: c) Write a program to print values of different data types.

Code:

Output:

6
Programming in 'C'

Practical: 1
Aim: d) Write a program to take input from command line arguments and print
it on screen.

Code:

Output:

7
Programming in 'C'

Practical: 1
Post Laboratory Questions

1. What is Linux programming?

2. Write down steps to execute C program in Linux operating system.

3. Enlist four basic data types.

4. What is command line argument?

5. State the difference between void main() and int main().

8
Programming in 'C'

6. What is the size of character data type?

7. Find errors, if any, in following program:

#include (stdio.h)

void main (void)

print (“Hello”);

8. Why do we need to use comments in programs?

9. Which header file contains standard input and output functions?

10. Every program statement in a C program must end with a _______.

Grade

Sign

9
Programming in 'C'

Practical: 2
scanf function:
 It is used to read the formatted data from the user.
 It is included in the stdio.h header file.
 Syntax: scanf(“format string”, arg1,arg2...argn);
o The format string specifies the field format in which data is to be entered.
o The arguments arg1,arg2...argnare the variable names in which entered values
should be stored.
 Format string contains field specification which is used in interpretation of input data.
 Field specification consists of conversion character %, a data type character and field width
(optional).

Field specification Data type Value Example

%d int (decimal) 10, -255

%c char ‘a’, ‘$’

%f float 6.78, 0.008

%o int (octal) 06, 0771


(number starts with 0) (Digits from 0 to 7)

%x int 0X19, 0xF4


(hexadecimal) (number starts with 0X or 0x)
(Digits from 0 to 9, A to F)

%s char array “Hello”


(Read the character up to first white space)

%wd int Read the integer type of data with width w

Examples:

 scanf(“%c %d”, &ch,&a); - It reads character data and stored in ch, reads integer data
and stored in a.
 scanf(“%d-%d”,&a,&b); - It reads the integer data into form 40-60, stores 40 in a and 60
in b.
 scanf(“%3d %5d”,&i,&j); - It reads three digits number into i and five digits number into
j. 3 and 5 specifies width of the data.

10
Programming in 'C'

Practical: 2
Aim: a) Write a program to take two numbers from the user and print its
addition and subtraction on screen.

Code:

Output:

11
Programming in 'C'

Practical: 2
Aim: b) Write a program to print ASCII code for a given character.

Code:

Output:

12
Programming in 'C'

Practical: 2
Aim: c) Write a program to swap values of two variables without using a third
variable.

Code:

Output:

13
Programming in 'C'

Practical: 2
Post Laboratory Questions

1. Write down the ASCII code of following characters:

Character ASCII code Character ASCII code

A K

G e

P 0

s $

2. The ___________ header file contains mathematical functions.

3. What is variable?

4. Which of the following are invalid variable names and why?

Minimum, &name, Sum total, float, total

Valid variable names:

Invalid variable names:

5. How to assign values to variables? Give one example for it.

14
Programming in 'C'

6. State whether the following statements are true or false:

i) ANSI C treats the variables- name and Name to the same.

ii) The scanf function can be used to read only one value at a time.

iii) Declaration can appear anywhere in a program.

iv) A variable can be used to store a value of any data type.

7. What is a syntax error?

8. Write the format specifier for the given values.

Values Suitable format specifier

100

‘R’

15
Programming in 'C'

45.89

9876666

9. What will be the values of variables after executing this code for given inputs?

void main()

int a,b;

scanf(“%2d %4d”,&a,&b);

inputs: 3467 87

a= ______________

b= ______________

Grade

Sign

16
Programming in 'C'

Practical: 3
What is Typecasting in C?

 Typecasting is converting one data type into another one. It is also called as data
conversion or type conversion.
 C programming provides two types of type casting operations:
o Implicit type casting
o Explicit type casting
 Implicit type conversion happens automatically when a value is copied to its compatible
data type. If the operands are of two different data types, then an operand having lower
data type is automatically converted into a higher data type.

#include<stdio.h>
int main(){
short x=5; //initializing variable of short data type
int y; //declaring int variable
y=x; //implicit type casting y is of type int and x is of type short
printf("%d\n",x); short data type is copied into the variable
printf("%d\n",y); a which is of an int data type.
}
Output
5
5

Converting Character to Int

Consider the example of adding a character decoded in ASCII with an integer:


#include <stdio.h>
main () {
int number = 1;
char character = 'k'; /*ASCII value is 107 */
int sum;
sum = number + character; Here compiler automatically converting
printf("Value of sum : %d\n", sum ); the value of 'k' to ASCII before
} performing the actual addition operation.
Output:
Value of sum: 108

Note: If you declare sum as float then output will be:

Value of sum: 108.00

17
Programming in 'C'

Explicit type casting

 In implicit type conversion, the data type is converted automatically.


 suppose we have a variable RESULT that stores the division of two operands which are
declared as an int data type.

int RESULT, n1=10, n2=3;


RESULT=n1/n2;
 In this case, after the division performed on variables n1 and n2 the result stored in the
variable "RESULT" will be in an integer format. Whenever this happens, the value stored
in the variable "RESULT" loses its meaning because it does not consider the fraction part
which is normally obtained in the division of two numbers.
 To force the type conversion in such situations, we use explicit type casting.
 The general syntax for type casting operations is as follows:

(type-name) expression

Here,
• The type name is the standard 'C' language data type.
• An expression can be a constant, a variable or an actual expression.
 Let us write a program to demonstrate implementation of explicit type-casting in 'C'.

#include<stdio.h>
int main()
{
float X = 1.7;
Int Y = (int)X + 1; If you write, int Y = X
printf("Value of a is %f\n", X); Then Compiler will throw an error because x is of
printf("Value of b is %d\n",Y); type float and y is of type int
return 0;
}
Output:
Value of X is 1.700000
Value of Y is 2

18
Programming in 'C'

Practical: 3
Aim: a) Write a program to find area of circle.

Code:

Output:

19
Programming in 'C'

Practical: 3
Aim: b) Write a program to convert number from integer to float, float to
integer and integer to character.

Code:

Output:

20
Programming in 'C'

Practical: 3
Aim: c) Write a program to convert temperature from celsius to fehrenhit.

Code:

Output:

21
Programming in 'C'

Practical: 3
Post Laboratory Questions

1. Enlist categories of C operators.

2. Enlist arithmetic operators with their meanings.

3. What is implicit type conversion?

4. What is explicit type conversion?

Grade

Sign

22
Programming in 'C'

Practical: 4
Decision Making Statement

Decision Making

If else Statement Switch Statement

Simple if-else

Nested if-else

Ladder else-if

Simple if-else:

if(condition)
{
Conditio
statement-1;
n
}
else
{ else part if part
statement-2; (statement (stateme
} -2) nt-1)
statement-3; Next line
(statement
-3)
Nested if else:

23
Programming in 'C'

if(condition-1)
{ Tru
if(condition-2) Condition- e
{ 1
statement-1;
}
else
{
Fal
statement-2; se
Condition-
} 2
}
else
{ Tru Fal
e se
if(condition-3)
{ Cond. 1:
Cond. 1: true
statement-3; true Cond. 2:
} Cond. 2: false
else true Statement-
{ Statement- 2
statement-4; 1
Condition-
} 3
}
Next statement;
Tru Fal
e se
Cond. 1:
false Cond. 1:
Cond. 3: false
true Cond. 3:
Statement- false
3 Statement-
4
Next
Statement

else-if ladder

24
Programming in 'C'

if(condition-1)
{ Cond. 1: true
statement-1; Condition-1
Statement-1
}
else if(condition-2)
{
statement-2;
}
Condition-2 Cond. 1: false
else if(condition-3)
Cond. 2: true
{ Statement-2
statement-3;
}
else
{ Cond. 1: false
statement-4; Condition-3 Cond. 2: false
} Cond. 3: true
Next statement; Statement-3

All cond.: false


Statement-4

Next Statement

Switch statement

25
Programming in 'C'

switch (condition)
{ Switch
case Label1: Condition
statement-1;
case Label2:
statement-2;
default:
statement-3; case Label-1 statement-1;
} break;
Next statement;

statement-2;
case Label-2
break;

default block;
statement-3;

Next statement

26
Programming in 'C'

Practical: 4
Aim: a) Write a program to find whether a given number is positive, negative
or zero.

Code:

Output:

27
Programming in 'C'

Practical: 4
Aim: b) Write a program to check whether a given number is odd or even.

Code:

Output:

28
Programming in 'C'

Practical: 4
Aim: c) Write a program to find the maximum of three numbers.

Code:

Output:

29
Programming in 'C'

Practical: 4
Aim: d) Write a program using switch statement to check whether a given
character is vowel or not.

Code:

Output:

30
Programming in 'C'

Practical: 4
Post Laboratory Questions

1. Enlist relational operators with their meanings.

2. What is the output of the following program?


int a=10, b=5;
if ( a> b )
{
if ( b> 5 )
printf( “%d” , b );
}
else
printf( “%d” , a );

3. Write equivalent switch statement for following code segment:

int level=1;
if(level==3)
{
printf(“You are excellent!”);
}
else if(level==2)
{
printf(“Keep it up!!”);
}
else if(level==1)
{
printf(“Work Hard!!”);
}
else
{
printf(“Invalid level..”);

31
Programming in 'C'

4. The _____________ statement transfers the control out of the switch statement.

5. What is the output of following expression:

y= ( x> 2 ) ? ( 2 * x + 5 ) : ( 1.5 * x + 3);

6. State true / false: else part can be worked without any if statement.

Grade

Sign

32
Programming in 'C'

Practical: 5
What is Loop?
 Loops in programming come into use when we need to repeatedly execute a block of
statements.
 For example: Suppose we want to print “Hello CGPIT” 10 times.
 For Loop: A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.

Syntax of for Loop


The syntax of a for loop in C programming language is −
for (initialization; condition; increment /decrement) {
statement(s);
}
Here is the flow of control in a 'for' loop −
 The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just
after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up to the increment or
decrement statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment or decrement step, and then again condition). After the
condition becomes false, the 'for' loop terminates.

In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below.
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition
is reached.

Without using loop With using loop


#include <stdio.h> #include <stdio.h>
void main() void main()
{ {
printf( " Hello CGPIT \n"); int i;
printf( " Hello CGPIT \n"); for (i=0; i<=10; i++)
printf( " Hello CGPIT \n"); {
printf( " Hello CGPIT \n"); printf( "Hello CGPIT\n");
printf( " Hello CGPIT \n"); }
printf( " Hello CGPIT \n"); }

33
Programming in 'C'

printf( " Hello CGPIT \n");


printf( " Hello CGPIT \n");
printf( " Hello CGPIT \n");
printf( " Hello CGPIT \n");
}
Output: Output:

Hello CGPIT Hello CGPIT


Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT
Hello CGPIT Hello CGPIT

Flowchart of for Loop

Initialization

Condition

If condition is true

Statement If condition is false

Increment
/Decrement

Next Statement

34
Programming in 'C'

Practical: 5
Aim: a) Write a program to print numbers from 1 to N in ascending and
descending order, where N is the user input.
Code:

Output:

35
Programming in 'C'

Practical: 5
Aim: b) Write a program to find addition of numbers between N1 to N2 which
are divisible by 5, where N1 and N2 are user input.

Code:

Output:

36
Programming in 'C'

Practical: 5
Aim: c) Write a program to find factorial of given number.

Code:

Output:

37
Programming in 'C'

Practical: 5
Post Laboratory Questions

1. What are loops?

2. _______ loop is entry controlled loop statement.

3. Which are the three constructs for performing loop operation in C language?

4. A for loop with the no test condition is known as _______ loop.

5. State the difference between break and goto.

6. What is exit controlled loop?

38
Programming in 'C'

7. Write down the syntax of for loop.

8. State the difference between while loop and do…while loop.

9. What is the output of following code:


int n = 0, m;
for ( m = 1 ; m <= n + 1 ; m++ )
printf( "%d",m );

10. The _______ statement is used to skip a part of the statements in a loop.

Grade

Sign

39
Programming in 'C'

Practical: 6

while loop
while(condition)
{ Condition
statement-1;
}
statement-2;

Statement-1

Statement-2

do-while loop
do
{ Statement-1
statement-1;
}while(condition);
statement-2;

Condition

Statement-2

40
Programming in 'C'

Practical: 6
Aim: a) Write a program to count odd numbers present in given range.

Code:

Output:

41
Programming in 'C'

Practical: 6
Aim: b) Write a program to find sum of digits of a given number.

Code:

Output:

42
Programming in 'C'

Practical: 6
Aim: c) Write a program to check whether given number is Armstrong or not.

Code:

43
Programming in 'C'

Output:

44
Programming in 'C'

Practical: 6
Aim: d) Write a program to print prime numbers present between given
range.

45
Programming in 'C'

Practical: 6
Post Laboratory Questions

1. How many times the following loop will execute?


int main()
{
int n=10,i=0;
while(i<n)
{
printf("Hello\n");
i+=2;
}
return 0;
}

2. Write equivalent while loop and do-while loop for following for loop.

for(i=20;i>=2;i--)
{
printf(“%d\n”,i);
}

3. Find errors, if any, in following program and write correct code:


while (x = 0 ; x < 5 ; x++)
{
printf ("x = %d\n", x);
x++;
}

Grade

Sign

46
Programming in 'C'

Practical: 7
Nested loop
 Nested loop means a loop statement inside another loop statement. That is why
nested loops are also called as “loop inside loop “.
 Syntax for Nested For loop:

for ( initialization; condition; increment ) {


for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}

 Syntax for Nested While loop:

while(condition) {
while(condition) {
// statement of inside loop }
// statement of outer loop }

 Syntax for Nested Do-While loop:

do{ do{
// statement of inside loop
}while(condition);

// statement of outer loop


} while(condition);

Note: There is no rule that a loop must be nested inside its own type. In fact, there can be
any type of loop nested inside any type and to any level.
do {
while(condition) {
for (initialization; condition; increment) {
// statement of inside for loop
}
// statement of inside while loop
}
// statement of outer do-while loop
} while(condition);

47
Programming in 'C'

Practical: 7
Aim: a) Write a program to print following pattern:

*
**
***
Code:

Output:

48
Programming in 'C'

Practical: 7
Aim: b) Write a program to print following pattern:

1
22
333
Code:

Output:

49
Programming in 'C'

Practical: 7
Aim: c) Write a program to print following pattern:

1
23
456
Code:

Output:

50
Programming in 'C'

Practical: 7
Aim: d) Write a program to print following pattern:

A
B C
D E F

51
Programming in 'C'

Practical: 7
Post Laboratory Questions

1. What is an infinite loop?

2. What is a nested loop?

3. Write down comparison between for loop and while loop.

4. State whether the following statements are true or false:

i) The for statement allow for negative increments.

ii) For and do while loops are pre-test loops.

Grade

Sign

52
Programming in 'C'

Practical: 8
Array:
 Array is the collection of elements having the same data type.
 Multiple values can be stored into one name.
 Elements are stored in contiguous memory locations.
 Elements can be accessed randomly using index.
 The starting index of an array is 0.

Syntax:
 Declaration: datatype variable_name[size];

 Initialization: datatype variable_name[]={v1,v2,...vn}; OR

o datatype variable_name[size]={v1,v2,...vn};

 Accessing: variable_name[index]=value;

Example:
 Declaration: int ary[5];

 Initialization: int ary[]={6,3,7,10}; OR int ary[4]=={6,3,7,10};

 Accessing: ary[2]=100;

Memory Representation:
int a[6]={10,20,30,40,50,60};

2000 10 a[0]

2004 20 a[1]

2008 30 a[2]

2012 40 a[3]

2016 50 a[4]

2020 60 a[5]

53
Programming in 'C'

Base address is the address of the first element of an array, pointed by array name.

Address of ith index element= base_address + (i * sizeof(datatype));

Over here, base address =2000.

Index Address

0 2000

1 2004

2 2008

3 2012

4 2016

5 2020

54
Programming in 'C'

Practical: 8
Aim: a) Write a program to store values in an array and print each element on
screen.
Code:

Output:

55
Programming in 'C'

Practical: 8
Aim: b) Write a program to find addition of array elements.

Code:

56
Programming in 'C'

Output:

57
Programming in 'C'

Practical: 8
Aim: c) Write a program to print elements present in even indices.

Code:

Output:

58
Programming in 'C'

Practical: 8
Post Laboratory Questions

1. Declare one dimensional array having size 4 and type float.

2. Write a loop to access each element of an array with the size n.

3. An array can be initialized either at compile time or ________.

4. Identify errors, if any, in each of the following initialization statements.

i) int number [ ] = { 0 , 0 , 0 , 0, 0 } ;

ii) float item [ 3 ] [ 2 ] = { 0 , 1 , 2 , 3 , 4 , 5 } ;

iii) char word * + = , ‘ A ’ , ‘ R ’ , ‘ R ’ , ‘ A ’ , ‘Y’ - ;

iv) float result [ 10 ] = 0 ;

5. Enlist types of array.

59
Programming in 'C'

6. State whether the following statements are true or false.

i) An array can store infinite data of similar type.

ii) When an array is declared, C automatically initializes its elements to zero.

iii) Accessing an array outside it’s rang is a compile time error.

iv) Array index starts with -1.

Grade

Sign

60
Programming in 'C'

Practical: 9

Two- Dimensional Array


 An array of arrays is known as 2D array.
 The two-dimensional (2D) array in C programming is also known as matrix.
 A matrix can be represented as a table of rows and columns.

Syntax:
 Declaration: datatype variable_name[rows][columns];
 Initialization:
Example: int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; OR
arr[4][3]={1,2,3,2,3,4,3,4,5,4,5,6}
 Accessing: variable_name[row][columns]=value;
Example: arr[2][1]=4

Memory representation:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Column 0 Column 1 Column 2


Row 0 arr[0][0] arr[0][1] arr[0][2]
Row 1 arr[1][0] arr[1][1] arr[1][2]
Row 2 arr[2][0] arr[2][1] arr[2][2]
Row 3 arr[3][0] arr[3][1] arr[3][2]

Column 0 Column 1 Column 2


Row 0 1 2 3
Row 1 2 3 4
Row 2 3 4 5
Row 3 4 5 6

61
Programming in 'C'

Practical: 9
Aim: a) Write a program to copy elements from one matrix to another matrix.

Code:

62
Programming in 'C'

Output:

63
Programming in 'C'

Practical: 9
Aim: b) Write a program to find addition of two matrices.

Code:

64
Programming in 'C'

Output:

65
Programming in 'C'

Practical: 9
Aim: c) Write a program to find maximum elements from a matrix.

Code:

66
Programming in 'C'

Output:

67
Programming in 'C'

Practical: 9
Post Laboratory Questions

1. What are multidimensional arrays?

2. Write down syntax to declare two-dimensional array.

3. An array that uses more than two subscript is referred to as _______ array.

4. How initial values can be assigned to a multi-dimensional array?

Grade

Sign

68
Programming in 'C'

Practical: 10
String:
 To represent the string in C language, a character array is used.
 Character array is terminated by a null character '\0'.
 To initialize string: char c*6+=,‘H’,’e’,’l’,’l’,’o’,’\0’-; OR char c*+=”Hello”;

String Input from user:

Syntax Description

scanf(“%s”,str); Read the string until one white space is found, and store it in
str.

scanf(“%^*\n+”,str); %^[x] is format specification. It reads the string until character


x is encountered. (In example \n)

for(i=0;i<6;i++) It reads character by character and stored in str.


{
scanf(“%c”,&str*0+);
}

gets(str); It reads the line until a new line character is encountered. It


can read white spaces also.

String functions: All functions are included in string.h library.

Function Syntax Description

strlen() n=strlen(string); computes string's length

strcpy() strcpy(string1,string2); copies the content of string2 to


string1

strcat() strcat(string1,string2) string2 is appended to string1

strcmp() int strcmp(string1,string2) compares two strings

strrev() char[] strrev(string) Reverse the string

strstr() strstr(string1,string2) Finds the first occurrence of string2


into string1

69
Programming in 'C'

Practical: 10
Aim: a) Write a program to demonstrate following:

Edit set command[^\n], getchar(), gets(), putchar(), puts()

Code:

Output:

70
Programming in 'C'

Practical: 10
Aim: b) Write a program to find length of a string.

Code:

Output:

71
Programming in 'C'

Practical: 10
Aim: c) Write a program to convert string from upper case to lower case.

Code:

Output:

72
Programming in 'C'

Practical: 10
Aim: d) Write a program to find whether given string is palindrome or not
using string handling function.

73
Programming in 'C'

Practical: 10
Post Laboratory Questions

1. Enlist the ways used to print the string on the terminal.

2. The function strcat(s1,s2) appends _____________ string to _________ string.

3. What is the output of the following code segment? How does it come?

printf(“%d”, strcmp(“push”,”pull”));

4. Assume string has the value “ Hello CGPIT.” What will be the output for following
segment:
a. printf(“%s”,string);

b. puts(string);

c. for(i=0;string*i+!=’ ‘;i++)
, printf(“%c”,string*i+);-

74
Programming in 'C'

5. Write a program to take input character by character until ‘q’ is pressed.

Grade

Sign

75
Programming in 'C'

Practical: 11
User define Function
 A function is a block of code that performs a specific task.
 C allows you to define functions according to your need. These functions are known as
user-defined functions.
 Any function (library or user-defined) has 3 things

1. Function declaration
2. Function calling
3. Function defintion

 Function declaration:
Syntax: return data_typefunction_name(arguments list);
 Function Definition:
Syntax:
return data_typefunction_name(argument list)
{
Body;
}
 Function Calling:
Syntax: Function_name(param_list);
 Formal Arguments: The arguments which are given at the time of function declaration or
function definition are called formal arguments.
 Actual Arguments:
 The arguments which are given at the time of function calling are called actual
arguments.

Example:

#include <stdio.h>
#include <conio.h>
void CGPIT(); /* Function Declaration */
void main()
{
CGPIT(); /* Function Calling */
}

void CGPIT() /* Function Definition*/


{

76
Programming in 'C'

printf("\n WELCOME TO THE WORLD OF CGPIT");


}

How to pass arguments to function?

#include<stdio.h>
int add(int , int );
int main()
{
………..
Sum=add(x , y);
……
}
int add(int n1, int n2 )
{
………..
………..
}

77
Programming in 'C'

Practical: 11
Aim: a) Write a program to find last digit of a given number using user
defined function.

Code:

Output:

78
Programming in 'C'

Practical: 11
Aim: b) Write a program to check whether the character is alphabet or not
using user defined function.

Code:

Output:

79
Programming in 'C'

Practical: 11
Aim: c) Design calculator using user defined function.

Code:

80
Programming in 'C'

Output:

81
Programming in 'C'

Practical: 11
Post Laboratory Questions

1. What is the use of the function in C?

2. How many arguments can be passed to a function in C?

3. By default, ______ is the return type of a C function.

4. The main is a user-defined function. How does it differ from other user-defined
functions?

5. Find errors in the following function calls:

i) void xyz( )

ii) xyz( )

Grade

Sign

82
Programming in 'C'

Practical: 12
Recursion:
 When a function is calling itself is called recursion.
 It has two things normally: Steps to repeat and terminating condition.

Example:

int m1(int a)
{
if(a==1)
return -1;
else
return a-m1(a-1);
}

The function is called as m1(4), how does it work?

m1(4) m1(3) m1(2) m1(1)

Result:4 -1
0 3

83
Programming in 'C'

Practical: 12
Aim: a) Write a program to find addition of first N numbers using recursion.

Code:

Output:

84
Programming in 'C'

Practical: 12
Aim: b) Write a program to find factorial using recursion.

Code:

Output:

85
Programming in 'C'

Practical: 12
Post Laboratory Questions
1. What is the output of following code:

main ( )

printf( “ Hello World \n ” ) ;

main ( ) ;

2. The ________________ data structure used to implement recursive function calls.

3. In the absence of an exit condition in a recursive function, the following error is


given __________ .

4. What will be the output for following code?

#include<stdio.h>
main()
{
int n,i;
n=f(6);
printf("%d",n);
}
f(int x)
{
if(x==2)
return 2;
else
{

86
Programming in 'C'

printf("+");
f(x-1);
}
}

Grade

Sign

87
Programming in 'C'

Practical: 13
Structure
 Structure is a group of variables of different data types represented by a single name.
 Lets say we need to store the data of students like student name, age, address, id etc.
One way of doing this would be creating a different variable for each attribute, however
when you need to store the data of multiple students then in that case, you would need
to create these several variables again for each student.
 We can solve this problem easily by using structure. We can create a structure that has
members for name, id, address and age and then we can create the variables of this
structure for each student.

How to create a structure?

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};
How to declare variable of a structure?
struct struct_namevar_name;
or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;

How to access data members of a structure using a struct variable?


Structure members are accessed using dot (.) operator.
var_name.member1_name;
var_name.member2_name;

88
Programming in 'C'

Practical: 13
Aim: Define structure data type called Result having structure member
enrolment number, marks of three subjects. Write a program to calculate
result percentage of 3 students using structure Result.
Code:

89
Programming in 'C'

Output:

90
Programming in 'C'

Practical: 13
Post Laboratory Questions

1. What are structure types in C?

2. What is the structure?

3. The variable declared in a structure definition are called its ________.

4. How does a structure differ from an array?

5. Write two different ways of assigning values to structure members with example.

Grade

Sign

91
Programming in 'C'

Practical: 14
Pointers:
 Pointers are special variables used to store the address of a variable.
 The address of any variable can be found using the special operator (&).
 For example: address of variable a is identified using &a.
 To declare any variable as pointer, the specified operator (*) will be used.

Pointer declaration:
 Syntax: data type * variable_name;
 Example:
○ int *p1;
○ int* p1;
○ int * p1;

Assigning address:
int a=10;
int *p1=&a;
Variable a is declared as integer and has the value 10.
Variable p1 is declared as a pointer to integer and has the address of variable a.

Example:
void main()
{
int a=300; // a has the value 300.
int *p=&a; // p is the pointer storing the address of variable a.

printf(“%d\n”,a); //300
printf(“%d\n”,&a); //Address of a

printf(“%d\n”,p); // Address of p

printf(“%d\n”,*p); // Value of a (300)

printf(“%d\n”,&p); // Address of p

92
Programming in 'C'

Practical: 14
Aim: a) Write a program to swap values of two variables using pointer.

Code:

Output:

93
Programming in 'C'

Practical: 14
Aim: b) Write a program to perform addition of two numbers using pointer.

Code:

Output:

94
Programming in 'C'

Practical: 14
Post Laboratory Questions

1. What is pointer?

2. A pointer variable contains as its value the ________ of another variable.

3. What are the arithmetic operators that are permitted on pointer?

4. What is the output of the following code?


int m [ 2 ] ;

*( m + 1 ) = 100 ;

*m=*(m+1);

printf( “ % d ” , m [ 0 ] ) ;

5. Write down benefits of pointers.

95
Programming in 'C'

6. Find error, if any


a. int *y=10;

b. int a, *b=&a;

c. int m;

int **x=&m;

7. Consider the following declarations:

int x=18,y=10;

int *p1=&x, *p2=&y;

What is the value of each of the following expressions?

a. (*p1)++
b. *p1+(*p2)--
c. (*p1)-x+(*p2)-y

Grade

Sign

96

You might also like