+ All Categories
Home > Documents > Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue...

Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue...

Date post: 27-Jun-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
29
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING THROUGH ‘C’ LAB Practical: COMPUTER PROGRAMMING THROUGH ‘C’ LAB Subject Code: 1600306 1. Programming exercise on executing a C program. If you are looking for C programs, please click here “C programs”. This C programming basics section explains a simple “Hello World” C program. Also, it covers below basic topics as well, which are to be known by any C programmer before writing a C program. 1. C programming basic commands to write a C program 2. A simple C program with output and explanation 3. Steps to write C programs and get the output 4. Creation, Compilation and Execution of a C program * How to install C compiler and IDE tool to run C programming codes 5. Basic structure of a C program * Example C program to compare all the sections * Description for each section of the C program 1. C PROGRAMMING BASICS TO WRITE A C PROGRAM: Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line. C Basic commands Explanation #include <stdio.h> This is a preprocessor command that includes standard input output header file(stdio.h) from the C library before compiling a C program int main() This is the main function from where execution of any C program begins. { This indicates the beginning of the main function. /*_some_comments_*/ whatever is given inside the command
Transcript
Page 1: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING THROUGH ‘C’ LAB

Practical: COMPUTER PROGRAMMING THROUGH ‘C’ LAB

Subject Code: 1600306

1. Programming exercise on executing a C program.

If you are looking for C programs, please click here “C programs”.

This C programming basics section explains a simple “Hello World” C program. Also, it

covers below basic topics as well, which are to be known by any C programmer before

writing a C program.

1. C programming basic commands to write a C program

2. A simple C program with output and explanation

3. Steps to write C programs and get the output

4. Creation, Compilation and Execution of a C program

* How to install C compiler and IDE tool to run C programming codes

5. Basic structure of a C program

* Example C program to compare all the sections

* Description for each section of the C program

1. C PROGRAMMING BASICS TO WRITE A C PROGRAM:

Below are few commands and syntax used in C programming to write a simple C program.

Let’s see all the sections of a simple C program line by line.

C Basic commands Explanation

#include <stdio.h>

This is a preprocessor command that

includes standard input output header

file(stdio.h) from the C library before

compiling a C program

int main()

This is the main function from where

execution of any C program begins.

{

This indicates the beginning of the main

function.

/*_some_comments_*/ whatever is given inside the command

Page 2: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

“/* */” in any C program, won’t be

considered for compilation and execution.

printf(“Hello_World!

“);

printf command prints the output onto the

screen.

getch();

This command waits for any character input

from keyboard.

return 0;

This command terminates C program (main

function) and returns 0.

} This indicates the end of the main function.

2. A SIMPLE C PROGRAM:

Below C program is a very simple and basic program in C programming language. This C

program displays “Hello World!” in the output window. And, all syntax and commands in C

programming are case sensitive. Also, each statement should be ended with semicolon (;)

which is a statement terminator.

#include <stdio.h>

int main()

{

/* Our first simple C basic program */

printf("Hello World! ");

getch();

return 0;

}

OUTPUT:

Hello World!

3. STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for any C program to create and get the output. This is

common to all C program and there is no exception whether its a very small C program or

very large C program.

1. Create

2. Compile

3. Execute or Run

4. Get the Output

4. CREATION, COMPILATION AND EXECUTION OF A C PROGRAM:

Prerequisite:

If you want to create, compile and execute C programs by your own, you have to install

C compiler in your machine. Then, you can start to execute your own C programs in

your machine.

You can refer below link for how to install C compiler and compile and execute C

programs in your machine.

Page 3: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

Once C compiler is installed in your machine, you can create, compile and execute C

programs as shown in below link.

If you don’t want to install C/C++ compilers in your machine, you can refer online

compilers which will compile and execute C/C++ and many other programming

languages online and display outputs on the screen. Please search for online C/C++

compilers in Google for more details.

5. BASIC STRUCTURE OF A C PROGRAM:

Structure of C program is defined by set of rules called protocol, to be followed by

programmer while writing C program. All C programs are having sections/parts which

are mentioned below.

1. Documentation section

2. Link Section

3. Definition Section

4. Global declaration section

5. Function prototype declaration section

6. Main function

7. User defined function definition section

EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS:

You can compare all the sections of a C program with the below C program.

/*

Documentation section

C programming basics & structure of C programs

*/

#include <stdio.h> /* Link section */

int total = 0; /* Global declaration, definition section */

int sum (int, int); /* Function declaration section */

int main () /* Main function */

{

printf ("This is a C basic program \n");

total = sum (1, 1);

printf ("Sum of two numbers : %d \n", total);

return 0;

}

int sum (int a, int b) /* User defined function */

{

return a + b; /* definition section */

}

OUTPUT:

This is a C basic program

Sum of two numbers : 2

Page 4: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

DESCRIPTION FOR EACH SECTION OF THE C PROGRAM:

Let us see about each section of a C basic program in detail below.

Please note that a C program mayn’t have all below mentioned sections except main

function and link sections.

Also, a C program structure mayn’t be in below mentioned order.

Sections Description

Documentation

section

We can give comments about the program,

creation or modified date, author name etc in this

section. The characters or words or anything

which are given between “/*” and “*/”, won’t be

considered by C compiler for compilation

process.These will be ignored by C compiler

during compilation.

Example : /* comment line1 comment line2

comment 3 */

Link Section

Header files that are required to execute a C

program are included in this section

Definition

Section

In this section, variables are defined and values

are set to these variables.

Global

declaration

section

Global variables are defined in this section. When

a variable is to be used throughout the program,

can be defined in this section.

Function

prototype

declaration

section

Function prototype gives many information about

a function like return type, parameter names used

inside the function.

Main function

Every C program is started from main function

and this function contains two major sections

called declaration section and executable section.

User defined

function section

User can define their own functions in this

section which perform particular task as per the

user requirement.

Page 5: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

2. Programming exercise on case Control Statement. The statements which are used to execute only specific block of statements in a series of

blocks are called case control statements.

There are 4 types of case control statements in C language. They are,

1. switch

2. break

3. continue

4. goto

EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C:

1. switch case statement in c:

• switch case statements are used to execute only specific case statements based on the

switch expression.

• below is the syntax for switch case statement.

switch (expression)

{

case label1: statements;

break;

case label2: statements;

break;

case label3: statements;

break;

default: statements;

break;

}

#include <stdio.h>

int main ()

{

int value = 3;

switch(value)

{

case 1:

printf(“Value is 1 \n” );

break;

case 2:

printf(“Value is 2 \n” );

break;

case 3:

printf(“Value is 3 \n” );

break;

case 4:

printf(“Value is 4 \n” );

Page 6: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

break;

default :

printf(“Value is other than 1,2,3,4 \n” );

}

return 0;

}

Output:

Value is 3

2. BREAK STATEMENT IN C:

Break statement is used to terminate the while loops, switch case loops and for loops

from the subsequent execution.

Syntax: break;

EXAMPLE PROGRAM FOR BREAK STATEMENT IN C:

#include <stdio.h>

int main()

{

int i;

for(i=0;i<10;i++)

{

if(i==5)

{

printf("\nComing out of for loop when i = 5");

break;

}

printf("%d ",i);

}

}

OUTPUT:

0 1 2 3 4

Coming out of for loop when i = 5

3. CONTINUE STATEMENT IN C:

Continue statement is used to continue the next iteration of for loop, while loop and do-

while loops. So, the remaining statements are skipped within the loop for that particular

iteration.

Syntax : continue;

EXAMPLE PROGRAM FOR CONTINUE STATEMENT IN C:

#include <stdio.h>

int main()

{

Page 7: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

int i;

for(i=0;i<10;i++)

{

if(i==5 || i==6)

{

printf("\nSkipping %d from display using " \

"continue statement \n",i);

continue;

}

printf("%d ",i);

}

}

OUTPUT:

0 1 2 3 4

Skipping 5 from display using continue statement

Skipping 6 from display using continue statement

7 8 9

4. GOTO STATEMENT IN C:

goto statements is used to transfer the normal flow of a program to the specified label in

the program.

Below is the syntax for goto statement in C.

{

…….

go to label;

…….

…….

LABEL:

statements;

}

EXAMPLE PROGRAM FOR GOTO STATEMENT IN C:

#include <stdio.h>

int main()

{

int i;

for(i=0;i<10;i++)

{

if(i==5)

{

printf("\nWe are using goto statement when i = 5");

goto HAI;

}

printf("%d ",i);

}

Page 8: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

HAI : printf("\nNow, we are inside label name \"hai\" \n");

}

OUTPUT:

0 1 2 3 4

We are using goto statement when i = 5

Now, we are inside label name “hai”

Page 9: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

3. Programming exercise on Decision Control Statement.

In decision control statements (if-else and nested if), group of statements are executed

when condition is true. If condition is false, then else part statements are executed.

There are 3 types of decision making control statements in C language. They are,

1. if statements

2. if else statements

3. nested if statements

“IF”, “ELSE” AND “NESTED IF” DECISION CONTROL STATEMENTS IN C:

Syntax for each C decision control statements are given in below table with description.

Decision control

statements Syntax/Description

if

Syntax:

if (condition)

{ Statements; }

Description:

In these type of statements, if condition is

true, then respective block of code is

executed.

if…else

Syntax:

if (condition)

{ Statement1; Statement2; }

else

{ Statement3; Statement4; }

Description:

In these type of statements, group of

statements are executed when condition is

true. If condition is false, then else part

statements are executed.

nested if

Syntax:

if (condition1){ Statement1; }

else_if(condition2)

{ Statement2; }

else Statement 3;

Description:

If condition 1 is false, then condition 2 is

checked and statements are executed if it is

true. If condition 2 also gets failure, then

else part is executed.

Page 10: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

EXAMPLE PROGRAM FOR IF STATEMENT IN C:

In “if” control statement, respective block of code is executed when condition is true.

int main()

{

int m=40,n=40;

if (m == n)

{

printf("m and n are equal");

}

}

OUTPUT:

m and n are equal

EXAMPLE PROGRAM FOR IF ELSE STATEMENT IN C:

In C if else control statement, group of statements are executed when condition is true. If

condition is false, then else part statements are executed.

#include <stdio.h>

int main()

{

int m=40,n=20;

if (m == n)

{

printf("m and n are equal");

}

else

{

printf("m and n are not equal");

}

}

OUTPUT:

m and n are not equal

EXAMPLE PROGRAM FOR NESTED IF STATEMENT IN C:

In “nested if” control statement, if condition 1 is false, then condition 2 is checked and

statements are executed if it is true.

If condition 2 also gets failure, then else part is executed.

#include <stdio.h>

int main()

{

int m=40,n=20;

Page 11: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

if (m>n) {

printf("m is greater than n");

}

else if(m<n) {

printf("m is less than n");

}

else {

printf("m is equal to n");

}

}

OUTPUT:

m is greater than n

Page 12: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

4. Programming exercise on looping.

Loop control statements in C are used to perform looping operations until the given condition

is true. Control comes out of the loop statements once condition becomes false.

TYPES OF LOOP CONTROL STATEMENTS IN C:

There are 3 types of loop control statements in C language. They are,

1. for

2. while

3. do-while

Syntax for each C loop control statements are given in below table with description.

Loop Name Syntax

for

for (exp1; exp2; expr3)

{ statements; }

Where,

exp1 – variable initialization

( Example: i=0, j=2, k=3 )

exp2 – condition checking

( Example: i>5, j<3, k=3 )

exp3 – increment/decrement

( Example: ++i, j–, ++k )

while

while (condition)

{ statements; }

where,

condition might be a>5, i<10

do while

do { statements; }

while (condition);

where,

condition might be a>5, i<10

EXAMPLE PROGRAM (FOR LOOP) IN C:

In for loop control statement, loop is executed until condition becomes false.

#include <stdio.h>

int main()

{

int i;

for(i=0;i<10;i++)

{

printf("%d ",i);

}

Page 13: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

}

OUTPUT:

0 1 2 3 4 5 6 7 8 9

EXAMPLE PROGRAM (WHILE LOOP) IN C:

In while loop control statement, loop is executed until condition becomes false.

#include <stdio.h>

int main()

{

int i=3;

while(i<10)

{

printf("%d\n",i);

i++;

}

}

OUTPUT:

3 4 5 6 7 8 9

EXAMPLE PROGRAM (DO WHILE LOOP) IN C:

In do..while loop control statement, while loop is executed irrespective of the condition for

first time. Then 2nd time onwards, loop is executed until condition becomes false.

#include <stdio.h>

int main()

{

int i=1;

do

{

printf("Value of i is %d\n",i);

i++;

}while(i<=4 && i>=2);

}

OUTPUT:

Value of i is 1

Value of i is 2

Value of i is 3

Page 14: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

Value of i is 4

DIFFERENCE BETWEEN WHILE & DO WHILE LOOPS IN C LANGUAGE:

while do while

Loop is executed

only when

condition is true.

Loop is executed for first time

irrespective of the condition. After

executing while loop for first

time, then c

Page 15: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

5. Programming exercise on recursion technique.

The process of calling a function by itself is called recursion and the function which calls

itself is called recursive function. Recursion is used to solve various mathematical problems

by dividing it into smaller problems. This method of solving a problem is called Divide and

Conquer.

In programming, it is used to divide complex problem into simpler ones and solving them

individually.

Syntax of Recursive Function

returntype recursive_func ([argument list])

{

statements;

... ... ...

recursive_func ([actual argument]);

... ... ...

}

Syntax of Recursive Function

returntype recursive_func ([argument list])

{

statements;

... ... ...

recursive_func ([actual argument]);

... ... ...

}

In this program, func1() calls func2(), which is a new function. But this new function func2()

calls the first calling function, func1(), again. This makes the above function an indirect

recursive function.

Example #4: C program to calculate factorial of a number using recursion.

#include<stdio.h>

int factorial(int n)

{

if(n==0)

return 1;

else

return (factorial(n-1)*n);

}

int main()

{

int num,f;

printf("Enter a number: ");

scanf("%d",&num);

f=factorial(num);

printf("Factorial of %d = %d",num,f);

return 0;

}

Page 16: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

Here, factorial is calculated using recursion. The formula for calculating factorial of a number

n is,

n! = 1*2*...(n-1)*n

Again, we can see

(n-1)! = 1*2*...(n-1)

Hence we can write,

n! = (n-1)! * n

We have implemented this recursive relation in our program.

Here,

The number whose factorial is to be found is stored in the variable n.

A recursive function factorial(num) calculates the factorial of the number.

As factorial is (n-1)! * n, factorial function calculates the factorial by recursively multiplying

n with factorial of (n-1).

Finally, when n = 0, it returns 1 because 0! = 1.

Output

Enter a number: 7

Factorial of 7 = 5040

Example #5: C program print first n Fibonacci numbers using recursion.

#include<stdio.h>

int fibo(int num)

{

if(num==1||num==2)

return 1;

else

return (fibo(num-1)+fibo(num-2)); // recursive call

}

int main()

{

int i,n;

printf("Enter the required term: ");

scanf("%d",&n);

printf("First %d fibonacci numbers are\n",n);

for (i=1; i<=n; i++)

printf("%d\n",fibo(i));

return 0;

}

This program uses recursion to generate Fibonacci series. In a Fibonacci series, nth term can

be obtained by adding (n-1)th and (n-2)th term. Mathematically,

Page 17: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

tn = tn-1 + tn-2

Here,

The number of fibonacci terms to be generated is taken from the user and stored in variable n.

A for loop is used to loop through the number to be generated which is sent to the function

fibo. This function is used to calculate and return fibonacci series.

Inside fibo, if the term-number is 1 or 2, it returns 1. This is because, the first two terms of

fibonacci series are both 1. The printed values are 1,1.

Then the next term-number 3 is passed onto fibo function, since it's not 1 or 2, the next term

in the series is calculated by taking fibo(n - 1) + fibo(n - 2), where n = 3. This calculates the

last two terms in the fibonacci series. This is equivalent to fibo(2) + fibo(1), which results in

1 + 1 = 2.

This recursive loop goes on finally printing the series as 1, 1, 2, 3, 5...

Output

Enter the required term: 7

First 7 fibonacci numbers are

1

1

2

3

5

8

13

Disadvantages of Recursion

Recursive programs are generally slower than non recursive programs because it needs to

make a function call so the program must save all its current state and retrieve them again

later. This consumes more time making recursive programs slower.

Recursive programs requires more memory to hold intermediate states in a stack. Non

recursive programs don't have any intermediate states, hence they don't require any extra

memory.

Page 18: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

6. Programming exercise on Structure.

C structures

Structure is a collection of variables of different types under a single name.

For example: You want to store some information about a person: his/her name, citizenship

number and salary. You can easily create different variables name, citNo, salary to store these

information separately.

However, in the future, you would want to store information about multiple persons. Now,

you'd need to create different variables for each information per person: name1, citNo1,

salary1, name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation

between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single name

Person, and use it for every person. Now, the code looks much cleaner, readable and efficient

as well.

This collection of all related information under a single name Person is a structure.

Structure Definition in C

Keyword struct is used for creating a structure.

Syntax of structure

struct structure_name

{

data_type member1;

data_type member2;

.

.

data_type memeber;

};

Note: Don't forget the semicolon }; in the ending line.

We can create the structure for a person as mentioned above as:

struct person

{

char name[50];

int citNo;

float salary;

};

This declaration above creates the derived data type struct person.

Structure variable declaration

Page 19: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

When a structure is defined, it creates a user-defined type but, no storage or memory is

allocated.

For the above structure of a person, variable can be declared as:

struct person

{

char name[50];

int citNo;

float salary;

};

int main()

{

struct person person1, person2, person3[20];

return 0;

}

Another way of creating a structure variable is:

struct person

{

char name[50];

int citNo;

float salary;

} person1, person2, person3[20];

In both cases, two variables person1, person2 and an array person3 having 20 elements of

type struct person are created.

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

Member operator(.)

Structure pointer operator(->) (is discussed in structure and pointers tutorial)

Any member of a structure can be accessed as:

structure_variable_name.member_name

Suppose, we want to access salary for variable person2. Then, it can be accessed as:

person2.salary

Example of structure

Write a C program to add two distances entered by user. Measurement of distance should be

in inch and feet. (Note: 12 inches = 1 foot)

#include <stdio.h>

struct Distance

Page 20: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

{

int feet;

float inch;

} dist1, dist2, sum;

int main()

{

printf("1st distance\n");

// Input of feet for structure variable dist1

printf("Enter feet: ");

scanf("%d", &dist1.feet);

// Input of inch for structure variable dist1

printf("Enter inch: ");

scanf("%f", &dist1.inch);

printf("2nd distance\n");

// Input of feet for structure variable dist2

printf("Enter feet: ");

scanf("%d", &dist2.feet);

// Input of feet for structure variable dist2

printf("Enter inch: ");

scanf("%f", &dist2.inch);

sum.feet = dist1.feet + dist2.feet;

sum.inch = dist1.inch + dist2.inch;

if (sum.inch > 12)

{

//If inch is greater than 12, changing it to feet.

++sum.feet;

sum.inch = sum.inch - 12;

}

// printing sum of distance dist1 and dist2

printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);

return 0;

}

Output

1st distance

Enter feet: 12

Enter inch: 7.9

Page 21: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

2nd distance

Enter feet: 2

Enter inch: 9.8

Sum of distances = 15'-5.7"

Keyword typedef while using structure

Writing struct structure_name variable_name; to declare a structure variable isn't intuitive as

to what it signifies, and takes some considerable amount of development time.

So, developers generally use typedef to name the structure as a whole. For example:

typedef struct complex

{

int imag;

float real;

} comp;

int main()

{

comp comp1, comp2;

}

Here, typedef keyword is used in creating a type comp (which is of type as struct complex).

Then, two structure variables comp1 and comp2 are created by this comp type.

Structures within structures

Structures can be nested within other structures in C programming.

struct complex

{

int imag_value;

float real_value;

};

struct number

{

struct complex comp;

int real;

} num1, num2;

Suppose, you want to access imag_value for num2 structure variable then, following structure

member is used.

num2.comp.imag_value

Passing structures to a function

There are mainly two ways to pass structures to a function:

Passing by value

Passing by reference

Page 22: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

7. Programs on array implementation.

An array is a collection of data that holds fixed number of values of same type. For example:

if you want to store marks of 100 students, you can create an array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

One-dimensional arrays

Multidimensional arrays

How to declare an array in C?

data_type array_name[array_size];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5

floating-point values.

Elements of an Array and How to access them?

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element

is mark[1] and so on.

C Array declaration

Few key notes:

Arrays have 0 as the first index not 1. In this example, mark[0]

If the size of an array is n, to access the last element, (n-1) index is used. In this example,

mark[4]

Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d,

address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array in C programming?

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

Page 23: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

int mark[] = {19, 10, 8, 17, 9};

Initialize an array in C programming

Here,

mark[0] is equal to 19

mark[1] is equal to 10

mark[2] is equal to 8

mark[3] is equal to 17

mark[4] is equal to 9

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element

mark[3] = 9;

// take input from the user and insert in third element

scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element

scanf("%d", &mark[i]);

// print first element of an array

printf("%d", mark[0]);

// print ith element of an array

printf("%d", mark[i-1]);

Example: C Arrays

// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>

int main()

{

int marks[10], i, n, sum = 0, average;

printf("Enter n: ");

scanf("%d", &n);

Page 24: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

for(i=0; i<n; ++i)

{

printf("Enter number%d: ",i+1);

scanf("%d", &marks[i]);

sum += marks[i];

}

average = sum/n;

printf("Average = %d", average);

return 0;

}

Output

Enter n: 5

Enter number1: 45

Enter number2: 35

Enter number3: 38

Enter number4: 31

Enter number5: 49

Average = 39

In C programming, you can create an array of arrays known as multidimensional array. For

example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the

array as table with 3 row and each row has 4 column.

Similarly, you can declare a three-dimensional (3d) array. For example,

Page 25: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

float y[2][4][3];

Here,The array y can hold 24 elements.

You can think this example as: Each 2 elements have 4 elements, which makes 8 elements

and each 8 elements can have 3 elements. Hence, the total number of elements is 24.

How to initialize a multidimensional array?

There is more than one way to initialize a multidimensional array.

Initialization of a two dimensional array

// Different ways to initialize two dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Above code are three different ways to initialize a two dimensional arrays.

Initialization of a three dimensional array.

You can initialize a three dimensional array in a similar way like a two dimensional array.

Here's an example,

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

Example #1: Two Dimensional Array to store and display values

// C program to store temperature of two cities for a week and display it.

#include <stdio.h>

const int CITY = 2;

const int WEEK = 7;

int main()

{

int temperature[CITY][WEEK];

for (int i = 0; i < CITY; ++i) {

for(int j = 0; j < WEEK; ++j) {

printf("City %d, Day %d: ", i+1, j+1);

Page 26: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

scanf("%d", &temperature[i][j]);

}

}

printf("\nDisplaying values: \n\n");

for (int i = 0; i < CITY; ++i) {

for(int j = 0; j < WEEK; ++j)

{

printf("City %d, Day %d = %d\n", i+1, j+1, temperature[i][j]);

}

}

return 0;

}

Output

City 1, Day 1: 33

City 1, Day 2: 34

City 1, Day 3: 35

City 1, Day 4: 33

City 1, Day 5: 32

City 1, Day 6: 31

City 1, Day 7: 30

City 2, Day 1: 23

City 2, Day 2: 22

City 2, Day 3: 21

City 2, Day 4: 24

City 2, Day 5: 22

City 2, Day 6: 25

City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33

City 1, Day 2 = 34

City 1, Day 3 = 35

City 1, Day 4 = 33

City 1, Day 5 = 32

City 1, Day 6 = 31

City 1, Day 7 = 30

City 2, Day 1 = 23

City 2, Day 2 = 22

City 2, Day 3 = 21

City 2, Day 4 = 24

City 2, Day 5 = 22

City 2, Day 6 = 25

Page 27: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

City 2, Day 7 = 26

Example #2: Sum of two matrices using Two dimensional arrays

C program to find the sum of two matrices of order 2*2 using multidimensional arrays.

#include <stdio.h>

int main()

{

float a[2][2], b[2][2], c[2][2];

int i, j;

// Taking input using nested for loop

printf("Enter elements of 1st matrix\n");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

{

printf("Enter a%d%d: ", i+1, j+1);

scanf("%f", &a[i][j]);

}

// Taking input using nested for loop

printf("Enter elements of 2nd matrix\n");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

{

printf("Enter b%d%d: ", i+1, j+1);

scanf("%f", &b[i][j]);

}

// adding corresponding elements of two arrays

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

{

c[i][j] = a[i][j] + b[i][j];

}

// Displaying the sum

printf("\nSum Of Matrix:");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

{

printf("%.1f\t", c[i][j]);

if(j==1)

printf("\n");

Page 28: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

}

return 0;

}

Ouput

Enter elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0

Example 3: Three Dimensional Array

C Program to store values entered by the user in a three-dimensional array and display

it.

#include <stdio.h>

int main()

{

// this array can store 12 elements

int i, j, k, test[2][3][2];

printf("Enter 12 values: \n");

for(i = 0; i < 2; ++i) {

for (j = 0; j < 3; ++j) {

for(k = 0; k < 2; ++k ) {

scanf("%d", &test[i][j][k]);

}

}

}

// Displaying values with proper index.

printf("\nDisplaying values:\n");

for(i = 0; i < 2; ++i) {

Page 29: Government Polytechnic Muzaffarpur.gpmuz.bih.nic.in/docs/cpc.pdf · 1. switch 2. break 3. continue 4. goto EXAMPLE PROGRAM FOR SWITCH..CASE STATEMENT IN C: 1. switch case statement

for (j = 0; j < 3; ++j) {

for(k = 0; k < 2; ++k ) {

printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);

}

}

}

return 0;

}

Output

Enter 12 values:

1

2

3

4

5

6

7

8

9

10

11

12

Displaying Values:

test[0][0][0] = 1

test[0][0][1] = 2

test[0][1][0] = 3

test[0][1][1] = 4

test[0][2][0] = 5

test[0][2][1] = 6

test[1][0][0] = 7

test[1][0][1] = 8

test[1][1][0] = 9

test[1][1][1] = 10

test[1][2][0] = 11

test[1][2][1] = 12


Recommended