74
Practical No 1.1 Aim: Study of Algorithm and Flowchart Theory: 1.1Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form the foundation of writing a program. For writing any programs, the following has to be known: Input Tasks to be preformed Output expected For any task, the instructions given to a friend is different from the instructions given to a computer. Let’s look at the difference between them and know how to give instructions to a computer. Instruction to a Friend: Step 1: Go to the College Board. Step 2: Search for my name on the board. Step 3: Check the rank against my name. Instructions to the Computer: Step 1: Go to the College Board. Step 2: Read the first name.

Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Embed Size (px)

Citation preview

Page 1: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 1.1Aim: Study of Algorithm and Flowchart

Theory:1.1 Algorithm

An algorithm is a procedure or step-by-step instruction for solving a problem. They form the

foundation of writing a program.

For writing any programs, the following has to be known:

Input

Tasks to be preformed

Output expected

For any task, the instructions given to a friend is different from the instructions given to a

computer. Let’s look at the difference between them and know how to give instructions to a

computer.

Instruction to a Friend:

Step 1: Go to the College Board.

Step 2: Search for my name on the board.

Step 3: Check the rank against my name.

Instructions to the Computer:

Step 1: Go to the College Board.

Step 2: Read the first name.

Step 3: If this is my name, see rank and come back.

Step 4: Read the next name.

Step 5: Repeat the above two steps until you find my name.

Breaking down the steps into smaller steps is called algorithm.

Page 2: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Example:

Considering the above example, let’s break down the task into steps:

Input – Name

Tasks to be preformed – Search for my name    

Output expected – My rank

It is a good practice to write down the algorithm first before attempting at writing a program.

Each step of the algorithm will get converted to a line or a set of lines in the programming

language.

Write Algorithm for Addition of Two Numbers

Step 1: Start

Step 2: Declaration of Variables num1,num2,sum

Step3: Read Values for num1 and num2

Step 4: sum<- num1+num2

Step 5: Display sum

Step 6: End

1.2 Flowchart

Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts

use simple geometric shapes to depict processes and arrows to show relationships and

process/data flow.

Every good programmer should be able to use them. Why? Because they are very powerful and

convenient. Once you have the complete algorithm on a chart it is just a matter of writing the

code in the language you want. And as we already explained writing the code is just one of the

steps in the software development process .

Page 3: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Flowchart SymbolsHere is a chart for some of the common symbols used in drawing flowchart

Symbol Symbol Name

Purpose

Start/StopUsed at the beginning and end of the algorithm to show start and end

of the program.

Process Indicates processes like mathematical operations.You will use a

rectangle to perform an action. It can be use for assignment

statements - when you change a value of a variable. An

action(rectangle) block may have one or several inputs and exactly

one output.

Input/

Output

Used for denoting program inputs and outputs. The parallelogram

flow chart symbol serves for input/output(I/O) to/from the program.

Output means that the program gives an output, for example –

display a message on the screen. Input is an input to the program. It

could be when the user enters a value for a variable

Decision Stands for decision statements in a program, where answer is usually

Yes or No.This is the only block that has more than one exit arrow.

Arrow Shows relationships between different shapes.

Page 4: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

On-page

Connector

Connects two or more parts of a flowchart, which are on the same

page.

Off-page

Connector

Connects two parts of a flowchart which are spread over different

pages.

Flowchart for addition Two Numbers

Conclusion: After successful completion of this experiment student will be able to write

Algorithm and Draw Flowchart for all Examples.

Page 5: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 1.2Aim: A Simple program to display a message “Hello world” on screen.

Theory:

1.1 Structure of C Program

Each instruction in a C program is written as a separate statement. The program starts with a

main function followed by the opening braces which indicates the start of the function then the

variable and constant declarations followed by the statements, which includes input and output

statements.

The basic structure of C program is as follow:

Links Section (File)

void main()

{

Variable declaration section

Function declaration section

executable statements;

}

Links Section (File):-

It is used to link the required system libraries or header files to execute a program.

Definition Section:-

It is used to define or set values to variables.

Global variable declaration Section:-

It is used to declare global or public variable.

Void main (): -

Used to start of actual C program. It includes two parts as declaration part and executable

Page 6: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

part.

Variable declaration section:-

Used to declare private variable.

Function declaration section:-

Used to declare functions of program from which we get required output. Then, executable

statements are placed for execution.

Function definition section:-

Used to define functions which are to be called from main ().

#include <stdio.h>

main ()

{

printf ("Hello, World! \n");

return 0;

}

1.2 Running C Programs

Developing a program in a compiled language such as C requires at least four steps:

1. Editing (or writing) the program

2. Compiling it

3. Linking it

4. Executing it

1.2.1 Editing Write a computer program with words and symbols that are understandable to human beings.

This is the editing part of the development cycle. As you type the program directly into a

window on the screen and save the resulting text as a separate file. This is often referred to as the

Page 7: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

source file (you can read it with the TYPE command in DOS or the cat command in unix). The

custom is that the text of a C program is stored in a file with the extension .c for C programming

language

1.2.2 Compiling

You cannot directly execute the source file. To run on any computer system, the source file must

be translated into binary numbers understandable to the computer's Central Processing Unit (for

example, the 80*87 microprocessor). This process produces an intermediate object file - with the

extension .obj, the .obj stands for Object.

1.2.3 Linking

The main reason is that many compiled languages come with library routines which can be

added to your program. Theses routines are written by the manufacturer of the compiler to

perform a variety of tasks, from input/output to complicated mathematical functions. In the case

of C the standard input and output functions are contained in a library (stdio.h) so even the most

basic program will require a library function. After linking the file extension is .exe which are

executable files.

1.2.4 Executable files

Thus the text editor produces .c source files, which go to the compiler, which produces .obj

object files, which go to the linker, which produces .exe executable file. You can then run .exe

files as you can other applications, simply by typing their names at the DOS prompt or run using

windows menu

A C program basically consists of the following parts −

Preprocessor Commands

Functions

Variables

Page 8: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Statements & Expressions

Comments

Example of “C” Program File:-

All the C programs are written into text files with extension ".c" for example samp.c.

Ex. /* Sample C program */

Print the message "Hello World" on the screen.

#include <stdio.h>

main()

{

printf("Hello World\n");

}

The first line is the standard start for all C programs - main (). After this comes the program's

only instruction enclosed in curly brackets {}. The curly brackets mark the start and end of the

list of instructions that make up the program - in this case just one instruction. Notice the

semicolon marking the end of the instruction.

You might as well get into the habit of ending every C instruction with a semicolon. Also notice

that the semicolon marks the end of an instruction - it isn't a separator as is the custom in other

languages.

why the curly brackets are on separate lines, it's just a layout convention to help you spot

matching brackets. C is very unfussy about the way you lay it out. For example, you could enter

the Hello World program as: main (){printf("Hello World\n");}

The printf function does what its name suggest it does: it prints, on the screen, whatever you tell

it to. The "\n" is a special symbol that forces a new line on the screen. Type it in and save it as

Hello.c. Then use the compiler to compile it, then the linker to link it and finally run it.

The output is as follows: Hello World

Conclusion: After successful completion of this experiment student will understand the structure

of C Program

Page 9: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No-2

Aim: A Program to take input from user and display value entered by user on screen

Theory:

3.1 Input and Output Function

C programming has several in-built library functions to perform input and output tasks.

Two commonly used functions for I/O (Input/Output) are printf() and scanf().

1. input functions, called scanf

2. output functions, called printf

The scanf() function reads formatted input from standard input (keyboard) whereas

the printf() function sends formatted output to the standard output (screen).

3.2 Data types

1. int - integer: a whole number.

2. float - floating point value: ie a number with a fractional part.

3. double - a double-precision floating point value.

4. char - a single character.

1) int variable

For example:

int a;

declares that you want to create an int variable called a.

To assign a value to our integer variable we would use the following C statement: a=10;

2) float

A float, or floating point, number has about seven digits of precision and a range of about 1.E-36

to 1.E+36. A float takes four bytes to store.

Page 10: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

3) double

A double, or double precision, number has about 13 digits of precision and a range of about 1.E-

303 to 1.E+303. A double takes eight bytes to store.

4) char c

To assign, or store, a character value in a char data type is easy - a character variable is just a

symbol enclosed by single quotes.

3.3 The % Format Specifiers

%c char single character

%d int signed integer

%f float or double signed decimal %s array of char sequence of characters

Example: #include <stdio.h> //This is needed to run printf() function.

int main()

{

printf("C Programming"); //displays the content inside quotation

return 0;

}

Output: C Programming

Example: Integer Data#include <stdio.h>

int main()

{

int a;

printf("enter value”);

Page 11: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

scanf(“%d”,&a);

printf(“Value is %d”,a);

return 0;}

Output: Enter value 5 Value is 5

Example: Float Data#include <stdio.h>

int main()

{

Float a;

printf("enter value”);

scanf(“%f”,&a);

printf(“Value is %f”,a);

return 0;

}

Output: Enter value 2.3 Value is 2.3

Example: Charcter Data#include <stdio.h>

int main()

{

Char a;

printf("enter value”);

scanf(“%c”,&a);

printf(“Value is %c”,a);

return 0;}

Output: Enter value 2.3 Value is 2.3

Conclusion: After successful completion of this experiment student will able to take input value and print it on screen

Page 12: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 3Aim: Basic example for performing different C Operations using operator. (With and without using scanf()).

Theory:

4.1 Operators in C

Operators are the foundation of any programming language. Thus the functionality of C

programming language is incomplete without the use of operators. We can define operators as

symbols that helps us to perform specific mathematical and logical computations on operands. In

other words we can say that an operator operates the operands.

For example, consider the below statement:

c = a + b;

Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition

operator tells the compiler to add both of the operands ‘a’ and ‘b’. C has many built-in operator

types and they can be classified as:

Arithmetic Operators:

These are the operators used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ Division

% remainder after division( modulo division)

Arithmetic operators are of two types:

Page 13: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

1. Unary Operators: Operators that operates or works with a single operand are unary operators. For example: (++ , –)

2. Binary Operators: Operators that operates or works with two operands are binary operators. For example: (+ , – , * , /)

Example : Program to demonstrate the working of arithmetic operators

#include <stdio.h>int main(){ int a = 9,b = 4, c; c = a+b; printf("a+b = %d \n",c); c = a-b; printf("a-b = %d \n",c); c = a*b; printf("a*b = %d \n",c); c=a/b; printf("a/b = %d \n",c); c=a%b; printf("Remainder when a divided by b = %d \n",c); return 0;}Outputa+b = 13a-b = 5a*b = 36a/b = 2Remainder when a divided by b=1

Relational Operators

Relational operators are used for comparison of the values of two operands. For example:

checking if one operand is equal to the other operand or not, an operand is greater than the other

operand or not etc. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Page 14: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0

Example: Program to demonstrate the working of Relational Operator

#include <stdio.h>

main() {

int a = 21; int b = 10; int c ;

if( a == b ) { printf("Line 1 - a is equal to b\n" ); } else { printf("Line 1 - a is not equal to b\n" ); }

if ( a < b ) { printf("Line 2 - a is less than b\n" ); } else { printf("Line 2 - a is not less than b\n" ); }

if ( a > b ) {

Page 15: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

printf("Line 3 - a is greater than b\n" ); } else { printf("Line 3 - a is not greater than b\n" ); }}

Output:Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b

Logical Operators  

Logical Operators are used to combine two or more conditions/constraints or to complement the

evaluation of the original condition in consideration. The result of the operation of a logical

operator is a Boolean value either true or false

An expression containing logical operator returns either 0 or 1 depending upon whether

expression results true or false. Logical operators are commonly used in decision making in C

programming.

Operator Meaning of Operator Example

&& Logial AND. True only if all operands are true 

If c = 5 and d = 2 then, expression ((c == 5) && (d > 5)) equals to 0.

|| Logical OR. True only if either one operand is true

If c = 5 and d = 2 then, expression ((c == 5) || (d > 5)) equals to 1.

! Logical NOT. True only if the operand is 0

If c = 5 then, expression ! (c == 5) equals to 0.

Example: Program to demonstrate the working of Logical Operator

#include <stdio.h>

main() {

int a = 5; int b = 20; int c ;

Page 16: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

if ( a && b ) { printf("Line 1 - Condition is true\n" ); }

if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 0; b = 10;

if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); }

if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); }

}Output: Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true

Bitwise Operators

The Bitwise operators is used to perform bit-level operations on the operands. The operators are

first converted to bit-level and then calculation is performed on the operands. The mathematical

operations such as addition , subtraction , multiplication etc. can be performed at bit-level for

faster processing

Bitwise operators are used in C programming to perform bit-level operations.

Page 17: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Operator Example Same as

= a = b a = b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example :Program to demonstrate the working of assignment operators

#include <stdio.h>int main(){ int a = 5, c; c = a;

Page 18: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

printf("c = %d \n", c);

c += a; // c = c+a printf("c = %d \n", c);

c -= a; // c = c-a printf("c = %d \n", c);

c *= a; // c = c*a printf("c = %d \n", c);

c /= a; // c = c/a printf("c = %d \n", c);

c %= a; // c = c%a printf("c = %d \n", c);

return 0;}Output:c = 5 c = 10 c = 5 c = 25 c = 5 c = 0

Conclusion: After successful completion of this experiment student will able to use different types of operators in C.

Practical No 4Aim: Study of Decision Control Structure (if-else, nested if-else)

Page 19: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Theory:

5.1 C if statement

The if statement allows you to control the execution of code based on a  particular condition. The syntax of the if statement is as follows:

if(expression){/* unit of code to be executed */}

The body of the if statement only executes if the expression evaluates to a non-zero value or true. If the expression evaluates to false, the statements inside the body of the if statement will be ignored.

The following flowchart illustrates the if statement:

The program asked users to enter a number. If the number is greater than zero, it displays a message showing that otherwise, it does nothing.

5.2 C if else statement

Page 20: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Sometimes you want to execute a piece of code in case of the expression in the if statement evaluates to false. You can use the second form of the if statement which is known as if else statement. The following illustrates the syntax of the if else statement:

if(expression){  /* code block of if statement */}else{  /* code block of else statement */}

This program asks users to enter a number. It displays the corresponding message based on the input value.

5.3 C else if statement

If you want to use more than one condition, you can use if else-if statement. The syntax of the if else ifstatement is as follows:

if(condition-1){ /* code block if condition-1 is true */}else if (condition-2){ /* code block if condition-2 is true */}else if (condition-3){ /* code block if condition-3 is true */}else{ /* code block all conditions above are false */}

The else-if statement is used to make multiway decisions. The conditions in the corresponding if and else if branch evaluates in sequence from top to bottom. If a condition evaluates to true, the statements associated with it executes and terminates the whole chain.

The following flowchart illustrates the if else statement:

Page 21: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

5.4 Program:

a. Write C program to find maximum and minimum number between two numbers given by user using if-else and conditional operator.

/** * C program to find maximum between two numbers */

#include <stdio.h>

intmain(){int num1, num2;

/* Input two numbers from user */printf("Enter two numbers: ");scanf("%d%d",&num1,&num2);

/* Compare num1 with num2 */if(num1 > num2){/* True part means num1 > num2 */printf("%d is maximum", num1);}

Page 22: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

else{/* False part means num1 < num2 */printf("%d is maximum", num2);}

return0;}

/** * C program to find maximum between two numbers using conditional operator */

#include <stdio.h>

intmain(){int num1, num2, max;

/* * Input two number from user */printf("Enter two numbers: ");scanf("%d%d",&num1,&num2);

/* * If num1 > num2 then * assign num1 to max * else * assign num2 to max */max=(num1 > num2)?num1 : num2;

printf("Maximum between %d and %d is %d", num1, num2, max);

return0;}

Page 23: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

b. Write C program to find even or odd number between two numbers given by user using if-else

#include<stdio.h>

int main()

{

int number;

printf("Enter an integer: ");

scanf("%d",&number);

// True if the number is perfectly divisible by 2

if(number %2==0)

printf("%d is even.", number);

else

printf("%d is odd.", number);

return0;

}

Output

Enter an integer: -7

-7 is odd.

c. Write C program to find grade of students using nested if-else

#include<stdio.h>

intmain(){intphy,chem, bio, math, comp;float per;

Page 24: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

/* Input marks of five subjects from user */printf("Enter five subjects marks: ");scanf("%d%d%d%d%d",&phy,&chem,&bio,&math,&comp);

/* Calculate percentage */per=(phy+chem+ bio + math + comp)/5.0;

printf("Percentage = %.2f\n", per);

/* Find grade according to the percentage */if(per >=90){printf("Grade A");}elseif(per >=80){printf("Grade B");}elseif(per >=70){printf("Grade C");}elseif(per >=60){printf("Grade D");}elseif(per >=40){printf("Grade E");}else{printf("Grade F");}

return0;}

Conclusion: After successful completion of this experiment student will be able to perform if-

else program.

Page 25: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 5.1Aim:-Study of Loop control structure (While Loop)

Theory:

6.1 While LoopThe syntax of a while loop is:while (testExpression) { //codes }where, testExpression checks the condition is true or false before each loop.

6.2 How while loop works?The while loop evaluates the test expression.If the test expression is true (nonzero), codes inside the body of while loop are exectued. The test expression is evaluated again. The process goes on until the test expression is false.When the test expression is false, the while loop is terminated.

6.3 Flowchart of while loop

Page 26: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

6.4 Program:

a. Write C program to print number 1 to 20 using while loop.

#include <stdio.h>

int main () {

/* local variable definition */int a = 1;

/* while loop execution */while( a < 20 ) {printf("value of a: %d\n", a);a++; }

return 0;}

b. Write C program to print square, cube and factorial of an entered number using while loop.

PROGRAM:#include<stdio.h>#include<conio.h>void main(){intn,i,f,sqr,cube; f=i=1;clrscr();printf("Enter a Number to Find Factorial: ");scanf("%d",&n);sqr=n*n;cube=n*n*n; while(i<=n) {

f*=i;i++; }printf("The Square of %d is : %d",n,sqr);printf("The cune of %d is : %d",n,cube);printf("The Factorial of %d is : %d",n,f);getch();} OUTPUT:

Page 27: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Enter a Number to Find Factorial: 5The Factorial of 5 is : 120

c. Program to check a number is Palindrome number or not.

#include <stdio.h>int main(){ int n, reversedInteger = 0, remainder, originalInteger;

printf("Enter an integer: ");scanf("%d", &n);

originalInteger = n;

// reversed integer is stored in variable while( n!=0 ) { remainder = n%10; reversedInteger = reversedInteger*10 + remainder;

n =n/ 10; }

// palindrome if orignalInteger and reversedInteger are equal if (originalInteger == reversedInteger)printf("%d is a palindrome.", originalInteger); elseprintf("%d is not a palindrome.", originalInteger);

return 0;}

OUTPUT:-Enter an integer: 121121 is palindrome

Conclusion: After successful completion of this experiment student will be able to perform

While loop Programs.

Page 28: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 5.2Aim: Study of Loop control structure (Do-While Loop)

Theory:

7.1 Do-While Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

SyntaxThe syntax of a do...while loop in C programming language is −do {statement(s);} while( condition );Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

7.2 Flow Diagram

Page 29: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

7.3 Difference Between While and Do_while

BASIS FOR COMPARISON WHILE DO-WHILE

General Form while ( condition) {statements; //body of loop}

do{.statements; // body of loop..} while( Condition );

Controlling Condition

In 'while' loop the controlling condition appears at the start of the loop.

In 'do-while' loop the controlling condition appears at the end of the loop.

Iterations The iterations do not occur if, the condition at the first iteration, appears false.

The iteration occurs at least once even if the condition is false at the first iteration.

Program

a. Write C program to check number is Armstrong number or not.

A positive integer is called an Armstrong number of order n ifabcd... = an + bn + cn + dn + ...In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number#include <stdio.h>int main(){ int number, originalNumber, remainder, result = 0;

printf("Enter a three digit integer: ");scanf("%d", &number);

originalNumber = number;

do { remainder = originalNumber%10; result =result+ remainder*remainder*remainder;

Page 30: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

originalNumber= originalNumbe/10; } while (originalNumber != 0);

if(result == number)printf("%d is an Armstrong number.",number); elseprintf("%d is not an Armstrong number.",number);

return 0;}

b. Write C program to find sum of digits of integer.#include <stdio.h> int main(){  int Number, Reminder, Sum=0;   printf("\n Please Enter any number\n");  scanf("%d", &Number);do  {     Reminder = Number % 10;     Sum = Sum+ Reminder;     Number = Number / 10;  }   while(Number > 0);

   printf("\n Sum of the digits of Given Number = %d", Sum);   return 0;}

c. Write C program to check a number entered by user is perfect number or not.

#include <stdio.h>intmain(){inti,num, sum =0;/* Input a number from user */printf("Enter any number to check perfect number: ");scanf("%d",&num);/* Calculate sum of all proper divisors */for(i=1;i<num;i++){/* If i is a divisor of num */

Page 31: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

if(num%i==0){sum=sum + i;}}/* Check whether the sum of proper divisors is equal to num */if(sum ==num){printf("%d is PERFECT NUMBER",num);}else{printf("%d is NOT PERFECT NUMBER",num);}return0;}

Conclusion: After successful completion of this experiment student will be able to perform iDo-

while loop program.

Page 32: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 6Aim: Study Loop control structure (For Loop)

Theory:

8.1 For LoopA for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax

The syntax of a for loop in C programming language is −

for ( init; condition; increment ) {statement(s);}

Here is the flow of control in a 'for' loop −

The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.

After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

8.2 Flow Diagram

Page 33: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Example

#include<stdio.h>

int main (){

int a; /* for loop execution */

for( a =10; a <20; a = a +1){

printf("value of a: %d\n", a);

}return0;

}

When the above code is compiled and executed, it produces the following result −

value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 15value of a: 16value of a: 17value of a: 18value of a: 19

Page 34: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

8.3 Difference Between For and While Loop

BASIS FOR COMPARISON FOR WHILE

Declaration for(initialization; condition; iteration){//body of 'for' loop}

while ( condition) {statements; //body of loop}

Format Initialization, condition checking, iteration statement are written at the top of the loop.

Only initialization and condition checking is done at the top of the loop.

Use The 'for' loop used only when we already knew the number of iterations.

The 'while' loop used only when the number of iteration are not exactly known.

Condition If the condition is not put up in 'for' loop, then loop iterates infinite times.

If the condition is not put up in 'while' loop, it provides compilation error.

Initialization In 'for' loop the initialization once done is never repeated.

In while loop if initialization is done during condition checking, then initialization is done each time the loop iterate.

Iteration statement In 'for' loop iteration statement is written at top, hence, executes only after all statements in loop are executed.

In 'while' loop, the iteration statement can be written anywhere in the loop.

Program

a. Write C program to check and generate prime number up to n.

#include<stdio.h>

int main(){

    int num,i,count,n;    printf("Enter max range: ");    scanf("%d",&n);

    for(num = 1;num<=n;num++){

         count = 0;

Page 35: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

         for(i=2;i<=num/2;i++){             if(num%i==0){                 count++;                 break;             }        }                 if(count==0 &&num!= 1)             printf("%d ",num);    }     return 0;}

Sample output:Enter max range: 502 3 5 7 11 13 17 19 23 29 31 37 41 43 47

b. Write C program to find GCD of two entered number.

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).#include <stdio.h>int main(){int n1, n2, i, gcd;printf("Enter two integers: ");scanf("%d %d", &n1, &n2);for(i=1; i<= n1 &&i<= n2; ++i) { // Checks if i is factor of both integersif(n1%i==0 && n2%i==0)gcd = i; }printf("G.C.D of %d and %d is %d", n1, n2, gcd);return 0;

Program to print half pyramid using **

Page 36: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

* ** * ** * * ** * * * *Source Code#include <stdio.h>int main(){inti, j, rows;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1; i<=rows; ++i) {for(j=1; j<=i; ++j) {printf("* "); }printf("\n"); }return 0;}

Program to print half pyramid a using numbers11 21 2 31 2 3 41 2 3 4 5Source Code#include<stdio.h>int main(){inti, j, rows;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1;i<=rows;++i){for(j=1; j<=i;++j){printf("%d ",j);}printf("\n");

Page 37: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

}return0;}

Print Floyd's Triangle.12 34 5 67 8 9 10Source Code#include<stdio.h>int main(){int rows,i, j, number=1;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1;i<= rows;i++){for(j=1; j <=i;++j){printf("%d ", number);++number;}

printf("\n");}

return0;}

* * * * * * * * * * * *

Conclusion: After successful completion of this experiment student will be able to perform For

Loop program.

Page 38: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 7

Aim: Study of an Array

Theory:

7.1 Array:

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays:

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

Page 39: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

balance[4] = 50.0;

The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary variable. The following example shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays 

Page 40: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Program:#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n to 0 */

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

n[ i ] = i + 100; /* set element at location i to i + 100 */

}

/* output each array element's value */

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

printf("Element[%d] = %d\n", j, n[j] );

} return 0;

}Output:

Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109

A. Write C program to find minimum and maximum from n entered numbers.

/** * C program to find maximum and minimum element in array */

#include <stdio.h>

Page 41: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

#define MAX_SIZE 100 // Maximum array size

int main(){ int arr[MAX_SIZE]; int i, max, min, size;

/* Input size of the array */ printf("Enter size of the array: "); scanf("%d", &size);

/* Input array elements */ printf("Enter elements in the array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); }

/* Assume first element as maximum and minimum */ max = arr[0]; min = arr[0];

/* * Find maximum and minimum in all array elements. */ for(i=1; i<size; i++) { /* If current element is greater than max */ if(arr[i] > max) { max = arr[i]; }

/* If current element is smaller than min */ if(arr[i] < min) { min = arr[i]; } }

/* Print maximum and minimum element */ printf("Maximum element = %d\n", max); printf("Minimum element = %d", min);

return 0;

Page 42: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

}

Output:

Enter size of the array: 10

Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10

Maximum element = 100

Minimum element = -10

B. Write C program to print alternate numbers from n entered numbers

/*  * C Program to Print the Alternate Elements in an Array  */  #include <stdio.h> void main() {  int array[10]; int i; printf("enter the element of an array \n"); for (i = 0; i < 10; i++) scanf("%d", &array[i]);  printf("Alternate elements of a given array \n"); for (i = 0; i < 10; i += 2) printf( "%d\n", array[i]) ; }

Output:

1223455768738497

Page 43: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

120125Alternate elements of a given array12456884120

C. Write C program to search an element in an array using linear and binary search.

Binary search:

#include <stdio.h>

int main()

{

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d",&n);

printf("Enter %d integers\n", n);

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

scanf("%d",&array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;

else if (array[middle] == search) {

printf("%d found at location %d.\n", search, middle+1);

Page 44: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

break;

}

else

last = middle - 1;

middle = (first + last)/2;

}

if (first > last)

printf("Not found! %d isn't present in the list.\n", search);

return 0;

}

Linear search:

#include <stdio.h>

int main()

{

int array[100], search, c, n;

printf("Enter the number of elements in array\n");

scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

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

scanf("%d", &array[c]);

printf("Enter a number to search\n");

scanf("%d", &search);

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

{

if (array[c] == search) /* If required element is found */

{

printf("%d is present at location %d.\n", search, c+1);

break;

Page 45: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

} }

if (c == n)

printf("%d isn't present in the array.\n", search);

return 0;

}

Output:

D. Write C program to print entered number in ascending order using sorting.

/* * C program to sort N numbers in ascending order using Bubble sort * and print both the given and the sorted array */#include <stdio.h>#define MAXSIZE 10 void main(){ int array[MAXSIZE]; int i, j, num, temp;  printf("Enter the value of num \n"); scanf("%d", &num); printf("Enter the elements one by one \n"); for (i = 0; i < num; i++) {

Page 46: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

scanf("%d", &array[i]); } printf("Input array is \n"); for (i = 0; i < num; i++) { printf("%d\n", array[i]); } /* Bubble sorting begins */ for (i = 0; i < num; i++) { for (j = 0; j < (num - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } printf("Sorted array is...\n"); for (i = 0; i < num; i++) { printf("%d\n", array[i]); }}

Output:

Enter the value of num6Enter the elements one by one234567891234Input array is2345678912

Page 47: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

34Sorted array is...122334456789

Conclusion: After successful completion of this experiment student will be able to perform

program using array.

Page 48: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 8Aim: Study of Function and String

Theory:

9.1 Function:

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list ) {

body of the function

}

A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Page 49: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of statements that define what the function does.

A. Write C program to print addition, subtraction and multiplication of Matric

#include <stdio.h>

int main()

{

int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");

scanf("%d%d", &m, &n);

printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)

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

scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

for (c = 0; c < m; c++)

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

scanf("%d", &second[c][d]);

Page 50: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

printf("Sum of entered matrices:-\n");

for (c = 0; c < m; c++) {

for (d = 0 ; d < n; d++) {

sum[c][d] = first[c][d] + second[c][d];

printf("%d\t", sum[c][d]);

}

printf("\n");

}

return 0;

}

Output:

Page 51: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

String:

Strings are actually one-dimensional array of characters terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows −

char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array

B. Write C program to find length of string (with and without using library function).

#include<stdio.h>

int main() {

char str[100];

int length;

printf("\nEnter the String : ");

gets(str);

Page 52: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

length = 0; // Initial Length

while (str[length] != '\0')

length++;

printf("\nLength of the String is : %d", length);

return(0);

}

Conclusion: After successful completion of this experiment student will be able to perform

program using Function.

Page 53: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 9Aim: Study of structure

Theory:

Structures in CWhat is a structure?A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to create a structure?‘struct’ keyword is used to create a structure. Following is an example.struct addrress

{

   char name[50];

   char street[100];

   char city[50];

   char state[20];

   int pin;

};

 How to declare structure variables?A structure variable can either be declared with structure declaration or as a separate declaration like basic types.// A variable declaration with structure declaration.

struct Point

{

   int x, y;

} p1;  // The variable p1 is declared with 'Point'

 // A variable declaration like basic data types

struct Point

{

Page 54: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

   int x, y; };

 int main()

{

   struct Point p1;  // The variable p1 is declared like a normal variable

}

Note: In C++, the struct keyword is optional before in declaration of variable. In C, it is mandatory.

 How to initialize structure members?Structure members cannot be initialized with declaration. For example the following C program fails in compilation.

struct Point

{

   int x = 0;  // COMPILER ERROR:  cannot initialize members here

   int y = 0;  // COMPILER ERROR:  cannot initialize members here

};

The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.

Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.struct Point

{

   int x, y;

};  

int main()

{

   // A valid initialization. member x gets value 0 and y

   // gets value 1.  The order of declaration is followed.

   struct Point p1 = {0, 1};

}

Page 55: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

 How to access structure elements?Structure members are accessed using dot (.) operator.struct Point

{

   int x, y;

}; 

int main()

{

   struct Point p1 = {0, 1};

 

   // Accesing members of point p1

   p1.x = 20;

   printf ("x = %d, y = %d", p1.x, p1.y);

    return 0;

}

Output:

20 1

  What is an array of structures?Like other primitive data types, we can create an array of structures.struct Point

{

   int x, y;

}; 

int main()

{

   // Create an array of structures

   struct Point arr[10];

Page 56: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

 

   // Access array members

   arr[0].x = 10;

   arr[0].y = 20;

    printf("%d %d", arr[0].x, arr[0].y);

   return 0;

}

Run on IDE

Output:

10 20

 What is a structure pointer?Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator.struct Point

{

   int x, y;

}; 

int main()

{

   struct Point p1 = {1, 2};

    // p2 is a pointer to structure p1

   struct Point *p2 = &p1; 

   // Accessing structure members using structure pointer

   printf("%d %d", p2->x, p2->y);

   return 0;

}

Output:

1 2

Page 57: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

A. Programs demonstrating use of Structures, Arrays of Structures and structure containing arrays.

#include <stdio.h>

#include <string.h>

struct student

{

int id;

char name[30];

float percentage;

};

int main()

{

int i;

struct student record[2];

// 1st student's record

record[0].id=1;

strcpy(record[0].name, "Raju");

record[0].percentage = 86.5;

// 2nd student's record

record[1].id=2;

strcpy(record[1].name, "Surendren");

record[1].percentage = 90.5;

// 3rd student's record

record[2].id=3;

Page 58: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

strcpy(record[2].name, "Thiyagu");

record[2].percentage = 81.5;

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

{

printf(" Records of STUDENT : %d \n", i+1);

printf(" Id is: %d \n", record[i].id);

printf(" Name is: %s \n", record[i].name);

printf(" Percentage is: %f\n\n",record[i].percentage);

}

return 0;

}

Output:

Records of STUDENT : 1Id is: 1Name is: RajuPercentage is: 86.500000 Records of STUDENT : 2Id is: 2Name is: SurendrenPercentage is: 90.500000 Records of STUDENT : 3Id is: 3Name is: ThiyaguPercentage is: 81.500000

Page 59: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Practical No 10

Aim: Study of Pointer

Theory:

Pointer:

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations −

int *ip; /* pointer to an integer */double *dp; /* pointer to a double */float *fp; /* pointer to a float */char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

B. Programs demonstrating use of pointers to integers, floats, char, strings, structures and arrays.

#include <stdio.h>

#include <stdlib.h>

struct person {

int age;

float weight;

Page 60: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

char name[30];

};

int main()

{

struct person *ptr;

int i, num;

printf("Enter number of persons: ");

scanf("%d", &num);

ptr = (struct person*) malloc(num * sizeof(struct person));

// Above statement allocates the memory for n structures with pointer personPtr pointing to base address */

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

{

printf("Enter name, age and weight of the person respectively:\n");

scanf("%s%d%f", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight);

}

printf("Displaying Infromation:\n");

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

printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);

return 0;

}

Out put:

Page 61: Syntax · Web viewPractical No 1.1 Aim: Study of Algorithm and Flowchart Theory: Algorithm An algorithm is a procedure or step-by-step instruction for solving a problem. They form

Enter number of persons: 2

Enter name, age and weight of the person respectively:

Adam

2

3.2

Enter name, age and weight of the person respectively:

Eve

6

2.3

Displaying Information:

Adam 2 3.20

Eve 6 2.30

Conclusion: After successful completion of this experiment student will be able to perform

program using pointer.