Sie sind auf Seite 1von 63

Lab

Manual

NFC-INSTITUTE OF ENGINEERING
& FERTILIZERS RESEARCH
(NFC-IEFR),
FAISALABAD

DEPARTMENT OF ELECTRICAL
ENGINEERING

Programming Fundamentals
(EE-170L)

LAB MANUAL
Name:____________

Reg #: ___________

Prepared By:
Mr. Salman Arain
LAB-1

Introduction to IDE Environment for C Language

OBJECTIVE
Study the features of Integrated Development Environment (IDE) for C language.

THEORY
Dev-C++ is a full-featured Integrated Development Environment (IDE) for the C/C++ programming
language. As similar IDEs, it offers to the programmer a simple and unified tool to edit, compile, link,
and debug programs. It also provides support for the management of the files of a program in “projects”
containing all the elements required to produce a final executable program.

Dev-C++ uses Mingw port of GCC (GNU Compiler Collection) as a compiler. It can creates native
Win32 executables, either console or GUI, as well as DLLs and static libraries. Dev-C++ can also be used
in combination with Cygwin or any other GCC based compiler. In this session, we will use Mingw --
included in the default Dev-C++ distribution-- to create console C programs. Dev-C++ is a Free Software
distributed under the terms of the GNU General Public License (GPL).

Features of DEV-C++

Dev-C++ features are:

- Support GCC based compilers (Mingw included)


- Integrated debugging (with GDB)
- Support for multiple languages (localization)
- Class Browser
- Debug variable Browser
- Code Completion
- Function Listing
- Project Manager
- Customizable syntax highlighting editor
- Quickly create Windows, console, static libraries and DLL -
- Support of templates for creating your own project types
- Makefile creation
- Edit and compile Resource files
- Tool Manager
- Print support
- Find and replace facilities
- Package manager, for easy installation of add-on-libraries

PROGRAMMING FUNDAMENTALS
First steps

The application development process encompasses the following steps:

1. Create a project

The type of application and the programming language to be used are specified.

2. Write source code

Write the program in C and save the source code file.

3. Compile and link the code

The source code is compiled and linked to generate a running program. Other files of the project may be
created.

4. Fix compilation errors, if any

If the syntax of the program is not correct, the compilation fails and the compiler generates a message
related to the error/s. The programmer must correct the errors.

5. Run the program

Run the program to validate the functioning.

6. Fix execution errors, if any

If the actions performed by the program are not as expected, it is necessary to correct the source code. It
may be also convenient to use the debugger to find complex errors.

Project creation

A project is a center for managing your different source files and options inside Dev-C++. It helps you
navigate through your code, and easily set different parameters, like the type of program you are doing
(GUI, console, DLL ...).

A project groups several files with a common purpose. In our programs, projects will include a file with
metadata about the project (.dev), a file with C source code (.c), a file with object code (.o), and a file
with linking instructions (makefile.win). Only the .c file must be explicitly created –the remaining files
are automatically created by Dev-C++.

When creating a project, Dev-C++ asks the user where the files must be stored. It is convenient to use
different folders for each project, since by default, the source code is named main.c and previous files can
be overwritten.

Project type determines the type of application that will be developed. In this lecture, we will create
Console projects. These are projects that run in a text-mode screen without windows or graphics. User

PROGRAMMING FUNDAMENTALS
interaction is performed by typing information on the keyboard (input) and printing characters on the
screen (output) with proper read and write instructions.

Steps

a. Start Dev-C++

Start the IDE from the Program folder Dev-C++.

Figure 1. Running Dev-C++ in the computer lab

b. Create a project

Before creating the source code file, it is necessary to create a project (File > New > Project).

Figure 2. Project creation parameters


PROGRAMMING FUNDAMENTALS
Options:

Console application

Name (name of the project)

C Project (for C language)

Select the folder to store the files in the next window. It is convenient to store each project in a different
folder

Figure 3. Saving project in a specific folder

After indicating the folder where the project configuration file (.dev) will be saved, the IDE generates a
basic source code file (by default, main.c). These files are not saved in the project folder until the
programmer saves or compiles the program (see below).

NOTE: The statement system(“PAUSE”); is automatically included to pause the execution of the program
before closing the terminal window in order to make it possible to see the output of the program.

Figure 4. Dev-C++ launches after project creation

PROGRAMMING FUNDAMENTALS
The IDE window includes three sub-windows: the Project Files Explorer, the Result Tabs, and the Source
Code Editor. These windows can be resized and minimized.

The Files Explorer window shows the name of the project and the included files. The Project tab usually
contains a single file with the source code of the program. In this pane, we can find two additional tabs:
Classes and Debug. Classes tab shows the functions of the program. Debug tab shows watched variables
in the debugging process.

The Results window is used to present the results of the actions of the IDE: compilation errors, compiling
directives, debugging commands, etc.

The Source code editor shows the code of the program.

c. Files created

The files of the project are saved when the source code file is saved. The remaining files of the

project are saved when the application is compiled and stored in the project folder.

File Extension Description

Project file .dev Project configuration data

.win

.c

.o

.exe

Makefile Required for the compilation process.


Manages

program dependencies and includes


instructions for the linker

Source code file Source code

Object file Object code resulting from the compilation


of the

source code. Each .c has a corresponding .o


after the compilation

Executable file Executable application

PROGRAMMING FUNDAMENTALS
Writing source code

Once the project has been created, we can start writing our C program.

It is recommended to use the classic color configuration of the editor (Tools > Editor options > Syntax >
Color Speed Settings > Classic) and to activate the support for opening and closing brackets (Tools >
Editor options > General > Highlight matching braces / parenthesis).

The editor highlights with different colors keywords and other elements of the C language. The classic
scheme uses:

Light blue for comments Green for included libraries Red for text strings

Bold black for C keywords

For instance, the HelloWorld program is shown as follows

Figure 5. The HelloWorld program

Compilation and link

To run a program, the source code must be compiled and linked. Dev-C++ performs the complete process
by clicking the Compile button (or Ctrl + F9).

While the compilation and link process is being performed, the IDE shows a dialog with related

information. If the process is successful, the window shows the message Done.

PROGRAMMING FUNDAMENTALS
Figure 6. Compilation window (success)

The Compile Log tab shows information about the process

Figure 7. Compilation process output

After the process, we can check that the files described in the previous table have been created.

Fixing compilation errors

Compilation errors are errors that are detected by the compiler. They are also named design- time errors.
To correct compilation errors, it is recommended to solve the first one and then to re-compile the program
again, since next errors are frequently wrong sections of the code that the compiler cannot interpret as a
result of the first error.

PROGRAMMING FUNDAMENTALS
Dev-C++ underlines in red the line of code where the compilation error has been detected. The Compile
tab of the Results window provides a detailed description of the error. The Compile

Log shows the error message issued by the compiler program.

Figure 8. Compilation errors

Common errors are: selecting a wrong project type (instead of Console), selecting a wrong language type
(instead of C), or library inclusion errors (wrong syntax, library missing, etc.).

Running the program

As a result of the link process, an executable program is created. To run this program, we have to click
the Run button (Ctrl + F10). Alternatively, we can find the executable program (.exe) in the project folder
and double-click on it.

NOTE: It is possible to compile and run the program in a single step by clicking the Compile & Run
button (F9).

Fixing execution errors

Developing a syntactically-correct program does not implies that it performs the required procedures.
Complex programs are error-prone and usually the logic implemented in the source code does not lead to
the expected behavior. These errors are named execution or

runtime errors, since they are detected when the program is running. Therefore, it may be necessary to
change the source code and repeat the compilation and link procedure.

The IDE includes a debugger, which is a supporting tool to find runtime errors. To use the debugger, it is
necessary to modify the compiler options to include debugging information in the object and the
executable files (Tools > Compiler Options > Compiler). This is done by adding the –g parameter to the
calls to the compiler and the linker.
PROGRAMMING FUNDAMENTALS
Figure 9. Compiler options for activating the debugger

When the program is compiled and link with these options, we can run the program in debug mode by
clicking on the Debug button (F8). This mode allows running the program step by step (instructions are
executed one-by-one), stopping the execution at breakpoints, or watch the value of a variable at any time
of the execution.

Breakpoints

To create a breakpoint, we can (alternatively): (a) select the line of the code and type Ctrl+F5; (b) right-
click on the line and select Toggle Breakpoint; (c) click on the gray vertical bar on the left of the code.
The instruction will be highlighted in red.

Figure 10. Setting a breakpoint

PROGRAMMING FUNDAMENTALS
Figure 11. Pausing the program at a breakpoint

When the program runs in Debug mode (F8), the execution is paused at this line. From this point, the
execution can continue normally or step by step. The current instruction is highlighted in blue.

The Debug tab of the Results window shows the debugging commands of Dev-C++. As depicted in the
following picture, it is possible to continue the execution, run the program step by step, run to the cursor,
etc.

Figure 12. Debug mode options to run a program

NOTE: It is possible to start the execution of a program in Debug mode without defining any breakpoint
by using Run to Cursor.

Start over: create a new program

create a new program, we have to repeat the steps 2.1-2.6 and create a new project, or alternatively,
replace the previous source code with the new code. We cannot have two files with a main function in the
same project. Therefore, it is convenient to create a different project for each program

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

What are the different features of Dev C++ IDE environment?

Task-2

Write a source code of the program that prints “Welcome to NFC”?

PROGRAMMING FUNDAMENTALS
LAB-2

UNDERSTADNING OF C EXPRESSION

OBJECTIVE
Study the use of variable and expressions in C along with escape sequences

THEORY
In order to write program in any programming language, it is necessary to understand the basic
structure of the program, its command and syntax.

Major Parts of C program

Operators Use
main() This marks the point where the C programs begins execution. Required for all
programs.
() Must appear immediately after main. Information that will be used by the program is
usually contained within that braces.
// These symbols are optional and used to indicate the comments.
; Each C statement is terminating with the semicolon.
{} The braces are required in all C programs. They indicate the beginning and the end of
the program instruction.

Printf() Function

The printf () function is output function. The printf () function is used to display the messages and
variables on the screen.

Example:

//Write a code to display “Welcome to C language”


#include<stdio.h>
main()
{
printf(“Welcome to C language”);
getche();
}
OUTPUT
Welcome to C language

Escape Sequences

When encountering a backslash in a string, the compiler looks ahead at the next character and
combines it with the backslash to form an escape sequence. The escape sequence \n means newline.
When a newline appears in the string output by a printf, the newline causes the cursor to position to
the beginning of the next line on the screen. Some common escape sequences are listed as,

PROGRAMMING FUNDAMENTALS
Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line.

\t Horizontal tab. Move the cursor to the next tab stop.

\a Alert. Produces a sound or visible alert without changing the current


cursor position.

\\ Backslash. Insert a backslash character in a string.

\” Double quote. Insert a double-quote character in a string.

Variables

A variable is a named location that can hold various values. All variables must be declare before they
can be used. A variable’s declaration serves one important purpose that it tells the C compiler that you
are giving an identity to the variable.

Data Types

char : It is eight bit long and it is commonly used to hold a single character.

Int : Integer may hold singed whole numbers (Numbers with no fractional part). It may hold values in
the range of –32768 to 32767.

Float and double: Data type float and double hold signed floating point values, which may have
fractional component. The difference between float and double is that double provides twice the
precision as does float.

Format Specifiers

The format specifiers in printf () determine the interpretation of a variable’s type, the width of the
field, the number of decimal places printed, and the justification. The following are few format
specifiers for printf ():

%c single character
%d signed decimal integer
%f floating point (decimal notation)

Example:
Void main()
{
int num=10;
char ch=’A’;
float fnum=89.34;
printf(“The integer type variable has value %d”,num);
printf(“The character type variable has value %c”,ch);
printf(“The float type variable has value %f”,fnum”);
}

PROGRAMMING FUNDAMENTALS
Operator

Operators are the symbols that cause a program to do something on the variables.
Following are the operators, which are commonly used, in C language.

Arithmetic operators

There are five arithmetic operators in C. they are

Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% remainder after integer division

The % operator some times to referred as modulus operator.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to display “Welcome to NFC” along with commas.

Task-2

Write a program to display the following

Hello
World

Task-3

Write a program to display the following names as shown

Saleem Kaleem

Task-4

Write a program to perform subtraction of two numbers.

Task-5

Write a program to perform division of two numbers.

Task-6

Write a program to find the average of 5 numbers.

PROGRAMMING FUNDAMENTALS
LAB-3

UNDERSTANDING OF INPUT/OUTPUT COMMAND

OBJECTIVE
Study the use of scanf command along with input and output formats.

THEORY

Scanf command

scanf (the “f” stands for “formatted”) to obtain a value from the user. The function
reads from the standard input, which is usually the keyboard.

Example:

//Write a code to add two integers


#include<stdio.h>
int main(void)
{
int integer1;
int integer2;
printf(“Enter first integer\n”);
scanf(“%d”,&integer1);
printf(“Enter second integer\n”);
scanf(“%d”,&integer2);
int sum;
sum= integer1+integer2;
printf( "Sum is %d\n", sum );
}
OUTPUT
Enter first integer
45
Enter second integer
72
Sum is 117

Operator

Operators are the symbols that cause a program to do something on the variables.
Following are the operators, which are commonly used, in C language.

PROGRAMMING FUNDAMENTALS
Arithmetics in C

Most C programs perform calculations using the C arithmetic operators.

C Operation Arithmetic Operator Algebraic Expression C Expression


Addition + f+7 f+7
Subtraction - p–c p-c
Multiplication * bm b*m
Division / x / y or or x ÷ y x/y
Remainder % r mod s r%s

Rules of Operator Precedence

C applies the operators in arithmetic expressions in a precise sequence determined by the


following rules of operator precedence, which are generally the same as those in algebra:

1. Operators in expressions contained within pairs of parentheses are evaluated first.


Parentheses are said to be at the “highest level of precedence.” In cases of nested,
or embedded, parentheses, such as the operators in the innermost pair of parentheses are applied first.

2. Multiplication, division and remainder operations are applied next. If an expression contains
several multiplication, division and remainder operations, evaluation proceeds from left to right.
Multiplication, division and remainder are said to be on the same level of precedence.

3. Addition and subtraction operations are evaluated next. If an expression contains


several addition and subtraction operations, evaluation proceeds from left to right.
Addition and subtraction also have the same level of precedence, which is lower
than the precedence of the multiplication, division and remainder operations.

4. The assignment operator (=) is evaluated last.

The rules of operator precedence specify the order C uses to evaluate expressions.

Specifying Precisions for Integers, Floating-Point Numbers and Strings

Function printf also enables you to specify the precision with which data is printed. Precision has
different meanings for different data types. When used with integer conversion specifiers, precision
indicates the minimum number of digits to be printed. If the printed value contains fewer digits than the
specified precision and the precision value has a leading zero or decimal point, zeros are prefixed to the
printed value until the total number of digits is equivalent to the precision. If neither a zero nor a decimal
point is present in the precision value, spaces are inserted instead. The default precision for integers is 1.
When used with floating-point conversion specifiers e, E and f, the precision is the number of digits to
appear after the decimal point. When used with conversion specifiers g and G, the precision is the
maximum number of significant digits to be printed. When used with conversion specifier s, the precision
is the maximum number of characters to be written from the beginning
of the string.

To use precision, place a decimal point (.), followed by an integer representing the
precision between the percent sign and the conversion specifier.
PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to display temperature in centigrade and convert it into Fahrenheit using scanf
command?

Task-2

Write a program to calculate speed using scanf command?

Task-3

Write a program that inputs age in years and display it in months and days?

Task-4

Write a program to find the average of 4 numbers using scanf command?

Task-5

Write a program to perform multiplication of two numbers using scanf command?

Task-6

Write a program to find the division of two numbers using scanf command. Use proper data format that
gives exact answers. For example 6/3=2, while 6/4 = 1.5 and so on?

PROGRAMMING FUNDAMENTALS
LAB-4

UNDERSTANDING OF CONDITIONAL STATEMENTS

OBJECTIVE
To study the use of conditional statements;

 If
 If else
 Nested if else

THEORY

The if Selection Statement

Selection statements are used to choose among alternative courses of action. For example,
suppose the passing grade on an exam is 60. The pseudocode statement

If student’s grade is greater than or equal to 60


Print “Passed”

determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the
condition is true, then “Passed” is printed, and the next pseudocode statement in order is “performed”
(remember that pseudocode isn’t a real programming language). If the condition is false, the printing is
ignored, and the next pseudocode statement in order is performed.

The preceding pseudocode If statement may be written in C as

if ( grade >= 60 ) {
puts( "Passed" );
} // end if

Notice that the C code corresponds closely to the pseudocode (of course you’ll also need to declare the int
variable grade). This is one of the properties of pseudocode that makes it such a useful program-
development tool. The second line of this selection statement is indented. Such indentation is optional,
but it’s highly recommended, as it helps emphasize the inherent structure of structured programs. The C
compiler ignores white-space characters such as blanks, tabs and newlines used for indentation and
vertical spacing.

PROGRAMMING FUNDAMENTALS
The flowchart illustrates the single-selection if statement. This flowchart contains what is perhaps the
most important flowcharting symbol—the diamond symbol, also called the decision symbol, which
indicates that a decision is to be made. The decision symbol contains an expression, such as a condition,
that can be either true or false. The decision symbol has two flowlines emerging from it. One indicates the
direction to take when the expression in the symbol is true and the other the direction to take when the
expression is false. Decisions can be based on conditions containing relational or equality

operators. In fact, a decision can be based on any expression—if the expression evaluates to zero, it’s
treated as false, and if it evaluates to nonzero, it’s treated as true.

The if…else Selection Statement

The if selection statement performs an indicated action only when the condition is true; otherwise the
action is skipped. The if…else selection statement allows you to specify that different actions are to be
performed when the condition is true and when it’s false. For example, the pseudocode statement

If student’s grade is greater than or equal to 60


Print “Passed”
else
Print “Failed”

prints Passed if the student’s grade is greater than or equal to 60 and Failed if the student’s grade is less
than 60. In either case, after printing occurs, the next pseudocode statement in sequence is “performed.”
The body of the else is also indented.

The preceding pseudocode If…else statement may be written in C as

if ( grade >= 60 ) {
puts( "Passed" );
} // end if
else {
puts( "Failed" );
} // end else

PROGRAMMING FUNDAMENTALS
The flowchart illustrates the flow of control in the if…else statement. Once again, besides small circles
and arrows, the only symbols in the flowchart are rectangles (for actions) and a diamond (for a decision).

Example

// A program for finding the smallest number


void main(void)
{
int a=2, b=3,small;
if(a<b)
small=a;
else
small=b;
printf(“%d”,small);
}

Nested if...else Statements

Nested if…else statements test for multiple cases by placing if…else statements inside
if…else statements. For example, the following pseudocode statement will print A for
exam grades greater than or equal to 90, B for grades greater than or equal to 80 (but less
than 90), C for grades greater than or equal to 70 (but less than 80), D for grades greater
than or equal to 60 (but less than 70), and F for all other grades.

This pseudocode may be written in C as

if ( grade >= 90 ) {
puts( "A" );
} // end if
else {
if ( grade >= 80 ) {
puts( "B" );
} // end if
else {
if ( grade >= 70 ) {
puts( "C" );

PROGRAMMING FUNDAMENTALS
} // end if
else {
if ( grade >= 60 ) {
puts( "D" );
} // end if
else {
puts( "F" );
} // end else
} // end else
} // end else
} // end else

If the variable grade is greater than or equal to 90, all four conditions will be true, but only
the puts statement after the first test will be executed. After that puts is executed, the else part of the
“outer” if…else statement is skipped.

You may prefer to write the preceding if statement as

if ( grade >= 90 ) {
puts( "A" );
} // end if
else if ( grade >= 80 ) {
puts( "B" );
} // end else if
else if ( grade >= 70 ) {
puts( "C" );
} // end else if
else if ( grade >= 60 ) {
puts( "D" );
} // end else if
else {
puts( "F" );
} // end else

As far as the C compiler is concerned, both forms are equivalent. The latter form is popular because it
avoids the deep indentation of the code to the right. Such indentation often leaves little room on a line,
forcing lines to be split and decreasing program readability.

The if selection statement expects only one statement in its body—if you have only one statement in the
if’s body, you do not need to enclose it in braces. To include several statements in the body of an if, you
must enclose the set of statements in braces ({ and }). A set of statements contained within a pair of
braces is called a compound statement or a block.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program that takes the input number from the user and identify whether
the number is “even” or “odd” using conditional statements.

Task-2

Write a program that inputs three integers, then display largest number with
proper statement and if user enters the same numbers, it should display that the
numbers are equal. The program should be completed by using conditional
statements only.

Task-3

If the user inputs the ages of Ali, Aslam and Aqeel, write a program to determine the
youngest of the three using conditional statements.

Task-4

Write a program that inputs single character and three integers and then do the following,

 If user enters “s”, then perform addition of the three integers


 If user enters “p”, then perform multiplication of the three integers
 If user enters “a”, then perform average of the three integers

And if user enters any other character, it should display “Wrong Statement”

PROGRAMMING FUNDAMENTALS
LAB-5

WHILE AND DO-WHILE LOOP

OBJECTIVE

To study the use of while, do-while and switch statement.

THEORY

The while loop

What happens if you don’t know how many times you want to do some thing, in this case the while lop is
used.

The structure of the while loop is

While( expression )
statement;

The statement may be a single statement or compound statement (enclosed in the braces {} ). The
statement is executed zero or more times until the expression becomes FALSE. In the operation of while
loop the expression is first evaluated, if this evaluation is FALSE (0), Then statement is never executed.
And control passed from the while statement to the rest of the program. If the evaluation is TRUE (non
zero), then statement is executed and the process is repeated again.

Example

// A program for to display first 10 natural numbers


void main()
{
int a=1;
while(a<=10)
{
printf(“%d\t”,a);
a++;
}
PROGRAMMING FUNDAMENTALS
}
Output
1 2 3 4 5 6 7 8 9 10

The do-while loop

The do-while loop is similar to the while loop, the difference being that the test condition is evaluated
after the loop is executed, recall that the while loop tests the condition before the loop is executed.

The structure of the do-while loop is

do
Statement;
while(expression);

Where statement may be a single or a compound statement, statement is executed one or more times until
expression becomes FALSE ( a value of 0), if the expression becomes FALSE, the do statement
terminates, and control passes to the next statement in the program. Otherwise if the expression is TRUE,
statement is repeated, and the process stars over again. The main difference between while and do-while
loop is that do-while loop is execute at least once, even the expression is FALSE.

Example

// A program for to display first 10 natural numbers


void main()
{
int a=1;
do
{
printf(“%d\t”,a);
a++;
}
while(a<=10);
}

PROGRAMMING FUNDAMENTALS
Output
1 2 3 4 5 6 7 8 9 10

The switch statement

The switch statement causes a particular group of statements to be chosen from several available groups.
The selection is based upon the current value of an expression, which is included within the switch
statement.

The general form of the switch statement is

Switch ( expression )
{
case 1: statements;
case 2: statements;
default:
}

Where expression results in an integer value. Note that expression may also be of type char, since
individual characters have equivalent integer values. The embedded statement is generally a compound
statement that specifies alternate courses of action. Each alternative is expressed as a group of one or
more individual statement within the overall embedded statement. For each alternative, the first statement
within the group must be preceded by one or more case labels the case label identify the different group
of the statement (i.e. the different alternatives) and distinguish them from one another. A flowchart of
switch statement is given below,

PROGRAMMING FUNDAMENTALS
Example

void main(void )
{
float num1=1.0, num2=1.0;
char op;
while(!(num1==0.0 && num2==0.0))
{
printf(“Type number, operator, number\n”);
scanf|(“%f %c %f”,&num1, &op, &num2);
switch (op)
{
case ‘+’:
printf(“ = %f”, num1 + num2);
break;
case ‘-’:
printf(“ = %f”, num1 - num2);
break;
case ‘*’:
printf(“ = %f”, num1 * num2);
break;
case ‘/’:
printf(“ = %f”, num1 / num2);
break;
default:
printf(“unknown operator”);
}
printf(“\n\n”);
}
}
Note that each of the groups is end with the break statement. The break statement causes control to be
transferred out of the switch statement, thus preventing more than one group of statement from being
executed. One of the labeled groups of the statement within the switch statement may be labeled default.
This group will be selected if none of the case labels matches the value of the expression.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to find the leap year using while loop. Perform this process until
user enters -1.

Task-2

Write a program that inputs any integer and find its factorial using while loop.

Task-3

Write a program that input result status if the class, count no. of pass and fail
students and then display “Bonus to instructor” if no. of pass students > 8. Consider
the number of total students is 10 in the class.

Task-4

Write a program that inputs grade of the student. Find the average of the class and
display it. If no data is entered, it should display “no data were entered”. The
condition for no data is (grade=-1)

Task-5

Write a program that inputs any integer and find the factorial from 1 to the input
number. If the user enters a number less than 0, the output displays “factorial not
possible” using do while loop.

Task-6

Write a program that inputs any integer and display the table using do while loop.

Task-7

Write a program to find the sum of first 50 odd numbers using do while loop.

PROGRAMMING FUNDAMENTALS
LAB-6

FOR LOOP
OBJECTIVE
To study the use of for loop.

THEORY
The for loop

The for loop executes the section of a code a fixed number of times. It’s usually used when you know,
before entering the loop, how many times you want to execute the code.

The for loop contains four major parts

1. The value at which the loop start (initial expression).


2. The condition at which the loop is to continue (conditional expression).
3. The changes that are to take place for each loop (increment expression).
4. The loop instructions.

These parts are put together in the for loop as

for( initial-expression, conditional-expression, increment-expression)


loop instructions;

The initial expression is executed only once, when the loops first starts. The test expression usually
involves a logical operator. It is evaluated each time through the loop, just before the body of the loop
executed. The increment expression changes the value of the loop variable, it always executed at the end
of the loop after the loop body has been executed.

You can execute more than one statements in the body of the loop, by placing the statements in the
brackets.
PROGRAMMING FUNDAMENTALS
Example:

// A program for to display first 10 natural numbers


void main()
{
int a;
for(a=1;a<=10;a++)
{
printf(“%d\t”,a);
}getche();
}
Output
1 2 3 4 5 6 7 8 9 10

Some Useful Points

1. The initialization, loop-continuation condition and increment can contain arithmetic expressions. For
example, if x = 2 and y = 10, the statement

for (j = x; j <= 4 * x * y; j += y / x)

is equivalent to the statement

for (j = 2; j <= 80; j += 5)

2. The “increment” may be negative (in which case it’s really a decrement and the loop actually counts
downward).

3. If the loop-continuation condition is initially false, the loop body does not execute. Instead, execution
proceeds with the statement following the for statement.

4. The control variable is frequently printed or used in calculations in the body of a loop, but it need not
be. It’s common to use the control variable for controlling iteration while never mentioning it in the body
of the loop.

5. The for statement is flowcharted and is much likely like the while statement. A simple statement flow
chart is given below for the “for” statement

Statement:

for (unsigned int counter = 1; counter <= 10; ++counter) {


printf("%u", counter);
}

PROGRAMMING FUNDAMENTALS
This flowchart makes it clear that the initialization occurs only once and that incrementing occurs after
the body statement each time it’s performed.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program that prints table of any integer using for loop.

Task-2

Write a program to find the sum of first 50 odd numbers using for loop.

Task-3

Write a program to print the following output using for loop,

1
23
456
7 8 9 10
Task-4

Write a program to print the following series up to 7th term

+ + + ….

Where ! is the representation of the factorial calculation.

Task-5

Write a program to display the following output using for loop,

1 1 2 4 3 9 4 16……..10 100.

PROGRAMMING FUNDAMENTALS
LAB-7

BASICS OF FUNCTION

OBJECTIVE
To familiarize with the basics of functions in C.

THEORY

A function is a self-contained program that carries out some specific, well-defined task. Every C program
consists of one or more functions, one of these functions must be called main. Execution of the program
will always begin by carrying out the instruction in main. Additional functions will be subordinate to
main, and perhaps to one and other.

A function will carry out its intended action whenever it is accessed (i.e. whenever the function is
“called”) from some other portion of the program. The same function can be accessed from several
different places within a program. Once the function has carried its intended action, control will be
returned to the point from which the function was accessed.

Generally function will process information that is passed to it from the calling portion of the program,
and return a single value. Information is passed to the function via a special identifier called arguments
(also called parameters). And return via the return statement.

Defining a function

To define a function in the program, it requires three type of the information.


1. Function declaration.
2. Function call.
3. Function definition

Function Declaration:

Just as you cannot use a variable without first telling the compiler what it is, you also can not use a
function without telling the compiler about it. Functions are declared by specifying the name of the
function, no of the arguments and return type of the function.

e.g. return type name_of_function(type1 arg1,type2 arg2, …. ,typen argn);

The most common approach is to declare the function at the beginning of the program.

Function Call:

The function can be accessed (i.e. called) by specifying its name, followed by a list of arguments enclosed
in parenthesis and separated by commas. If function call does not require any arguments, an empty pair of
braces must follow the name of the function. The function call may be part of a simple expression (such
PROGRAMMING FUNDAMENTALS
as assignment statement), or it may be one of the operands within a more complex expression. The
arguments appearing in the function call are referred to as actual arguments, in contrast to the formal
arguments that appear in the first line of the function definition.

Function Definition:

The definition consists of a line called the decelerator, followed by the function body. The function body
is composed of the statements that make up the function, delimited by braces.

Example

int add(int a, int b); //function declaration


void main(void)
{
int sum;
sum = add(2,2); // function call
printf(“%d”,sum);
getch();
}

int add(int a, int b) // function definition


{
return(a+b);
}

If you place the function definition before the main function, then there is no need of declaring the
function. Function sum can be rewritten as

int add(int a, int b) // function definition


{
return(a+b);
}
void main(void)
{
int sum,a=3,b=4;
sum=add(2,2); // function call
printf(“%d”,sum); // function call
getch();
}

Creating user define Header files

User can create his own header files, by putting the user defined function in those header files. The header
files that comes with the C compiler are placed in the include folder of the C compiler. So the header files
created by the user should be placed in the include folder.

PROGRAMMING FUNDAMENTALS
Example

int add(int a, int b)


{
return(a+b);
}

int sub(int a,int b)


{
return(a-b);
}

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to display “NFC-IEFR” using functions.

Task-2

Write a program to for calling function 5 times using loops.

Task-3

Write a program to find the multiplication table using function. The user should
input the table number.

Task-4

Write a program to read/input the factorial (!) of a number using function.

Task-5

By developing a function, write a program to input an integer and identify if the


number is odd or even.

PROGRAMMING FUNDAMENTALS
LAB-8

FUNCTIONS-A DEEPER LOOK


OBJECTIVE
To study different techniques using functions in C.

THEORY
An important C feature is the function prototype, which was borrowed from C++. The compiler uses
function prototypes to validate function calls. Pre-standard C did not perform this kind of checking, so it
was possible to call functions improperly without the compiler detecting the errors. Such calls could result
in fatal execution-time errors or nonfatal errors that caused subtle, difficult-to-detect problems. Function
prototypes correct this deficiency.

Header

Each standard library has a corresponding header containing the function prototypes for
all the functions in that library and definitions of various data types and constants needed
by those functions.

Square Function

Consider a program that uses a function square to calculate and print the squares of the integers from 1 to
10.

#include<math.h>
int square( int y ); /* function prototype */
int main()
{int x; /* counter */
PROGRAMMING FUNDAMENTALS
for ( x = 1; x <= 10; x++ ) {
printf( "%d ", square( x ) ); /* function call */
} /* end for */
printf( "\n" );
return 0; /* indicates successful termination */
} /* end main */
int square( int y ) /* y is a copy of argument to function */
{
return y * y; /* returns square of y as an int */
} /* end function square */

Maxinmum Function

#include <stdio.h>
int maximum( int x, int y, int z ); /* function prototype */
int main()
{
int number1; /* first integer */
int number2; /* second integer */
int number3; /* third integer */
printf( "Enter three integers: " );
scanf( "%d%d%d", &number1, &number2, &number3 );
printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );
return 0; /* indicates successful termination */
} /* end main */
int maximum( int x, int y, int z )
{
int max = x; /* assume x is largest */
if ( y > max ) { /* if y is larger than max, assign y to max */
max = y;
} /* end if */
if ( z > max ) { /* if z is larger than max, assign z to max */
max = z;
} /* end if */
return max; /* max is largest value */
}

Recursion
For some types of problems, it’s useful to have functions call themselves. A recursive function is one
that calls itself either directly or indirectly through another function. Recursion is a complex topic
discussed at length in upper-level computer science courses. In this section and the next, we present
simple examples of recursion.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Develop a function that receives marks obtained by a student in three subjects and return average and
percentage of the marks called from the main function. The final output should print the result of the
student.

Task-2

Write a function that returns the smallest of three floating point numbers.

Task-3

Write a function that takes an integer values and returns the numbers with its digits reversed. For
example, given the number 7631, the function should return 1367. Make a generalized program.

Task-4

Write a function that returns the square of an integer.

Task-5

Write a function to display this series (1,4,9,16,25,…) and so on, where number of terms is given by the
user.

PROGRAMMING FUNDAMENTALS
LAB-9

ARRAYS IN C

OBJECTIVE
To study the basics of arrays in C.

THEORY

Array

An array is a collection of variables of same data type, placed contiguously in memory. Like other
variable the array needs to be defines, so the computer will know what kind of array, and how large an
array, we want. We can declare array as int temp[7];

Here int specifies the type of variable, just as it does with simple variable, and the word temp is the name
of the array variable. The subscript [7], tells how many variable of type int will be in array.

Figure is a schematic representation of what the array looks like.

0 1 2 3 4 5 6

temp

Initializing Arrays

We can directly initialize the array as

int temp[7]={35,38,46,42,39,44,45};

Some Basic Array Operations

Defining an Array and Using a Loop to Set the Array’s Element Values:

#include <stdio.h>
int main(void)
{
int n[5]; // n is an array of five integers
for (size_t i = 0; i < 5; ++i) {
n[i] = 0;
}
printf("%s%13s\n", "Element", "Value");
for (size_t i = 0; i < 5; ++i) {
PROGRAMMING FUNDAMENTALS
printf("%7u%13d\n", i, n[i]);
}
}

Summing the Elements of an Array

#include<stdio.h>

int main() {
int i, arr[50], sum, num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Reading values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);

//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];

//Printing of all elements of array


for (i = 0; i < num; i++)
printf("\na[%d]=%d", i, arr[i]);

//Printing of total
printf("\nSum=%d", sum);

return (0);
}

Comparing the Elements of an Array

#include<stdio.h>

int main()
{
int a[50],i,n,large,small;
printf("How many elements:");
scanf("%d",&n);
printf("Enter the Array:");

for(i=0;i<n;++i)
scanf("%d",&a[i]);

large=small=a[0];
for(i=1;i<n;++i)
{
PROGRAMMING FUNDAMENTALS
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}

printf("The largest element is %d",large);


printf("\nThe smallest element is %d",small);

return 0;
}

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to find average of 5 numbers using arrays.

Task-2

Write a program to find largest number out of 10 numbers using arrays.

Task-3

Write a program to find the smallest number out of 10 numbers using arrays.

Task-4

Write a program to initialize 5 elements of arrays to zero.

PROGRAMMING FUNDAMENTALS
LAB-10
MORE ON ARRAYS
(PASSING ARRAY TO FUNCTION AND SORTING
TECHNIQUES)
OBJECTIVE

To study various techniques to evaluate data by using arrays in C.

THEORY

Passing Arrays to Functions

To pass an array argument to a function, specify the array’s name without any brackets. For example, if
array hourlyTemperatures has been defined as

int hourlyTemperatures[HOURS_IN_A_DAY];

the function call

modifyArray(hourlyTemperatures, HOURS_IN_A_DAY)

passes array hourlyTemperatures and its size to function modifyArray. Recall that all arguments in C are
passed by value. C automatically passes arrays to functions by reference—the called functions can modify
the element values in the callers’ original arrays. The array’s name evaluates to the address of the array’s
first element. Because the starting address of the array is passed, the called function knows precisely
where the array is stored. Therefore, when the called function modifies array elements in its function
body, it’s modifying the actual elements of the array in their original memory locations.

Sorting Arrays

Sorting data (i.e., placing the data into ascending or descending order) is one of the most
important computing applications. A bank sorts all checks by account number so that it
can prepare individual bank statements at the end of each month. Telephone companies
sort their lists of accounts by last name and, within that, by first name to make it easy to
find phone numbers. Virtually every organization must sort some data, and in many cases
massive amounts of it. Sorting data is an intriguing problem which has attracted some of
the most intense research efforts in the field of computer science

The technique we use is called the bubble sort or the sinking sort because
the smaller values gradually “bubble” their way upward to the top of the array like air bubbles rising in
water, while the larger values sink to the bottom of the array. The technique is to make several passes
through the array. On each pass, successive pairs of elements (element 0 and element 1, then element 1
and element 2, etc.) are compared. If a pair is in increasing order (or if the values are identical), we leave
the values as they are. If a pair is in decreasing order, their values are swapped in the array.

PROGRAMMING FUNDAMENTALS
Example

// A program for to display first 10 natural numbers


#include<stdio.h>
int main() {
int a[50], n, i, j, temp = 0;
printf("Enter how many numbers you want:\n");
scanf("%d", &n);
printf("Enter the %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("\n\t\tThe given array is:\n");
for (i = 0; i < n; i++) {
printf("\n\t\t%d", a[i]);
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}

printf("\n\n\n\t\tThe sorted array using Buble sort is:\n");


for (i = 0; i < n; i++) {
printf("\n\t\t%d", a[i]);
}
return 0;
}

More than one Dimension

Arrays in C can have multiple indices. A common use of multidimensional arrays, which the C standard
refers to as multidimensional arrays, is to represent tables of values consisting of information arranged in
rows and columns. To identify a particular table element, we must specify two indices: The first (by
convention) identifies the element’s row and the second (by convention) identifies the element’s column.
Tables or arrays that require two indices to identify a particular element are called two-dimensional
arrays. Multidimensional arrays can have more than two indices.

The array contains three rows and four columns, so it’s said to be a 3-by-4 array. In general, an array with
m rows and n columns is called an m-by-n array.

PROGRAMMING FUNDAMENTALS
Every element in array a is identified in by an element name of the form a[i][j]; a is the name of the array,
and i and j are the indices that uniquely identify each element in a. The names of the elements in row 0 all
have a first index of 0; the names of the elements in column 3 all have a second index of 3

Example

#include<stdio.h>

int main() //The main function


{
int ar[2][3]={{9,7,5},{6,4,2}}; //declaring array ar
int i,j; //declaring variable i,j
printf("Matrix of 2x3 is given as \n\n"); //display message
for(i=0;i<=1;i++){ //for loop for accessing row
for(j=0;j<=2;j++){ //for loop for accessing coloumn
printf("%2d",ar[i][j]); //display result
}
printf("\n"); //enter new line
}
} //end of function main

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to initialize 5 elements of arrays with initializer list (random


numbers) in a list.

Task-2

Write a program that reads numbers from an array and graph the information in
the form of histogram. Each number will be printed, then bar consisting of asterisks
(*) will be printed according to the given number.

Task-3

An array A=[1 3 5 7 9 13 11 19 15 17] is given. Sort array A to print the array in


ascending order, i.e. [1 3 5 7 9 11 13 15 17 19].

Task-4

Generate a 2 x 2 matrix using arrays. Also generate a 2 x 3 matrix in a separate


program. The numbers inside a matrix can be random.

Task-5

Initialize an array containing 25 numbers. Write a program to find total number of


positive and negative numbers from the array.

PROGRAMMING FUNDAMENTALS
LAB-11

INTRODUCTION TO POINTERS

OBJECTIVE
To familiarize with the basic of pointers in C and its usage.

THEORY
A pointer provides the way of accessing a variables (or a more complex kind of data, such as an array)
without referring to the variable directly. The mechanism used for this is the address of the variable.

Uses of the Pointer variable

Some reasons to use the pointers are

1. To return more than one value from the function.


2. To pass array and function more conveniently from one function to another.
3. To manipulate the arrays more easily by moving the pointer to them.
4. To create complex data structure, such as linked lists and binary tress.

Pointer are declared in the same manner as we are declaring the simple variables, but the name of the
variable must be followed by the * sign.

e.g. int * a;

Example (1)

#include<iostream.h>
#include<conio.h>
void main(void)
{
int a=2, *b;
b=&a;
printf(“%u”,b); // displays the address of the variable a.
printf(“%d”,*b); // displays the value of the variable a .
}

Relationship between Pointers and Arrays

Arrays and pointers are intimately related in C and often may be used interchangeably. An
array name can be thought of as a constant pointer. Pointers can be used to do any operation
involving array indexing.Assume the following definitions:

PROGRAMMING FUNDAMENTALS
int b[5];
int *bPtr;

Because the array name b (without an index) is a pointer to the array’s first element, we
can set bPtr equal to the address of the array b’s first element with the statement

bPtr = b;

This statement is equivalent to taking the address of array b’s first element as follows:

bPtr = &b[0];

Pointer/Offset Notation

Array element b[3] can alternatively be referenced with the pointer expression

*(bPtr + 3)

The 3 in the expression is the offset to the pointer. When bPtr points to the array’s first element, the offset
indicates which array element to reference, and the offset value is identical to the array index. This
notation is referred to as pointer/offset notation. The parentheses are necessary because the precedence of
* is higher than the precedence of +. Without the parentheses, the above expression would add 3 to the
value of the expression *bPtr (i.e., 3 would be added to b[0], assuming bPtr points to the beginning of the
array). Just as the array element can be referenced with a pointer expression, the address

&b[3]

can be written with the pointer expression

bPtr + 3

The array itself can be treated as a pointer and used in pointer arithmetic. For example, the expression

*(b + 3)

also refers to the array element b[3]. In general, all indexed array expressions can be written with a
pointer and an offset. In this case, pointer/offset notation was used with the name of the array as a pointer.
The preceding statement does not modify the array name in any way; b still points to the first element in
the array.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Initialize the variable a=10 and demonstrate the use of * and & with respect to
pointers.

Task-2

Initialize three pointer variables and find the position (address) of the numbers
using pointers.

Task-3

Find the address of a number using pointers. The user should read/scan the
number from the keyboard.

Task-4

What is the output of the following code?


#include<stdio.h>
int main (void) {
int s1[3]={1,2,3};
int s2[4]={4,5,6,7};
int s3[2]={8,9}
int *sptr[3]={s1,s2,s3};
printf(“%d\n”,*(sptr[0]+2));
printf(“%d\n”,*(sptr[1]+2));
printf(“%d\n”,*(sptr[2]+1));
}

PROGRAMMING FUNDAMENTALS
LAB-12

POINTER OPERATIONS

OBJECTIVE

To study different operations using pointers.

THEORY
Pointers are among C’s most difficult capabilities to master. Pointers enable programs to accomplish
pass-by-reference, to pass functions between functions, and to create and manipulate dynamic data
structures—ones that can grow and shrink at execution time, such as linked lists, queues, stacks and trees.
This chapter explains basic pointer concepts.

Pointer Expressions and Pointer Arithmetic

Pointers are valid operands in arithmetic expressions, assignment expressions and comparison
expressions. However, not all the operators normally used in these expressions are
valid in conjunction with pointer variables. This section describes the operators that can
have pointers as operands, and how these operators are used.

Allowed Operators for Pointer Arithmetic

A pointer may be incremented (++) or decremented (--), an integer may be added to a pointer
(+ or +=), an integer may be subtracted from a pointer (- or -=) and one pointer may be
subtracted from another—this last operation is meaningful only when both pointers point
to elements of the same array.

Aiming a Pointer at an Array

Assume that array int v[5] has been defined and its first element is at location 3000 in
memory. Assume pointer vPtr has been initialized to point to v[0]—i.e., the value of
vPtr is 3000. Figure 7.18 illustrates this situation for a machine with 4-byte integers. Variable vPtr can be
initialized to point to array v with either of the statements.

vPtr = v;
vPtr = &v[0];

Adding an Integer to a Pointer

In conventional arithmetic, 3000 + 2 yields the value 3002. This is normally not the case
with pointer arithmetic. When an integer is added to or subtracted from a pointer, the
pointer is not incremented or decremented simply by that integer, but by that integer
times the size of the object to which the pointer refers. The number of bytes depends on
the object’s data type. For example, the statement
PROGRAMMING FUNDAMENTALS
vPtr += 2;

would produce 3008 (3000 + 2 * 4), assuming an integer is stored in 4 bytes of memory.
In the array v, vPtr would now point to v[2]

Subtracting an Integer from a Pointer

If vPtr had been incremented to 3016, which points to v[4], the statement

vPtr -= 4;

would set vPtr back to 3000—the beginning of the array.

Incrementing and Decrementing a Pointer

If a pointer is being incremented or decremented by one, the increment (++) and decrement (--) operators
can be used. Either of the statements

++vPtr;
vPtr++;

increments the pointer to point to the next location in the array. Either of the statements

--vPtr;
vPtr--;

decrements the pointer to point to the previous element of the array.

Assigning Pointers to One Another

A pointer can be assigned to another pointer if both have the same type. The exception to
this rule is the pointer to void (i.e., void *), which is a generic pointer that can represent
any pointer type. All pointer types can be assigned a pointer to void, and a pointer to void
can be assigned a pointer of any type (including another pointer to void). In both cases, a
cast operation is not required.

Comparing Pointers

Pointers can be compared using equality and relational operators, but such comparisons
are meaningless unless the pointers point to elements of the same array. Pointer comparisons compare the
addresses stored in the pointers. A comparison of two pointers pointing
to elements in the same array could show, for example, that one pointer points to a higher- numbered
element of the array than the other pointer does. A common use of pointer
comparison is determining whether a pointer is NULL.

Passing Arguments to Functions by Reference

In C, you use pointers and the indirection operator to accomplish pass-by-reference. When calling a
function with arguments that should be modified, the addresses of the arguments are passed. This is

PROGRAMMING FUNDAMENTALS
normally accomplished by applying the address operator (&) to the variable (in the caller) whose value
will be modified. Arrays are not passed using operator & because C automatically passes the starting
location in memory of the array (the name of an array is equivalent to &arrayName[0]). When the address
of a variable is passed to a function, the indirection operator (*) may be used in the function to modify the
value at that location in the caller’s memory.

PROGRAMMING FUNDAMENTALS
Example

// program for returning more than one value from the function
#include<iostream.h>
#include<conio.h>

void function(int *a, int *b)


{
*a=100;
*b=200;
}
void main(void )
{
int y,z;
function(&y,&z);
printf(“%d,%d”,y,z);
getch();
}

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program to find the sum of three numbers using pointers.

Task-2

Write a program to find multiplication of two numbers using pointers.

Task-3

Write a program two perform fundamental mathematical calculations (+,-,*,/) using


pointers. The program should read the two numbers from the user.

Task-4

Find the cube of a variable using function (Call by reference) with pointer
arguments.

PROGRAMMING FUNDAMENTALS
LAB-13

C-STURCUTRES II

OBJECTIVE

To study simple structures to develop the concept of structures in C.

THEORY

A structure is a data type whose format is defined by the programmer. A structure consists of a
number of data items which need not be of the same type grouped together e.g a structure could
consist of the employee’s name, department number and designation.

The use of structures could be described as

1. Declaring a structure type.


2. Defining structure variable.
3. Accessing member of structure.

Fundamental data types used in C such as ‘int’ and ‘float’ are predefined by the compiler, e.g
the ‘int’ variable will always consist of two bytes. However a structure may consist of any
number of elements of different types but the programmer must tell the compiler that a particular
structure is going to look like before using any variable of that type.

struct easy
{
int num;
char ch;
};

Here ‘struct’ is the keyword and ‘easy’ is the data type but not the variable name. Further ‘num’
and ‘ch’ are two members or elements of the data type “easy” and are of integer and character
type respectively.

After declaring the new data type, we can define one or more variables to be of that type.

struct easy ez1;

Here easy is the data type and ez1 is the variable name or structure name.

PROGRAMMING FUNDAMENTALS
Structure uses and approach called the “dot operator” which is also called the “membership
operator”.

ez1.num=2;

Here ‘ez1’ is the structure and ‘num’ is its member. The dot operator (.) connects a structure
variable name with a member of the structure.

Example

#include <stdio.h>
#define SIZE 25

struct bookrecord { // structure bookrecord definition


char title[SIZE]; //title element
char authorname[SIZE]; //authorname element
};

int main() //the function main


{
struct bookrecord B; //acessing stucture bookrecord
printf("\nEnter Book title : "); //display message
fgets(B.title, SIZE, stdin); //read input
printf("\nEnter Author name : "); //display message
fgets(B.authorname, SIZE, stdin); //read input
printf("\n\nBook title : %s",B.title); //display result
printf("\nBook author : %s",B.authorname); //display result
} //end of function main

How it is different from arrays?

It is different from arrays as it a group of data with different data types such as integer, float, double, char,
etc.

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Explain the difference between arrays, pointers and structures. What is the basic
procedure for defining the structure variable?

Task-2

Write a program using structure to store the data of a student that includes roll
number, name and marks of the student.

Task-3

Write a program using structures to enter the two distances (d1,d2) in meters and
calculate the sum of the total distance(D=d1+d2).

Task-4

Write a program using structures to define struct type variable books that stores
(title, author name, subject and book id) and print accordingly. You may need to use
<string.h> library if required.

PROGRAMMING FUNDAMENTALS
LAB-14

STRUCTURES II

OBJECTIVE
To practice some real world application problems using structures.

THEORY
Structures—sometimes referred to as aggregates in the C standard—are collections of related variables
under one name. Structures may contain variables of many different data types—in contrast to arrays,
which contain only elements of the same data type. Structures are commonly used to define records to be
stored in files.

Self-Referential Structures

A variable of a struct type cannot be declared in the definition of that same struct type.
A pointer to that struct type, however, may be included. For example, in struct
employee2:

struct employee2 {
char firstName[20];
char lastName[20];
unsigned int age;
char gender;
double hourlySalary;
struct employee2 teamLeader; // ERROR
struct employee2 *teamLeaderPtr; // pointer
};

the instance of itself (teamLeader) is an error. Because teamLeaderPtr is a pointer (to type
struct employee2), it’s permitted in the definition. A structure containing a member that’s
a pointer to the same structure type is referred to as a self-referential structure.

Operations That Can Be Performed on Structures

The only valid operations that may be performed on structures are:


• assigning struct variables to struct variables of the same type for a pointer member, this copies only the
address stored in the pointer.

• taking the address (&) of a struct variable.


• accessing the members of a struct variable.
• using the sizeof operator to determine the size of a struct variable.

PROGRAMMING FUNDAMENTALS
Using Structures with Functions
Structures may be passed to functions by

• passing individual structure members.


• passing an entire structure.
• passing a pointer to a structure.

When structures or individual structure members are passed to a function, they’re passed
by value. Therefore, the members of a caller’s structure cannot be modified by the called
function. To pass a structure by reference, pass the address of the structure variable. Arrays
of structures—like all other arrays—are automatically passed by reference.

Some Useful Applications

Student Record in an Institute

#include <stdio.h>
#define SIZE 25
struct student { // structure student definition
int rollnumber; //rollnumber element
char name[SIZE]; //name element
int marks; //marks element
};

int main() //the function main


{
struct student A; //acessing stucture student
printf("Enter student name: "); //display message
fgets(A.name, SIZE, stdin); //read input
printf("Enter student roll number : "); //display message
scanf("%d",&A.rollnumber); //read input
printf("Enter student marks : "); //display message
scanf("%d",&A.marks); //read input
printf("\nStudent name : %s",A.name); //display result
printf("Student roll number : %d",A.rollnumber); //display result
printf("\nStudent marks : %d",A.marks); //display result

} //end of function main

PROGRAMMING FUNDAMENTALS
Employee Record in an Organization

#include<stdio.h>
#define SIZE 60
struct Employee
{
int Id;
int Salary;
char Name[SIZE];
char Designation[SIZE];

};

int main()
{

struct Employee E1;


printf("\nEnter Employee Name : ");
int i=0;
while (i!=SIZE) {
E1.Name[i]=getche();
if(E1.Name[i]==13){
i=SIZE-1;
}
i=i+1;
}
printf("\nEnter Employee Designation : ");
fgets(E1.Designation, SIZE, stdin); //read input
printf("\nEnter Employee Id : ");
scanf("%d",&E1.Id);
printf("\nEnter Employee Salary : ");
scanf("%d",&E1.Salary);
printf("\n\nEmployee Id : %d",E1.Id);
printf("\n\nEmployee Name : %s",E1.Name);
printf("\nEmployee Designation : %s",E1.Designation);
printf("\nEmployee Salary : %d",E1.Salary);

PROGRAMMING FUNDAMENTALS
LAB ASSIGNMENT

Task-1

Write a program that manages book data in a small library. The data consists of title and author name.
The program must 1). Define a structure named bookrecord to store book data, 2) declare and initialize to
variables with bookrecord type

Task-2

Write a C program using structures that will allow the information about 20 employees to be stored in the
structure. The program prompts the user for appropriate information and then prints the stored
information and display the information that includes employee name, salary, id no and designation.

Task-3

Write a program using structures that initially stores name of the student, marks and roll number and then
display the stored information

Task-4

Write a program using structures that initially stores name of the student, roll number and marks in three
subjects along with total marks. The program should store and display the required output. Use required
header libraries if any.

PROGRAMMING FUNDAMENTALS

Das könnte Ihnen auch gefallen