You are on page 1of 46

How to Answer a Question.?!

What Would be the Expected Answer.?!

Solution to
Model Question Papers
Principles of Programming Using C
BPOPS103/ (22POP13)
WELCOME
to

VLA CREATIONS
A computer is an electronic device that performs five major operations:
• Accepting data or instructions (input)
• Storing data
• Processing data
• Displaying results (output)
• Controlling and coordinating all operations inside a computer
Input unit – Input unit is a unit that accepts any input device. The input device is used to input data into
the computer system. Function of input unit:
o It converts inputted data into binary codes.
o It sends data to main memory of computer.
Central Processing Unit (CUP) – CPU is called the brain of a computer. An electronic circuitry that
carries out the instruction given by a computer program. CPU can be sub classified into three parts.
i .Control unit (CU)
ii. Arithmetic & Logic unit (ALU)
iii. Memory Unit (MU)
i. Control unit (CU)- the control unit manages the various components of the computer. It reads instructions from
memory and interpretation and changes in a series of signals to activate other parts of the computer. It controls and co-
ordinate is input output memory andall other units.

ii. Arithmetic & Logic unit (ALU) – The arithmetic logic unit (ALU), which performs simple arithmetic operation such as
+,-, *, / and logical operation such as >, <, =<, <= etc.

iii. Memory Unit (MU)- Memory is used to store data and instructions before and after processing. Memory is also called
Primary memory or internal memory. It is used to store data temporary or permanently.
Function of CPU-
• It controls all the parts and software and data flow of computer.
• It performs all operations.
• It accepts data from input device.
• It sends information to output device.
• Executing programs stored in memory
• It stores data either temporarily or permanent basis.
• It performs arithmetical and logical operations.
Output Unit- Output unit is a unit that constituents a number of output device. An output device is used to show the result
of processing.
Function of Output unit:
• It accepts data or information sends from main memory of computer
• It converts binary coded information into HLL or inputted languages.
Input devices: 1)Keyboard - The keyboard is the main input – The users can use mouse to handle the pointer easily on
device for computers. the screen to perform various functions like opening a
• With a keyboard , the user can type a document, use key program or file.
stroke shortcuts, access menus, play games and perform • The mouse has two buttons and a scroll wheel.
numerous other tasks. • It can be held in the hand and easily moved, without lifting,
• Most keyboards have between 80 and 110 keys which along the hard flat surface to move the cursor to the desired
include: location- up, down, left and right.
– Typing keys 3) Touch Screen
– Numeric keys • A touch screen is a display screen which can identify the
– Function keys occurrence and position of a touch inside the display region.
• Typing Keys: • The user can touch the screen either by his finger or by using
– These include the letters of the alphabet. a stylus.
– The layout of a keyboard is known as QWERTY for its • These displays can be connected to computers, laptops,
first six letters. PDAs, cell phones etc.
• Numeric Keys • Touch screen monitors are widely used in different
applications including:
– These include a set of 17 keys, arranged in the same
configuration found on calculators to speed up the data – Point-of-Sale cash registers.
entry of numbers. – PDAS
2)Mouse – Automated Teller Machines.
– The mouse is the key input device to be used in a – Car Navigation screens.
graphical user interface (GUI). – Mobile Phones.
Monitor
– The monitor is a soft copy output devices used to display video and graphics information generated by the
computer through the video card.
– Monitors display information at a much higher quality
– The monitor is connected to either a VGA or the digital video interface (DVI) port on the video card.
Monitors come in three variants:
• Cathode Ray Tube(CRT).
• Liquid Crystal Display(LCD).
• Plasma Monitors.
• Projector
• A projector is a device which takes an image from a video source and projects it on to a screen or other surface.
• These days, projectors are used for a wide range of applications varying from home theater systems to organizations
for projecting information and presentations on to screens large enough for rooms filled with people to see.
• Projectors also allows users to change/ adjust some features of the image such as brightness, sharpness, and color
settings similar to the features available in a standard television.
• Speakers
• Today all business and home users demand sound capabilities from their computers.
• For this purpose, speakers were developed in different sizes and shapes and also with different powers and sound
quality.
• With good quality speakers, the voice will also be audible even to people sitting in another or room or even to
neighbors.
Algorithm printf("The area of the given circle is %f", area);
Step 1: Start return 0;
Step 2: Input radius and variable area }
Step 3: let pi = 3.14
Step 4: area = pi * radius * radius
Step 6: print area
Step 7: stop

Program
#include <stdio.h>
int main()
{
int radius;
float area;
printf("Enter The Radius of Cicle:");
scanf("%d",&radius);
area = 3.14* radius * radius;
Identifiers 7. Maximum length of an identifier is 31 characters.
It refers to the name of the objects.
These are the names given to variables, functions,
macros etc.
The rules to write an identifier are as follows:
1. It must contain only alphabets (A to Z, a to z),
numbers (0 to 9) and underscore ( _ ). containing a special character
2. It must start with alphabet or underscore but not
numeric character.
3. It should not contain any special symbols apart from
underscore.
4. It should not have any space.
5. Keywords cannot be used as identifiers.
6. Identifiers are case sensitive.
printf()
The printf function (stands for print formatting) is used to display information required by the user and also prints the values
of the variables. For this, the print function takes data values, converts them to a text stream using formatting specifications in
the control string and passes the resulting text stream to the standard output. The control string may contain zero or more
conversion specifications, textual data, and control characters to be displayed.
printf("control string", variable list);
The function accepts two parameters-control string and variable list. The control string may also contain the text to be printed
like instructions to the user, captions, identifiers, or any other text to make the output readable.
Example
printf("\n The number is %6d", 12);
O/p: The number is 12
scanf( )
• The scanf() function stands for scan formatting and is used to read formatted data from the keyboard. The scanf function
takes a text stream from the keyboard, extracts and formats data from the stream according to a format control string
and then stores the data in specified program variables. The syntax of the scanf() function can be given as:
• scanf("control string", arg1, arg2, arg3,….argn);
• The control string specifies the type and format of the data that has to be obtained from the keyboard and stored in the
memory locations pointed by arguments arg1, arg2,, argn, i.e., the arguments are actually the variable addresses where
each piece of data is to be stored.
Example: int num;
• scanf("%d", &num);
Requirement Analysis
• In this phase, the user’s expectations are gathered to know why the program/software has to
be built.
• Then all the gathered requirements are analyzed to arrive at the scope or objective of the
overall software product.
• The last activity in this phase includes documenting every identified requirement of the user
in order to avoid any doubts or uncertainty regarding the functionality of the program.
Design
• The requirements documented in the previous phase acts as an input to the design phase.
• In the design phase, a plan of actions is made before the actual development process can
start.
• In the design phase, the core structure of the software/program is broken down into modules.
• The solution of the program is then specified for each module in the form of
algorithms/flowcharts.
Implementation
• In this phase, designed algorithms are converted into program codes using any of the high level languages.
• The particular choice of language will depend on the type of program, such as whether it is system or application program.
• While C is preferred for writing system programs , Visual Basic might be preferred for writing an application program.
• The program codes are tested by the programmers to ensure their correctness.
• This phase is also called construction or code generation phase, as the code of the software is generated in this phase.
Testing
• In this phase , all the modules are tested together to ensure that the overall system works as a whole product.
• In this phase, the software is tested using a large number of varied inputs, also known as test data, to ensure that the
software is working as expected by the user’s requirements that were identified in the requirement analysis phase.
Software Deployment, training and support
• After the code is tested and the software or the program has been approved by the users, it is installed or deployed in the
production environment.
• Product designers and developers spend a lot of time to create software but if nobody in an organization knows how to use
it or fix up certain problems, then no one would like to use it.
Maintenance
• Maintenance and enhancements are ongoing activities that are done to cope with newly discovered problems or new
requirements.
• Such activities may take a long time to complete as the requirements may call for the addition of new code that does not
fit the original design or an extra piece of code required to fix an unforeseen problem.
• As a general rule, if the cost of the maintenance phase exceeds 25% of the prior phase, it clearly indicates that the overall
quality of at least one prior phase is poor.
• In such cases, it is better to rebuild the software (or some modules) before the maintenance cost shoots out of control.
1. Arithmetic Operators 2. Relational Operators 3. Equality Operators 4. Conditional Operators
Arithmetic Operators: The different arithmetic operators are:

• Relational Operators:
• A relational operator is also known as comparison operator, is one that compares two values.
• Expressions that contain relational operators are called relational expressions.
• Relational operators return true(1) or false(0) value, depending on the
• The relational operators are evaluated from left to right.
• Characters are considered valid operands since they are represented by numeric values in the computer system .
• The different relational operators are:
Equality Operators
• C language supports two kinds of operators to compare their operators for equality or inequality.
• They are equal to(= =) and not equal to (!=) operators.
• The equality operators have lower precedence than the relational operators.

Conditional operator / Ternary Operator(?:)


• The conditional operator or Ternary operator (? :) is just like an if-else statement that can be within expressions.
Such an operator is useful in situations in which there are two or more alternatives for an expression.
• The syntax of the conditional operator is exp1 ? exp2 : exp3
• Where,
• Expression1  Condition
• Expression2  Statement followed if condition is true
• Expression3  Statement followed if condition is false
• Ex: large = (4 > 2) ? 4: 2  large = 4
• TYPE CONVERSION AND TYPE CASTING cast an integer variable into a floating point variable.
• Type conversion and type casting of variables refers to float salary = 10000.00;
changing a variable of one data type into another. int sal;
• While type conversion is done implicitly, casting has to sal = (int) salary;
be done explicitly by the programmer. • Typecasting can be done by placing the destination data
Type conversion is done when the expression has variables type in parentheses followed by the variable name that
of different data types. So to evaluate the expression, the has to be converted.
data type is promoted from lower to higher level where the • When floating point numbers are converted to integers,
hierarchy of data types can be given as: double, float, long, the digits after the decimal are truncated.
int, short and char.
• Typecasting is done to make a variable one data type to
For example, type conversion is automatically done when act like a variable of another type.
we assign an integer value to a floating point variable.
• Examples: res = (int) 9.5 ;
For ex: float x;
9.5 is converted to 9 by truncation and then assigned to res.
int y = 3;
res = (int) 12.3 / (int) 4.2
x = y;
It is evaluated as 12/4 and the value 3 is assigned to res.
Now, x = 3.0,
Type casting is also known as forced conversion. It is done
when the value of a
• higher data type has to be converted in to the value of a
lower data type. For example, we need to explicitly type
#include <math.h> printf("Roots are real and distinct \n");
#include <stdio.h> printf("root1 = %.2f and root2 = %.2f", root1, root2);
int main( ) { }
float a, b, c, disc, root1, root2, realPart, imagPart; // condition for real and equal roots
printf("Enter coefficients a, b and c: "); else if (disc == 0) {
scanf("%f %f %f", &a, &b, &c); root1 = root2 = -b / (2 * a);
//check for zero coefficients printf("Roots are real and equal \n");
if((a==0)||(b==0)||(c==0)) printf("root1 = root2 = %.2f ", root1);
{ } // if roots are not real
printf("Invalid coefficients\n"); else {
return 0; realPart = -b / (2 * a);
} imagPart = sqrt(-disc) / (2 * a);
disc = b * b - 4 * a * c; printf("Roots are imaginary \n");
// condition for real and different roots printf("root1 = %.2f+%.2fi and root2 = %.2f - %.2fi",
if (disc> 0) realPart, imagPart, realPart,imagPart);
{ }
root1 = (-b + sqrt(disc)) / (2 * a); return 0;
root2 = (-b - sqrt(disc)) / (2 * a); }
Looping is nothing but repeating the execution of a list of loop
statements, depending on the value of an integer expression.
While loop
• It is a pre-test loop (also known as entry controlled loop).
• This loop has following syntax:
while (condition)
{
statement_block; Example: WAP to find sum of 1 to 5 using while.
} #include<stdio.h>
statement x; void main( )
{
• The while loop is used to repeat one or more statements
int i=1,
while a particular condition is true.
sum=0;
• In the while loop, the condition is tested before any of the while (i< = 5)
statements in the statement block is executed. {
• If the condition is true, only then the statements will be sum=sum+i;
executed otherwise the control will jump to the i = i++;
immediate statement outside the while loop block. }
• We must constantly update the condition of the while printf(“%d”, sum);
}
do…. while loop
It is a post-test loop (also called exit controlled loop) it has
two keywords do and while.
Syntax
do
{
statement-block;
} while (condition);
Example: WAP to find sum of 1 to 5 using do…
• In this loop the body of the loop is executed first and then while
test condition is evaluated. #include<stdio.h>
• If the condition is true, then the body of loop will be void main( )
executed once again. This process continues as long as {
condition is true. int i=1, sum=0;
do
• When condition becomes false, the loop will be
{
terminated and control comes out of the loop.
sum=sum+i;
i=i++;
} while (i<=5);
printf(“%d”, sum);
}
#include <stdio.h> break;
void main() case '/': result = num1 / num2;
{ break;
char operator; default: printf("\n You have entered an Invalid Operator ");
float num1, num2, result = 0; }
printf("Enter an Operator (+, -, *, /) :\n "); printf("\n The result of %f %c %f = %f", num1, Operator,
scanf("%c", &Operator); num2, result);
printf("Enter the Values for two Operands: num1 and num2 : }
\n ");
scanf("%f%f", &num1, &num2);
switch(operator)
{
Lab program 1
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
• Break Statement • It terminates only the current iteration of the loop.
• In C, break statement is used to terminate the execution • Continue can appear in looping statements.
of the nearest en-closing loop in which it appears. • Keyword used is continue
• It terminates the execution of remaining iteration of loop.
• A break can appear in both switch and looping Syntax
statements. Keyword is break while(condition)
{
• Syntax Statements; if(condition)
while(condition) Example Example
#include<stdio.h> continue; Statements; #include<stdio.h>
{ }
void main( ) { void main( )
Statements; int i; {
if(condition) for(i=1; i<=5; i++) int i;
break; { for(i=1; i<=5; i++)
Statements; if(i= =3) {
break; if(i= =3)
}
printf(“%d”, i) continue;
} printf(“%d”, i)
} }}
Continue OUTPUT 1 2 OUTPUT 1 2 4 5
C-language provides goto statement to transfer control unconditionally to other part of the program. Although
use of goto statement is not advisable but sometime it is desirable to use go to statement. It has the following
form:
goto statement requires a label to determine where to transfer the control. A label
must end with colon (:). We can use any valid name as a label similar to variable name. When
compiler encounters goto statement with a label name then, it transfers the control to the
location where label has been defined in the program
Example: #include<stdio.h>
void main()
{
printf(“Bangalore \t”);
goto label;
printf(“is a \t”);
lable: printf(“smart city”);
}
Output:
Bangalore smart city
The ‘switch’ statement is a control statement used to make a select one alternative among several alternatives.
It is a “multi-way decision statement” that tests whether an expression matches one of the case values and
branches accordingly.
Here switch, case, break and default are built-in C language words.
•If the choice matches to label1 then block1 will be executed else if it evaluates to label2 then block2 will be
executed and so on.
•If choice does not matches with any case labels, then default block will be executed
Example: case '/': result = num1 / num2;
#include <stdio.h> break;
void main() default: printf("\n You have entered an Invalid Operator
{ ");
char Operator; }
float num1, num2, result = 0; printf("\n The result of %f %c %f = %f", num1, Operator,
printf("Enter an Operator (+, -, *, /) :\n "); num2, result);
scanf("%c", &Operator); }
printf("Enter the Values for two Operands: num1 and
num2 : \n ");
scanf("%f%f", &num1, &num2);
switch(Operator)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
#include <stdio.h> /* Perform Bubble Sort */
#include <stdlib.h> for(i=1;i<n;i++)
void main() {
for(j=0;j<n-i;j++)
{
{
int a[50],i,j,temp,n; /* Declaration of the variables*/
if(a[j]>a[j+1])
printf("Enter the value of n\n");
{
scanf("%d",&n); /* Read the size of an array */
temp=a[j];
printf("Enter the array elements\n"); a[j]=a[j+1];
for(i=0;i<n;i++) a[j+1]=temp;
scanf("%d",&a[i]); /* Read the elements */ }
printf("The given array elements are \n"); }
for(i=0;i<n;i++) }
printf("%d\t",a[i]); printf("\nThe array after sorting\n");
/* Display the array after sorting */
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
● “A recursive function is a function that calls itself to defined in terms of simpler problems and the simplest
solve a smaller version of its task until a final call is made problem is given explicitly.
which does not require a call to itself “.
● Every recursive solution has two major cases, they are
base case, in which the problem is simple enough to be
solved directly without making any further calls to the
same function
recursive case, in which first the problem at hand is
divided into simpler sub parts. Second the function calls
itself but with sub parts of the problem obtained in the
first step. Third, the result is obtained by combining the
solutions of simpler sub-parts.
● Therefore, recursion is defining large and complex
problems in terms of a smaller and more easily solvable
problem. In recursive function, complicated problem is
BLOCK SCOPE • PROGRAM SCOPE
A statement block is a group of statements enclosed within an If you want that functions should be able to access some
opening and closing curly brackets ({ }). If a variable is declared variables which are not passed to them as arguments, then
within a statement block then, as soon as the control exits that declare those variables outside any function blocks. Such
block, the variable will cease to exist. variables are commonly known as global variables. Hence,
Such a variable also known as a local variable is said to have a global variables are those variables that can be accessed from
block scope. any point in the program.
#include <stdio.h>
int main() #include<stdio.h>
{ int x = 10;
int x = 10; void print();
Int i=0; int main()
printf("\n The value of x outside the while loop is %d", x); { printf("\n The value of x in the main() = %d", x);
while (i<3) int x = 2;
{ int x = i; printf("\n The value of local variable x in the main() = %d", x);
printf("\n The value of x inside the while loop is %d", x); print();
i++; }
} void print()
printf("\n The value of x outside the while loop is %d", x); { printf("\n The value of x in the print() = %d", x);
return 0; }
}
FUNCTION SCOPE
Function scope is applicable only with goto label names. That is the programmer can not have the same label
name inside a function.

FILE SCOPE
• When a global variable is accessible until the end of the file, the variable is said to have file scope.
• To allow a variable to have file scope, declare that variable with the static keyword before specifying its data type,
like this:
• static int x = 10;
• A global static variable can be used any where from the file in which it is declared but it is not accessible by any
other files.
• Such variables are useful when the programmer writes his own header files.
Call by value Call by reference
• In the Call by value method original value is not modified • Call by reference method, the original value is modified.
• In Call by value, a copy of the variable is passed • Call by reference, a variable itself is passed
• In Call by value, actual and formal arguments will be created • whereas in Call by reference, actual and formal arguments
in different memory locations, will be created in the same memory location.
#include<stdio.h> #include<stdio.h>
int swap(int, int); int swap(int *, int *);
int main( ) int main( )
{ {
int a=5, b=10 ; int a=5, b=10 ;
swap(a, b); swap(&a, &b);
printf(“%d%d:, a, b); printf(“%d%d:, a, b);
} }
int swap(int x, int y) int swap(int *x, int *y)
{ {
int temp; int temp;
temp = x; temp = *x;
x = y; *x = *y;
y = temp; *y = temp;
} }
#include <stdio.h> for (int i = 0; i < 3; i++)
int main() { {
int a[3][3], transpose[3][3]; for (int j = 0; j < 3; j++)
printf("\nEnter matrix elements:\n"); {
for (int i = 0; i < 3; ++i){ transpose[i][j] = a[j][i];
for (int j = 0; j < 3; ++j) }
{ // printing the transpose
scanf("%d", &a[i][j]); printf("\nTranspose of the matrix:\n");
} for (int i = 0; i < 3; i++)
} {
// printing the matrix a[][] printf(“\n”);
printf("\nEntered matrix: \n"); for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++) printf("%d ", transpose[i][j]);
{ if (j == r - 1)
printf(“\n”); printf("\n");
for (int j = 0; j < 3; j++) }
printf("%d ", a[i][j]); return 0;
} }
// computing the transpose
The storage class of a variable defines the scope (visibility) and life time of variables
and/or functions declared within a C Program. In addition to this, the storage class gives
the following information about the variable or the function.
• It is used to determine the part of memory where storage space will be allocated for
that variable or function
• how long the storage allocation will continue to exist for that function
• It specifies the scope of the variable or function
• It specifies whether the variable will be automatically initialized to zero or to any
indeterminate value
OPERATIONS ON STRINGS
1. Finding the length of a string
2. Converting characters of a string into upper case
3. Converting characters of a string into lower case
4. Concatenating two strings to form a new string
5. Comparing two strings
6. Reversing a string
7. Replacing a pattern with another pattern in a string
Strlen Function
Syntax: size_t strlen(const char *str);
This function calculates the length of the string str up to but
not including the null character, i.e., the function returns
the number of characters in the string.
Strcpy Function
Syntax: char *strcpy(char *str1, const char *str2);
This function copies the string pointed to by str2 to str1
including the null character of str2. It returns the argument
str1. Here str1 should be big enough to store the contents
of str2 .
#include <stdio.h> }
#include <stdlib.h> mean=sum/n;
#include<math.h> ptr=a;
void main() for(i=0;i<n;i++)
{ {
float a[10],*ptr,mean,std,sum=0,sumstd=0; sumstd=sumstd+pow((*ptr-mean),2);
int n,i; ptr++;
printf("Enter the no of elements\n"); }
scanf("%d",&n); std=sqrt(sumstd/n);
printf("Enter the array elements\n"); printf("Sum=%.3f\t",sum);
for(i=0;i<n;i++) printf("Mean=%.3f\t",mean);
{ printf("Standard Deviation=%.3f\t",std);
scanf("%f",&a[i]); }
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+*ptr;
ptr++;
A string is a collection of characters enclosed within the
double quotes.
• The general form of declaring a string is
• char str[size];
• For example if we write,
• char str[ ] = “HELLO”;
We are declaring a character array with 5 characters
namely, H, E, L, L and O. Besides, a null character („\0‟) is
stored at the end of the string. So, the internal
representation of the string becomes- HELLO‟\0‟. Note
that to store a string of length 5, we need 5 + 1 locations (1
Memory representation of
extra for the null character).
a character array
Strcmp Function
• Syntax: char *strcmp( const char *str1, const char *str2);
• The strcmp function compares the string pointed to by str1 to the string pointed to by str2. the function returns
zero if the strings are equal. Otherwise, it returns a value less than zero or greater than zero if str1 is less than or
greater than str2 respectively.
• Actually pointers are nothing but memory float *pnum1=&num1, *pnum2=&num2;
addresses. *psum=&sum;
• A pointer is a variable that contains the memory printf(“enter thw two numbers”);
location of another variable. scanf(“%f %f”,pnum1, pnum2);
• An integer value can be added or subtracted *psum=*pnum1+*pnum2;
from printf(“%f + %f = %.2f”, *pnum1,*pnum2,*psum);
a pointer variable return o;
• Prefix or postfix increment and decrement }
operators can be applied on a pointer variable
• A pointer variable cannot be added to another
pointer variable
• A pointer variable can be compared with
another pointer variable of same type
Program to add two floating point numbers using
pointers
#include<stdio.h>
int main()
{
float num1, num2, sum=0.0;
gets() puts( )
• gets() is an unformatted input function • Method of writing a string is by using puts().
• Used to read the string inputs • puts() function writes a line of output on the screen.
• Declaration: gets(str); • It terminates the line with a newline character (‘ \n ’).
• Helps to scan a line of text from a standard input • it returns an EOF (-1) if an error occurs or returns a
device positive number on success.
Ex: void main()
{ • Example : Char s[10];
char a[20]; gets(s);
printf(“Enter a string”); puts(s);
gets(a);
printf(“\n output=%s”,a);
}
Reads data untill encounters a newline character.
Files can be opened in different modes in C, depending on operations. If the file exists, its contents are truncated
the type of processing to be done on the file. The modes in to zero length. If the file does not exist, a new file is
which a file can be opened are: created.
1. "r" (read mode):The file is opened in read mode, 6. "a+" (read/append mode):The file is opened in
allowing read operations only. If the file does not exist, read/append mode, allowing both read and write
the fopen function returns NULL. operations at the end of the file. If the file does not
2. "w" (write mode):The file is opened in write mode, exist, a new file is created.
allowing write operations only. If the file exists, its
contents are truncated to zero length. If the file does
not exist, a new file is created.
3. "a" (append mode):The file is opened in append mode,
allowing write operations at the end of the file. If the
file does not exist, a new file is created.
4. "r+" (read/write mode):The file is opened in
read/write mode, allowing both read and write
operations. If the file does not exist, the fopen function
returns NULL.
5. "w+" (read/write mode):The file is opened in
read/write mode, allowing both read and write
#include <stdio.h> for(i=0; i<n;i++)
#include <stdlib.h> {
struct student printf("Enter USN: ");
{ scanf("%s",s[i].usn);
char usn[50]; printf("Enter name: ");
char name[50]; scanf("%s",s[i].name);
int marks; printf("Enter marks: ");
} s[10]; scanf("%d",&s[i].marks);
void main() { printf("\n"); }
int i,n,countav=0,countbv=0; printf("Displaying Information:\n\n");
float sum,average;
printf("Enter number of Students\n");
scanf("%d",&n);
printf("Enter information of students:\n");
// storing information
// displaying information if(s[i].marks>=average)
for(i=0; i<n; i++) countav++;
{ else
printf("\nUSN: %s\n",s[i].usn); countbv++;
printf("Name: %s\n ", s[i].name); }
printf("Marks: %d",s[i].marks); printf("\nTotal No of students above average=
printf("\n"); %d",countav);
} printf("\nTotal No of students below average=
for(i=0;i<n;i++) %d",countbv);
{ }
sum=sum+s[i].marks;
}
average=sum/n;
printf("\nAverage marks: %f",average);
for(i=0;i<n;i++)
{
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals
or integers that are given names by a user. The use of enum in C to name the integer values makes the
entire program easy to learn and understand.
The syntax for declaring a variable of an enumerated data type can be given as,
• enumeration_name variable_name;
• So to create a variable of COLORS, we may write:
• enum COLORS bg_color;
• Another way to declare a variable can be as illustrated in the statement below.
• enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color, fore_color;
• USING THE TYPEDEF KEYWORD
• C permits to use typedef keyword for enumerated data types. For ex, if we write
• typedef enum COLORS color;
• Then, we can straight-away declare variables by writing
• color forecolor = RED;
• C provides the following set of functions to read data from a file.
• fscanf() fgets() fgetc() fread()
• fscanf() function is used to read data formatted data from the stream.
int fscanf(FILE *stream, const char *format,…);
The fscanf() is used to read data from the stream and store them according to the parameter format into the locations
pointed by the additional arguments.

• fgets() stands for file get string. The fgets() function is used to get a string from a stream. The syntax of fgets() can be given
as:
char *fgets(char *str, int size, FILE *stream);
The fgets() function reads at most one less than the number of characters specified by size

• The fgetc() function returns the next character from stream, or EOF if the end of file is reached or if there is an error. The
syntax of fgetc() can be given as
int fgetc( FILE *stream );

• The fread() function is used to read data from a file. Its syntax can be given as:
int fread( void *str, size_t size, size_t num, FILE *stream );
C provides the following set of functions to read data from a file.
fprintf() fputs() fputc() fwrite()
• fprintf()
The fpritnt() is used to write formatted output to stream. Its syntax can be given as,
int fprintf ( FILE * stream, const char * format, ... );
• fputs()
The fputs() is used to write a line into a file. The syntax of fputs() can be given as
int fputs( const char *str, FILE *stream );

• fputc()
The fputc() is used to write a character to the stream.
int fputc(int c, FILE *stream);
The fputc() function will write the byte specified by c.

• fwrite()
The fwrite() is used to write data to a file. The syntax of fwrite can be given as,
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
The fwrite() function will write, from the array pointed to by str, up to count objects of size specified by size, to the stream
pointed to by stream.
Structure Union
• The keyword struct is used to define a structure • The keyword union is used to define a union
• It is a collection of heterogeneous elements of • Size of union is equal to the size of largest member.
different data type. • Memory allocated is shared by individual members of
• Each member within in a structure is assigned a unique union.
storage area of location. Size of structure is equal to the • Altering the value of any of the member will alter other
sum of sizes of its members. members value
• Altering the value of a member will not affect the other • Only one member can be accessed at a time
members of the structure • Only the first member of a union can be initialized.
• Individual members can be accessed at a time • Syntax: union tag_name
• Several members of a structure can initialize at once. • {
• Syntax: struct struct_name data-type member1;
• { data-type member2;
data-type member1; data-type membern;
data-type member2; };
data-type membern;
}; Example
Example
• EOF stands for End of File. The function getc() returns }
EOF, on success.. • In the above program, file isopened by using fopen().
Consider a file with name of file as “new.txt” file with the When integer variable c is not equal to EOF, it will
following content. read the file.
This is demo! • It reads a single character from the input and return
This is demo! an integer value. If it fails, it returns EOF.
#include <stdio.h> • The function feof() is used to check the end of file
int main() { after EOF. It tests the end of file indicator. It returns
non-zero value if successful otherwise, zero.
FILE *f = fopen("new.txt", "r");
• Here is the syntax of feof() in C language,
int c = getc(f);
• int feof(FILE *stream)
while (c != EOF)
{
putchar(c);
c = getc(f);
}
fclose(f);
getchar();
return 0;
THANK YOU

All The Best For Exams….

Click For Videos:https://www.youtube.com/VLAcreations

You might also like