CS1CRT02 Methodology of Programming and C Language (Core)
CS1CRT02 Methodology of Programming and C Language (Core)
Module 4
use a popular language. You are also more menu, and can be executed just like a
likely to find reference material and other help. regular program.
• Internal — they are contained inside the
Language-domain match. program itself, so that they can be called by
Select a language that matches your problem the program whenever needed.
domain. You can do this by looking at what
other people in your field are using. Look at PURPOSE OF PROGRAM PLANNING
the code that solves problems that you are Before writing a program, one should know
working on. what is going to be programmed. Problems
are solved using computer programs. A
Availability of libraries Programmer should analyze the problem very
If there's a library that solves your problem well from the beginning to end. He should
well, then it will be helpful to choose the have an idea and design the problem before it
language for your need. implement. Also imagination of the result
should be predicted. Else he would get
Efficiency unpredicted and undesirable output.
Languages compilers should be efficient. Look
at the efficiency of compilers or interpreters Program Life Cycle
for your language. Be aware that interpreted When we want to develop a program using
code will run properly. any programming language, we follow a
sequence of steps. These steps are called
Expressiveness phases in program development. The program
The number of lines of code you create per development life cycle is a set of steps or
hour is not a strong function of language, so phases that are used to develop a program in
favor languages that are expressive or any programming language.
powerful.
Generally, program development life cycle
Tool Support contains 6 phases, they are as follows:
Popularity usually buys tool support. Some
languages are easier to write tools. If you are a • Problem Definition
tool-oriented user, choose a language with • Problem Analysis
good tool support. • Algorithm Development
• Coding & Documentation
SUBPROGRAM • Testing & Debugging
A subprogram is a program called by another • Maintenance
program to perform a particular task or
function for the program. When a task needs
to be performed multiple times, you can make
it into a separate section. The complete
program is thus made up of multiple smaller,
independent subprograms that work together
with the main program.
1. Start
2. Read Num1
3. Read Num2
4. Is (Num1>Num2)?
5. Yes: Print Num1 is Large, GOTO Step 7
6. Else: Print Num2 is Large
7. End
Sequence
Pseudo code
The term pseudo means false. The false codes The sequence structure simply executes a
used to represent the flow of execution of a sequence of statements in the order in which
program is known as pseudo codes. Usually they occur.
programmers use pseudo codes for rough
work on their problem solving. Most probably, Selection
they use pen and papers for their rough
programming work. They should not bother
syntax or semantics of any high-level
programming languages.
CONTROL STRUCTURES
A control structure is a block of programming
that analyzes variables and chooses a direction
in which to go based on given parameters. Any
computer program can be written using the
basic control structures. They can be combined
The basic building blocks of the C Look at the various parts of the above program
programming language has well defined −
program structure as shown below. • The first line of the program #include
<stdio.h> is a preprocessor command,
The documentation section consist of a set of which tells a C compiler to include stdio.h
comment line giving the name of the program, file before going to actual compilation.
author, and other details which the • The next line int main() is the main
programmer would like to use later. The link function where the program execution
section provides instructions to the compiler begins.
to link functions from the system library. The • The next line /*...*/ will be ignored by the
definition section defines all symbolic compiler and it has been put to add
constants. There are some variables and are additional comments in the program. So
declared in the global declaration section that such lines are called comments in the
is outside of all the functions. program.
• The next line printf(...) is another function
Every C program has one main() function available in C which causes the message
section. This section contains two parts, "Hello, World!" to be displayed on the
declaration part and executable part. The screen.
declaration part declares all variables used in • The next line return 0; terminates the
the executable parts. There is at least one main() function and returns the value 0 to
statement in executable part. These two parts the compiler.
must appear between the opening and closing
braces. CHARACTER SET
Character set is a set of alphabets, letters and
The program execution begins at the opening some special characters that are valid in C
brace and ends at the closing brace. The language.
closing brace of the main function section is
the logical end of the program. All statements Alphabets
in the declaration and executable parts end Uppercase: A B C ................................... X Y Z
with a semicolon. Lowercase: a b c ...................................... x y z
The subprogram section contains all the user C accepts both lowercase and uppercase
defined functions that are called in the main alphabets as variables and functions.
function. User defined functions are generally
placed immediately after the main function. Digits
0123456789
Let us look at a simple code that would print
the words "Hello World". Special Characters
Special Characters in C Programming
Example: Hello World , < > . _
( ) ; $ :
#include <stdio.h> % [ ] # ?
int main() ' & { } "
{ ^ ! * / |
/* my first sample program in C */ - \ ~ +
printf("Hello, World! \n");
return 0;
}
c = a*b;
printf("a*b = %d \n",c); Increment and decrement operators
C programming has two operators increment
c=a/b; ++ and decrement -- to change the value of
printf("a/b = %d \n",c); an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas
c=a%b; decrement -- decreases the value by 1. These
printf("Remainder when a divided by b = %d two operators are unary operators, meaning
\n",c); they only operate on a single operand.
C Relational Operators
A relational operator checks the relationship printf("%d >= %d = %d \n", a, b, a >= b);
between two operands. If the relation is true, it //true
returns 1; if the relation is false, it returns value printf("%d >= %d = %d \n", a, c, a >= c);
0. //false
days = (February == '1') ? 29 : 28; • Here, stdio.h is a header file (standard input
output header file) and #include is a
printf("Number of days in February = preprocessor directive to paste the code
%d",days); from the header file when necessary. When
return 0; the compiler encounters printf() function
} and doesn't find stdio.h header file,
compiler shows error.
Output • The return 0; statement is the "Exit status"
If this year is leap year, enter 1. If not enter any of the program. In simple terms, program
integer: 1 ends.
Number of days in February = 29
Example #2: C Integer Output
Module
#include <stdio.h>
INPUT AND OUTPUT IN C int main()
C programming has several in-built library {
functions to perform input and output tasks. int testInteger = 5;
printf("Number = %d", testInteger);
Two commonly used functions for I/O return 0;
(Input/Output) are printf() and scanf(). }
Note the '&' sign before testInteger; Example #5: C ASCII Code
&testInteger gets the address of testInteger #include <stdio.h>
and the value is stored in that address. int main()
{
Example #3: C Floats Input/Output char chr;
#include <stdio.h> printf("Enter a character: ");
int main() scanf("%c",&chr);
{
float f; // When %c text format is used, character is
printf("Enter a number: "); displayed in case of character types
// %f format string is used in case of floats printf("You entered %c.\n",chr);
scanf("%f",&f);
printf("Value = %f", f); // When %d text format is used, integer is
return 0; displayed in case of character types
} printf("ASCII value of %c is %d.", chr, chr);
return 0;
Output }
Enter a number: 23.45
Value = 23.450000 Output
Enter a character: g
The format string "%f" is used to read and You entered g.
display formatted in case of floats. ASCII value of g is 103.
Example #4: C Character I/O The ASCII value of character 'g' is 103. When,
#include <stdio.h> 'g' is entered, 103 is stored in variable var1
int main() instead of g.
{
char chr; You can display a character if you know ASCII
printf("Enter a character: "); code of that character. This is shown by
scanf("%c",&chr); following example.
printf("You entered %c.",chr);
return 0; Example #6: C ASCII Code
} #include <stdio.h>
int main()
Output {
Enter a character: g int chr = 69;
You entered g. printf("Character having ASCII value 69 is
%c.",chr);
Format string %c is used in case of character return 0;
types. }
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When user enters -2, the test expression
(number < 0) becomes true. Hence, You
entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement in C programming is easy. Example #2: C if...else statement
When user enters 5, the test expression // Program to check whether an integer
(number < 0) becomes false and the statement entered by the user is odd or even
inside the body of if is skipped.
#include <stdio.h>
if...else statement int main()
The if...else statement executes some code if {
the test expression is true (nonzero) and some int number;
other code if the test expression is false (0). printf("Enter an integer: ");
scanf("%d",&number);
Syntax of if...else
if (testExpression) { // True if remainder is 0
// codes inside the body of if if( number%2 == 0 )
} printf("%d is an even integer.",number);
else { else
// codes inside the body of else printf("%d is an odd integer.",number);
} return 0;
If test expression is true, codes inside the body }
of if statement is executed and, codes inside
the body of else statement is skipped. Output
If test expression is false, codes inside the body Enter an integer: 7
of else statement is executed and, codes inside 7 is an odd integer.
the body of if statement is skipped. When user enters 7, the test expression (
number%2 == 0 ) is evaluated to false. Hence,
the statement inside the body of else
statement printf("%d is an odd integer"); is
executed and the statement inside the body of
if is skipped.
The nested if...else statement allows you to //checks if number1 is greater than
check for multiple test expressions and number2.
execute different codes for more than two else if (number1 > number2)
conditions. {
printf("Result: %d > %d", number1,
Syntax of nested if...else statement. number2);
if (testExpression1) }
{
// statements to be executed if // if both test expression is false
testExpression1 is true else
} {
else if(testExpression2) printf("Result: %d < %d",number1,
{ number2);
// statements to be executed if }
testExpression1 is false and testExpression2 is
true return 0;
} }
else if (testExpression 3)
{ Output
// statements to be executed if Enter two integers: 12
testExpression1 and testExpression2 is false 23
and testExpression3 is true Result: 12 < 23
}
. switch...case
. The if..else..if ladder allows you to execute a
else block code among many alternatives. If you
{ are checking on the value of a single variable
// statements to be executed if all test in if...else...if, it is better to use switch
expressions are false statement.
}
The switch statement is often faster than
Example #3: C Nested if...else statement nested if...else (not always). Also, the syntax of
// Program to relate two integers using =, > or switch statement is cleaner and easy to
< understand.
case '*':
printf("%.1lf * %.1lf =
%.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf =
%.1lf",firstNumber, secondNumber,
firstNumber/firstNumber);
break;
Loops
Loops are used in programming to repeat a
specific block until some end condition is met.
There are three loops in C programming:
1. for loop Example: for loop
2. while loop // Program to calculate the sum of first n
3. do...while loop natural numbers
// Positive integers 1,2,3...n are known as
for Loop natural numbers
The syntax of for loop is:
for (initializationStatement; testExpression; #include <stdio.h>
updateStatement) int main()
{ {
// codes int num, count, sum = 0;
}
printf("Enter a positive integer: ");
Working of for loop scanf("%d", &num);
The initialization statement is executed only
once. // for loop terminates when n is less than
Then, the test expression is evaluated. If the count
test expression is false (0), for loop is
return 0;
}
Output
Enter an integer: 5
Factorial = 120
do...while loop
The do..while loop is similar to the while loop
Example #2: do...while loop
with one important difference. The body of
// Program to add numbers until user enters
do...while loop is executed once, before
zero
checking the test expression. Hence, the
do...while loop is executed at least once.
#include <stdio.h>
int main()
do...while loop Syntax
{
do
double number, sum = 0;
{
// codes
// loop body is executed at least once
}
do
while (testExpression);
{
printf("Enter a number: ");
Working of do...while loop
scanf("%lf", &number);
The code block (loop body) inside the braces
sum += number;
is executed once.
}
Then, the test expression is evaluated. If the
while(number != 0.0);
test expression is true, the loop body is
executed again. This process goes on until the
printf("Sum = %.2lf",sum);
test expression is evaluated to 0 (false).
When the test expression is false (nonzero),
return 0;
the do...while loop is terminated.
}
Output
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
continue Statement
The continue statement skips some Example #2: continue statement
statements inside the loop. The continue // Program to calculate sum of maximum of 10
statement is used with decision making numbers
statement such as if...else. // Negative numbers are skipped from
calculation
Syntax of continue Statement
continue; # include <stdio.h>
int main()
Flowchart of continue Statement {
int i;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
In the program, when the user enters positive for(i=1; i<=maxInput; ++i)
number, the sum is calculated using sum += {
number; statement. printf("%d. Enter a number: ", i);
When the user enters negative number, the scanf("%lf",&number);
continue statement is executed and skips the
negative number from calculation. // If user enters negative number, flow of
program moves to label jump
goto statement if(number < 0.0)
The goto statement is used to alter the normal goto jump;
sequence of a C program.
sum += number; // sum = sum+number;
Syntax of goto statement }
goto label;
... .. ... jump:
... .. ...
... .. ... average=sum/(i-1);
label: printf("Sum = %.2f\n", sum);
statement; printf("Average = %.2f", average);
The label is an identifier. When goto statement
is encountered, control of the program jumps return 0;
to label: and starts executing the code. }
Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Reasons to avoid goto statement
Example: goto Statement
The use of goto statement may lead to code
that is buggy and hard to follow.
// Program to calculate the sum and average
of maximum of 5 numbers
For example:
one:
for (i = 0; i < number; ++i)
{ Declare An Array
test += i; data_type array_name[array_size];
goto two;
} For example,
two: float mark[5];
if (test > 5) { Here, we declared an array, mark, of floating-
goto three; point type and size 5. Meaning, it can hold 5
} floating-point values.
... .. ...
Elements of an Array and to access them
Also, goto statement allows you to do bad You can access elements of an array by indices.
stuff such as jump out of scope. Suppose you declared an array mark as above.
The first element is mark[0], second element
That being said, goto statement can be useful is mark[1] and so on.
sometimes.
For example: to break from nested loops.
Initialize an Array
It's possible to initialize an array during
declaration.
For example,
int mark[5] = {19, 10, 8, 17, 9};
An array is a collection of data that holds fixed
number of values of same type. Another method to initialize array during
declaration:
For example: if you want to store marks of 100 int mark[] = {19, 10, 8, 17, 9};
students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed
after its declaration.
You can think this example as: Each 2 elements scanf("%d", &temperature[i][j]);
have 4 elements, which makes 8 elements and }
each 8 elements can have 3 elements. Hence, }
the total number of elements is 24.
printf("\nDisplaying values: \n\n");
Initialize a Multidimensional Array for (int i = 0; i < CITY; ++i) {
There is more than one way to initialize a for(int j = 0; j < WEEK; ++j)
multidimensional array. {
printf("City %d, Day %d = %d\n", i+1,
Initialization of a two dimensional array j+1, temperature[i][j]);
// Different ways to initialize two dimensional }
array }
return 0;
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; }
int main()
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18
};
avg = average(age); /* Only name of array is
In C programming, a single array element or passed as argument. */
an entire array can be passed to a function. printf("Average age=%.2f", avg);
This can be done for both one-dimensional return 0;
array or a multi-dimensional array. }
Pointer variables
In C, there is a special variable that stores just
the address of another variable. It is called
Pointers are powerful features of C Pointer variable or, simply, a pointer.
programming that differentiates it from other
popular programming languages like: Java and Declaration of Pointer
Python. data_type* pointer_variable_name;
int* p;
Pointers are used in C program to access the
memory and manipulate the address. Above statement defines, p as pointer variable
of type int.
Address in C Reference operator (&) and Dereference
Before you get into the concept of pointers, operator (*)
let's first get familiar with address in C.
If you have a variable var in your program, As discussed, & is called reference operator.
&var will give you its address in the memory, It gives you the address of a variable.
where & is commonly called the reference Likewise, there is another operator that gets
operator. you the value from the address, it is called a
dereference operator (*).
You must have seen this notation while using Below example clearly demonstrates the use of
scanf() function. It was used in the function to pointers, reference operator and dereference
store the user inputted value in the address of operator.
var.
scanf("%d", &var); Note: The * sign when declaring a pointer is
not a dereference operator. It is just a similar
/* Example to demonstrate use of reference notation that creates a pointer.
operator in C programming. */
Example To Demonstrate Working of
#include <stdio.h> Pointers
int main() /* Source code to demonstrate, handling of
{ pointers in C program */
int var = 5;
printf("Value: %d\n", var); #include <stdio.h>
printf("Address: %u", &var); //Notice, the int main(){
ampersand(&) before var. int* pc;
return 0; int c;
} c=22;
printf("Address of c:%u\n",&c);
Output printf("Value of c:%d\n\n",c);
Value: 5 pc=&c;
Address: 2686778 printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
Note: You may obtain different value of c=11;
address while using this code. printf("Address of pointer pc:%u\n",pc);
C Call by Reference: Using pointers pointers *n1 and *n2 accept those values. So,
now the pointer n1 and n2 points to the
address of num1 and num2 respectively.
These functions are defined in the header file. When the compiler encounters
When you include the header file, these functionName(); inside the main function,
functions are available for use. control of the program jumps to
void functionName()
For example: And, the compiler starts executing the codes
The printf() is a standard library function to inside the user-defined function.
send formatted output to the screen (display
output on the screen). This function is defined The control of the program jumps to
in "stdio.h" header file. statement next to functionName(); once all the
codes inside the function definition are
There are other numerous library functions executed.
defined under "stdio.h", such as scanf(),
fprintf(), getchar() etc. Once you include
"stdio.h" in your program, all these functions
are available for use.
User-defined functions
C allow programmers to define functions. Such
functions created by the user are called user-
defined functions.
C allows you to define functions according to parameters and return type. It doesn't contain
your need. These functions are known as user- function body.
defined functions.
A function prototype gives information to the
compiler that the function may later be used
For example: in the program.
Suppose, you need to create a circle and color
it depending upon the radius and color. You
can create two functions to solve this problem: Syntax of function prototype
• createCircle() function returnType functionName(type1 arg1,
• color() function type2 argt2,...);
For example,
return a;
return (a+b);
Then, the appropriate message is displayed Example: Sum of Natural Numbers Using
from the main() function. Recursion
Local Variable
The variables declared inside the function are
automatic or local variables.
The local variables exist only inside the
function in which it is declared. When the
function exits, the local variables are
destroyed.
int main() {
int n; // n is a local variable to main()
function
... .. ...
}
void func() {
int n1; // n1 is local to func() function
}
Global Variable
Variables that are declared outside of all
Advantages and Disadvantages of
functions are known as external variables.
Recursion
External or global variables are accessible to
Recursion makes program elegant and
any function.
cleaner. All algorithms can be defined
recursively which makes it easier to visualize
Example #1: External Variable
and prove.
#include <stdio.h>
void display();
If the speed of the program is vital then, you
should avoid using recursion. Recursions use
int n = 5; // global variable
more memory and are generally slow. Instead,
you can use loop.
int main()
{
Scope and Lifetime of a variable
++n; // variable n is not declared in the
Every variable in C programming has two
main() function
properties: type and storage class.
display();
return 0;
Type refers to the data type of a variable. And,
}
storage class determines the scope and
lifetime of a variable.
void display()
There are 4 types of storage class:
{
1. automatic
++n; // variable n is not declared in the
2. external
display() function
3. static
printf("n = %d", n);
4. register
}
Output Output
n=7 0 5
Suppose, a global variable is declared in file1. During the first function call, the value of c is
If you try to use that variable in a different file equal to 0. Then, it's value is increased by 5.
file2, the compiler will complain. To solve this
problem, keyword extern is used in file2 to During the second function call, variable c is
indicate that the external variable is declared not initialized to 0 again. It's because c is a
in another file. static variable. So, 5 is displayed on the screen.
Unless you are working on embedded system However, in the future, you would want to
where you know how to optimize code for the store information about multiple persons.
given application, there is no use of register Now, you'd need to create different variables
variables. for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2
Static Variable
A static variable is declared by using keyword You can easily visualize how big and messy the
static. For example; code would look. Also, since no relation
static int i; between the variables (information) would
The value of a static variable persists until the exist, it's going to be a daunting task.
end of the program.
A better approach will be to have a collection
Example #2: Static Variable of all related information under a single name
#include <stdio.h> Person, and use it for every person. Now, the
void display(); code looks much cleaner, readable and
efficient as well.
int main() This collection of all related information under
{ a single name Person is a structure.
display();
display(); Structure Definition in C
} Keyword struct is used for creating a structure.
void display()
{ Syntax of structure
static int c = 0; struct structure_name
printf("%d ",c); {
c += 5; data_type member1;
} data_type member2;
.
// function prototype should be below to the void add(struct distance d1,struct distance d2,
structure declaration otherwise compiler struct distance *d3);
shows error
int main()
int main() {
{ struct distance dist1, dist2, dist3;
struct student stud;
printf("Enter student's name: "); printf("First distance\n");
scanf("%s", &stud.name); printf("Enter feet: ");
printf("Enter roll number:"); scanf("%d", &dist1.feet);
scanf("%d", &stud.roll); printf("Enter inch: ");
display(stud); // passing structure variable scanf("%f", &dist1.inch);
stud as argument
return 0; printf("Second distance\n");
} printf("Enter feet: ");
scanf("%d", &dist2.feet);
void display(struct student stu){ printf("Enter inch: ");
printf("Output\nName: %s",stu.name); scanf("%f", &dist2.inch);
printf("\nRoll: %d",stu.roll);
} add(dist1, dist2, &dist3);
C program to add two distances (feet-inch if (d3->inch >= 12) { /* if inch is greater
system) and display the result without the or equal to 12, converting it to feet. */
return statement. d3->inch -= 12;
++d3->feet;
#include <stdio.h> }
struct distance }
{
int feet; Output
float inch; First distance
}; Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5 1. Referencing pointer to another address to
Enter inch: 7.5 access the memory
Consider an example to access structure's
Sum of distances = 18'-2.3" member through pointer.
Here, the pointer variable of type struct name Using -> operator to access structure
is created. pointer member
Structure pointer member can also be
Accessing structure's member through accessed using -> operator.
pointer (*personPtr).age is same as personPtr->age
A structure's member can be accesssed (*personPtr).weight is same as personPtr-
through pointer in two ways: >weight
1. Referencing pointer to another address
to access memory
2. Using dynamic memory allocation
return 0;
2. Accessing structure member through }
pointer using dynamic memory allocation
To access structure member using pointers, Output
memory can be allocated dynamically using Enter number of persons: 2
malloc() function defined under "stdlib.h" Enter name, age and weight of the person
header file. respectively:
Syntax to use malloc() Adam
ptr = (cast-type*) malloc(byte-size) 2
3.2
Example to use structure's member Enter name, age and weight of the person
through pointer using malloc() function. respectively:
Eve
#include <stdio.h> 6
#include <stdlib.h> 2.3
struct person { Displaying Information:
int age; Adam 2 3.20
float weight; Eve 6 2.30
char name[30];
}; Pass structure to a function
In C, structure can be passed to functions by
int main() two methods:
{ 1. Passing by value (passing actual value
struct person *ptr; as argument)
int i, num; 2. Passing by reference (passing address
of an argument)
printf("Enter number of persons: ");
scanf("%d", &num); Passing structure by value
A structure variable can be passed to the
ptr = (struct person*) malloc(num * function as an argument as a normal variable.
sizeof(struct person));
// Above statement allocates the memory for If structure is passed by value, changes made
n structures with pointer personPtr pointing to to the structure variable inside the function
base address */ definition does not reflect in the originally
passed structure variable.
for(i = 0; i < num; ++i) C program to create a structure student,
{ containing name and roll and display the
printf("Enter name, age and weight of the information.
person respectively:\n");
scanf("%s%d%f", &(ptr+i)->name, #include <stdio.h>
&(ptr+i)->age, &(ptr+i)->weight); struct student
} {
char name[50];
printf("Displaying Infromation:\n"); int roll;
for(i = 0; i < num; ++i) };
printf("%s\t%d\t%.2f\n", (ptr+i)->name,
(ptr+i)->age, (ptr+i)->weight); void display(struct student stu);
But, dist3 is passed by reference ,i.e, address of In both cases, union variables car1, car2 and
dist3 (&dist3) is passed as an argument. union pointer variable car3 of type union car
Due to this, the structure pointer variable d3 is created.
inside the add function points to the address
of dist3 from the calling main function. So, any Accessing members of a union
change made to the d3 variable is seen in dist3 Again, the member of unions can be accessed
variable in main function. in similar manner as structures.
As a result, the correct sum is displayed in the In the above example, suppose you want to
output. access price for union variable car1, it can be
accessed as:
Unions car1.price
Unions are quite similar to structures in C. Like Likewise, if you want to access price for the
structures, unions are also derived types. union pointer variable car3, it can be accessed
as:
union car (*car3).price
{ or;
char name[50]; car3->price
int price;
}; Difference between union and structure
Though unions are similar to structure in so
Defining a union is as easy as replacing the many ways, the difference between them is
keyword struct with the keyword union. crucial to understand.
After you compile and run this program, you Writing to a binary file
can see a text file program.txt created in C To write into a binary file, you need to use the
drive of your computer. When you open the function fwrite(). The functions takes four
file, you can see the integer you entered. arguments: Address of data to be written in
disk, Size of data to be written in disk, number
Reading from a text file of such type of data and pointer to the file
Example 2: Read from a text file using where you want to write.
fscanf()
fwrite(address_data, size_data,
#include <stdio.h> numbers_data, pointer_to_file);
int main()
{ Example 3: Writing to a binary file using
int num; fwrite()
FILE *fptr;
#include <stdio.h>
if ((fptr = fopen("C:\\program.txt","r")) ==
NULL){ struct threeNum
printf("Error! opening file"); {
5. Programs based on Pointers, operations on 12. Find the Largest Number among Three
pointers, Arrays & Pointers, Numbers Entered by User
6. Programs based on functions, Call by value, 13. Find all Roots of a Quadratic equation
Call by reference, Recursion, 14. Check Whether the Entered Year is Leap
7. Programs based on structure and union, Year or not
array of structures, Pointer to structure, 15. Check Whether a Number is Positive or
structure and functions Negative or Zero.
8. Simple programs using pointers and 16. Checker Whether a Character is an
malloc(). Alphabet or not
17. Find Sum of Natural Numbers
Scheme of Evaluation for software lab I 18. Find Factorial of a Number
external is as follows: 19. Generate Multiplication Table
20. Display Fibonacci Series
Division of Marks (Practical - 3 hours 21. Find HCF of two Numbers
External) 22. Find LCM of two numbers entered by user
23. Count Number of Digits of an Integer
First program from part 1& 2 – 25 marks 24. Reverse a Number
1. Flowchart – 5 marks 25. Calculate the Power of a Number
2. Logic – 10 marks 26. Check Whether a Number is Palindrome or
3. Successful compilation – 5 marks Not
4. Result – 5 marks 27. Check Whether an Integer is Prime or Not
28. Display Prime Numbers Between Two
Second program should be based on Intervals
advanced concepts, part 3 to part 8 29. Check Armstrong Number
– 35 marks 30. Display Armstrong Number between Two
1. Logic – 20 marks Intervals
2. Successful compilation – 10 marks 31. Display Factors of a Number
3. Result – 5 marks 32. Print Pyramids and Triangles in C
Viva Voce – 10 marks programming using Loops
Lab Record (min 25 Programs) – 10 marks 33. Make a Simple Calculator to Add, Subtract,
Total Marks – 80 marks Multiply or Divide Using switch...case
34. Find the Frequency of Characters in a String
Lab Cycle 35. Find the Number of Vowels, Consonants,
1. Print a Sentence Digits and White space in a String
2. Print an Integer Entered by a User 36. Reverse a String by Passing it to Function
3. Add Two Integers Entered by User 37. Find the Length of a String
4. Multiply two Floating Point Numbers 38. Concatenate Two Strings
5. Find ASCII Value of Character Entered by 39. Copy a String
User 40. Remove all Characters in a String except
6. Find Quotient and Remainder of Two alphabet
Integers Entered by User 41. Sort Elements in Lexicographical Order
7. Find Size of int, float, double and char of (Dictionary Order)
your System 42. Change Decimal to Hexadecimal Number
8. Demonstrate the Working of Keyword long and Vice Versa
9. Swap Two numbers Entered by User 43. Convert Hexadecimal to Octal and Vice
10. Check Whether a Number is Even or Odd Versa
11. Check Whether a Character is Vowel or 44. Convert Binary Number to Hexadecimal
consonant Vice Versa
45. Find Largest Number Using Dynamic 73. Calculate Difference Between Two Time
Memory Allocation Period
46. Store Information Using Structures with 74. Store Information of 10 Students Using
Dynamically Memory Allocation Structure
47. Calculate Average Using Arrays 75. Store Information Using Structures for n
48. Find Largest Element of an Array Elements Dynamically
49. Calculate Standard Deviation
50. Add Two Matrix Using Multi-dimensional
Arrays
51. Multiply to Matrix Using Multi-dimensional
Arrays
52. Find Transpose of a Matrix
53. Check a matrix symmetric or not.
54. Multiply two Matrices by Passing Matrix to
Function
55. Sort Elements of an Array
56. Access Elements of an Array Using Pointer
57. Swap Numbers in Cyclic Order Using Call
by Reference
58. Find Largest Number Using Dynamic
Memory Allocation
59. Display all prime numbers between two
Intervals
60. Check Prime and Armstrong Number by
making function
61. Check whether a number can be expressed
as the sum of two prime number
62. Find sum of natural numbers using
recursion
63. Calculate factorial of a number using
recursion
64. Find G.C.D using recursion
65. Reverse a sentence using recursion
66. Calculate the power of a number using
recursion
67. Convert binary number to decimal and
vice-versa
68. Convert octal Number to decimal and vice-
versa
69. Convert binary number to octal and vice-
versa
70. Store Information(name, roll and marks) of
a Student Using Structure
71. Add Two Distances (in inch-feet) System
Using Structures
72. Add Two Complex Numbers by Passing
Structure to a Function