Introduction To C Programming Notes PDF
Introduction To C Programming Notes PDF
Introduction To C Programming Notes PDF
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
INTRODUCTION TO C
PROGRAMMING
Department: Electrical and Electronics Engineering
Batch/Year: 2017-2021/IV
Created by: VIBITH A S
Date: 13.07.2020
Table of Contents
Course Objectives
Syllabus
Course Outcomes (Cos)
CO-PO Mapping
??== for each unit
Lecture Plan
Activity based learning
Lecture notes
Assignments
Part A Q&A
Part B Qs
List of Supportive online Certification courses
Real time applications in day to day life and to industry
Contents beyond Syllabus
??====
Assessment Schedule (proposed and actual date)
Prescribed Text Books & Reference Books
Mini Project Suggestions
Course Objectives
OCS752 INTRODUCTION TO C PROGRAMMING LTPC
3003
OBJECTIVES
CO2 PO1 3 Identify the data type and operators to solve the problem
CO2 PO3 2 Recognize the need of basic data types and operators
CO2 PO5 2 Apply control flow statement for solving the problem
CO3 PO3 3 Apply the knowledge to find the possible code for function
CO4 PO5 2 Design and Develop program using the selected compound data
Learn by questioning
Structure of C Program
A C program is divided into different sections. There are six main sections to
a basic c program.
Link Section
This part of the code is used to declare all the header files that will be used in
the program. This leads to the compiler being told to link the header files to the
system libraries.
Definition Section
In this section, we define different constants. The keyword define is used in this
part.
Example:
This part of the code, where the global variables are declared. All the global
variable used are declared in this part. The user-defined functions are also
declared in this part of the code.
Example:
float a (float rd);
int x;
All the user-defined functions are defined in this section of the program.
Example:
int sum (int x, int y)
{
Return x+y;
}
Sample Program
https://www.youtube.com/watch?v=bS6uNMmIoQ0
Constants:
Constants are identifiers whose value does not change.
#define PI 3.14159
#define service_tax 0.12
Variables:
A variable is defined as a meaningful name given to the data storage
location
in computer memory. C language supports two basic kinds of variables
Numeric Variable
Character Variable
Numeric Variable:
Numeric variable can be used to store either integer value or floating point
values. While an integer value is a whole number without a fraction part or
decimal point a floating point value can have a decimal point.
Numeric variables may also be associated with modifiers like short,
long, signed, and unsigned. The difference between signed and unsigned numeric
variable is that signed variable can be either negative or positive but unsigned
variables can only be positive.
Character Variable:
Character variable can include any letter from the alphabet or from
the ASCII chart and numbers 0 – 9 that are given with in single quotes.
Example:
int emp_num;
float salary;
double balance;
In C variable are declared at three basic places as follows
When a variable is declared inside a function it is known as a local variable.
When a variable is declared in the definition of function parameter it is known
as formal parameter.
When the variable is declared outside all functions, it is known as a global
variable.
Keywords:
Operators
Arithmetic Operators
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Division A/B
% Modulus A%B
#include<stdio.h>
#include<conio.h>
void main() Output:
{ a++ = 11
int a = 10, b=3; b-- = 2
printf("a++ = ", (a ++) );
printf("a - - = " , (a - -) );
}
Relational Operators
Relational operators are used to test condition and results true or false
value, The following table lists relational operators
#include<stdio.h>
#include<conio.h>
void main() Output:
{ a == b = false
int a = 10, b=20; a != b = true
printf("a= = b=", (a ==b) ); a > b = false
printf("a !=b= " , (a!=b) ); a < b = true
printf(“a>b=”,(a>b)); b >= a = true
printf(“a>=b=”,(a>=b)); b <= a = false
printf(“a<b=”,(a<b));
printf(“a<=b=”,(a<=b))
}
Logical Operators
Logical operators are used to combine more than one condition.
The following table lists logical operators
Example
#include<stdio.h> Output:
void main() a && b = false
{ a || b = true
boolean a = true; !(a && b) = true
boolean b = false;
printf("a && b = " + (a&&b) );
printf("a || b = " + (a||b) );
printf("!(a && b) = " + !(a && b) );
}
Assignment Operator
Simple Assignment
=, assigns right hand side value to left hand side variable
Ex:
int a;
a = 10;
Compound Assignment
+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=, assigns right
hand side value after the computation to left hand side variable
Ex:
int a;
int b;
a += 10; // means a = a + 10;
a &= b; // means a = a & b;
Bitwise Operators
Bitwise operator act on integral operands and perform binary operations. The
lists of bitwise operators are
Bitwise AND
The & operator compares corresponding bits between two numbers and if
both the bits are 1, only then the resultant bit is 1. If either one of the bits
is 0, then the resultant bit is 0. 5-> 0101
9-> 1001
Example : 0001
int x = 5; int y = 9; x & y = 1
Bitwise OR
The | operator will set the resulting bit to 1 if either one of them is 1.
It will return 0 only if both the bits are 0.
Example :
int x = 5; 5-> 0101
int y = 9; 9-> 1001
x | y = 13 1101
Bitwise EXOR
The ^ operator compares two bits to check whether these bits are
different. If they are different, the result is 1.Otherwise, the result is 0.
This operator is also known as XOR operator.
Example :
int x = 5; 5-> 0101
int y = 9; 9-> 1001
x | y = 12
1110
#include<stdio.h>
void main()
{
int x = 5;
int y = 9; Output:
int a = x & y; int b = x | y; int c = x ^ y; x&y=1
printf("x & y = "+a); x | y = 13
printf(" x | y = "+b); x ^ y = 12
printf("x ^ y = "+c);
}
Bitwise NOT
5 -> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
~5 - > 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0
Shift Operators
The shift operators (<< and >>) shift the bits of a number to the left
or right, resulting in a new number. They are used only on integral
numbers (and not on floating point numbers, i.e. decimals).
Shift Right
When we apply >> which is the right shift operator, bit represented by 1 moves by
the positions to the right (represented by the 3 right shift operator). After
number after the binary digit 1, we will get : shifting
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
x=2
Shift Left
Eg.
int x = 8;
x = x << 4;
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
When we apply << which is the left shift operator, bit represented by1 moves by
the positions to the left (represented by the number right shift 4 After
after the binary digit 1, we will get : operator). shifting
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
X=128
#include<stdio.h>
Output:
Void main() The original value of x is 8
{ After using << 2, the new value is 2
After using >> 4, the new value is 128
int x =8;
printf("The original value of x is “,x);
printf("After using << 2, the new value is “,x << 2);
printf("After using >> 4, the new value is “, x >> 4);
}
Precedence and Associativity
()
++ —
++ — =
+– < < += -=
!~ = *= /=
(type > > left-to-right | left-to-right %= &
) right-to-left = =
* ^= |=
& <<=
sizeof >>= right-to-left
==
% left-to-right left-to-right
,
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input
and to display data on screen when there is a need to output the result.
Streams
A stream act in two ways. It is the source of data as well as the
destination of the data. C programs input and output data from a stream. It is
associated with a physical devices such as the monitor or with a file stored on the
secondary memory. C use two forms of streams Text and Binary.
We can do input/output from the keyboard from any file. Consider input of data is
the keyboard and output data is the monitor.
#include<stdio.h>
#include<conio.h>
void main()
{
float i;
printf(“Enter the value”);
scanf(“%f”,&i);
printf(“The value is %f=“,i);
getch();
}
The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. The putchar() function displays the
character passed to it on the screen and returns the same character.
#include<stdio.h>
void main()
{
char q;
Printf(“Enter a Character”);
q=getchar();
putchar(q);
}
Assignment Statement
An assignment statement sets the value stored in the storage location denoted by
a variable_name. In other words, it copies a value into the variable.
Syntax:
variable = expression;
Simple if
syntax :
if(Booleanexpressio)
{
statement–block;
}
Next statement;
#includ<stdio.h>
void main()
{
int n=5;
if(n<25)
{
printf(“This is if statement”); Output:
} This is if statement
}
if .. else statement
Syntax
if(boolean expression)
{
True-block statements;
}
else
{
False-block statements;
}
Next statement;
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age”);
scanf(%d”,&age);
if(age>18)
{
printf(“Eligible to vote”);
}
else
{
printf(“Not eligible to vote”);
}
}
Cascading if..else
Syntax:
if (condition1)
{
statement-1
}
….
else if(conditio-n)
{
statement-n
}
else
{
default statement
}
next statement
#include<stdio.h>
void main()
{
int n1,n2,n3;
printf(“Enter the number”);
scanf(“%d%d%d”,&n1,&n2,&n3);
if(n1>n2 && n1>n3)
{
printf(“%d is largest number”,n1);
}
else If(n2>n3)
{
printf(“%d is the largest number”,n2);
}
else
{
printf(“%d is the largest number”,n3);
}
}
Switch Statement
The switch-case conditional construct is a more structured way of testing
for multiple conditions rather than resorting to a multiple if statement
Syntax:
switch(expression)
{
case 1: case 1 block
break;
case 2: case 2 block
break;
default: default block;
break;
}
statement;
#include<stdio.h>
Void main()
{
int w;
printf(“Enter the week”);
scanf(“%d”,&w);
switch(w)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);
break;
Default:
Printf(“Invalid input please enter number between (1 – 7)”);
}
}
Looping Statement
for Loop
The for loop initialize the value before the first step. Then checking the
condition against the current value of variable and execute the loop statement
and then perform the step taken for each execution of loop body. For-loops
are also typically used when the number of iterations is known before entering
the loop.
Syntax
#include<stdio.h>
void main()
{ Output:
int i; i: 1
for(i=0;i<=5;i++) i: 2
{ i: 3
printf(“i:”,i); i: 4
} i: 5
While Loop
It‟s a entry controlled loop, the condition in the while loop is evaluated,
and if the condition is true, the code within the block is executed. This
repeats until the condition becomes false
Syntax
while(condition)
{
Body of the loop
}
#include<stdio.h>
void main()
{
int i = 0; Output:
while (i < 5) i: 0
{ I: 1
printf("i: “,i); i: 2
i = i + 1; i: 3
} i: 4
}
do.. while Loop
It‟s a exit controlled loop, the body of the loop gets executed first
followed by checking the condition. Continues with the body if the condition is
true, else loops gets terminated.
Syntax
do
{
body of the loop
}
while(Boolean expression);
#include<stdio.h>
void main()
{
int i=5;
do
{
println("i: “,i);
i = i + 1;
}
while (i < 5);
}
Output:
I: 5
Pre-processor Directives
This preprocessor is a macro processor this is used automatically by the C
compiler to transform your program before actual compilation. It is called macro
processor because it allows you to define macros, which are brief abbreviations of
longer constructs. A macro is a segment of code which is replaced by the value of
macro. Macro is defined by #define directive.
Preprocessing directives are lines in your program that start with #. The # is
followed by an identifier that is the directive name. For example, #define is the
directive that defines a macro. Whitespace is also allowed before and after the #.
The # and the directive name cannot come from a macro expansion. For
example, if foo is defined as a macro expanding to define, that does not make #foo a
valid preprocessing directive.
#include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma
#include
The #include preprocessor directive is used to paste code of given file into
current file. It is used include system-defined and user-defined header files.
#define
Syntax:
#define token value
#undef
#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it
executes the code.
Syntax:
#ifdef MACRO
//code
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code.
Syntax:
#ifndef MACRO
//code
#endif
#if
The #if preprocessor directive evaluates the expression or condition. If condition is
true, it executes the code
Syntax:
#if expression
//code
#endif
#else
The #else preprocessor directive evaluates the expression or condition if condition
of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
#if
//code
#else
//else code
#endif
#error
The #error preprocessor directive indicates error. The compiler gives fatal error
if #error directive is found and skips further compilation process.
#include<stdio.h>
#ifndef _MATH_
#error First include then compile
#else
void main()
{
int a;
a=sqrt(9);
printf(“%f”,a);
}
#endif
#pragma
The #pragma preprocessor directive is used to provide additional information to the
compiler. The #pragma directive is used by the compiler to offer machine or operating-
system feature. Different compilers can provide different usage of #pragma directive.
Syntax:
#pragma token
Compilation Process:
The compilation is a process of converting the source code into object code. It is
done with the help of the compiler. The compiler checks the source code for the
syntactical or structural errors, and if the source code is error-free, then it generates
the object code.
The c compilation process converts the source code taken as input into the object
code or machine code. The compilation process can be divided into four steps, i.e.,
Pre-processing, Compiling, Assembling, and Linking.
Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed
to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the
pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the
object file generated by the assembler is the same as the source file. The extension of
the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source
file is ‘welcome.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension.
The main working of the linker is to combine the object code of library files with the
object code of our program. Sometimes the situation arises when our program refers to
the functions defined in other files; then linker plays a very important role in this. It links
the object code of these files to our program. Therefore, we conclude that the job of the
linker is to link the object code of our program with the object code of the library files
and other files. The output of the linker is the executable file. The name of the
executable file is the same as the source file but differs only in their extensions. In DOS,
the extension of the executable file is '.exe', and in UNIX, the executable file can be
named as 'a.out'. For example, if we are using printf() function in a program, then the
linker adds its associated code in an output file.
Exercise:
Check whether the required amount can be withdrawn based on
the available amount
#include <stdio.h>
unsigned long amount=1000, deposit, withdraw;
int ch, pin, l;
char transaction ='y';
void main()
{
while (pin != 9090)
{
printf("ENTER YOUR SECRET PIN NUMBER:");
scanf("%d", &pin);
if (pin != 9090)
printf("PLEASE ENTER VALID PASSWORD\n");
}
do
{
printf("********Welcome to ATM Service**************\n");
printf("1. Check Balance\n");
printf("2. Withdraw Cash\n");
printf("3. Deposit Cash\n");
printf("4. Quit\n");
printf("*********************************************?*\n\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n YOUR BALANCE IN Rs : %lu ", amount);
break;
case 2:
printf("\n ENTER THE AMOUNT TO WITHDRAW: ");
scanf("%lu", &withdraw);
if (withdraw % 100 != 0)
{
printf("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
}
else if (withdraw >(amount - 500))
{
printf("\n INSUFFICENT BALANCE");
}
else
{
amount = amount - withdraw;
printf("\n\n PLEASE COLLECT CASH");
printf("\n YOUR CURRENT BALANCE IS%lu", amount);
}
break;
case 3:
printf("\n ENTER THE AMOUNT TO DEPOSIT");
scanf("%lu", &deposit);
amount = amount + deposit;
printf("YOUR BALANCE IS %lu", amount);
break;
case 4:
printf("\n THANK U USING ATM");
break;
default:
printf("\n INVALID CHOICE");
}
printf("\n\n\n DO U WANT TO CONTINUE?(y/n): \n");
flush(stdin);
scanf("%c", &transaction);
if (transaction == 'n'|| transaction == 'N')
l = 1;
}
while (!l);
printf("\n\n THANKS FOR USING OUT ATM SERVICE");
}
#include <stdio.h>
void main ()
{
int ch,rad,length,width,breadth,height;
float area;
printf("Input 1 for area of circle\n");
printf("Input 2 for area of rectangle\n");
printf("Input 3 for area of triangle\n");
printf("Input your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Input radius of the circle : ");
scanf("%d",&rad);
area=3.14*rad*rad;
break;
case 2:
printf("Input length and width of the rectangle : ");
scanf("%d%d",&length,&width);
area=length*width;
break;
case 3:
printf("Input the base and height of the triangle :");
scanf("%d%d",&breadth,&height);
area=.5*breadth*height;
break;
}
printf("The area is : %f\n",area);
}
#include <stdio.h>
void main()
{
int i, x, sum=0;
/* Input upper limit from user */
printf("Enter upper limit: ");
scanf("%d", &x);
for(i=2; i<=x; i+=2)
{
/* Add current even number to sum */
sum = sum+i;
}
printf("Sum of all even number between 1 to %d = %d", x, sum);
}
Assignment
Unit I
Assignment Questions
CO 1 Develop C program solutions to simple computational problems
1. Write a C program to check whether the number is palindrome number or not K2 CO1
a palindrome number.
Test Data :
Input a three digit number : 121
Expected Output :
The given number is :
121
The given number is palindrome number
Test Data :
Input the given number :5
Expected Output :
The factorial of a given number is : 120
Part A
Question & Answer
PART A QUESTION & ANSWERS
printf(): The printf() function is used to print the integer, character, float and string
values on to the screen.
scanf(): The scanf() function is used to take input from the user.
The typecasting is a process of converting one data type into another is known as
typecasting. If we want to store the floating type value to an int type, then we will
convert the data type into another data type explicitly.
(type-name) expression
10. What is the difference between variable declaration and variable definition?
(CO1)(K2)
Declaration associates type to the variable whereas definition gives the value to the
variable.
11. What are global variable and how do you declare them? (CO1)(K1)
Global variables are variables that can be accessed and manipulated anywhere in the
program. To make a variable global, place the variable declaration on the upper
portion of the program, just after the pre_processor directives section.
12. What is local variable in C (CO1)(K2)
· The variables which are having scope/life only within the function are called local
variables.
· These variables are declared within the function and can‟t be accessed outside the
function.
Order of precedence determines which operation must first take place in an operation
statement or conditional statement. On the top most level of precedence are the
unary operators !, +, – and &. It is followed by the regular mathematical operators
(*, / and modulus % first, followed by + and -). Next in line are the relational
operators <, <=, >= and >. This is then followed by the two equality operators ==
and !=. The logical operators && and || are next evaluated. On the last level is the
assignment operator =.
17. What is the difference between pre-increment operator and post increment
operator? (CO1)(K2)
Pre increment operator is used to increment variable value by 1 before
assigning the value to the variable.
Post increment operator is used to increment variable value by 1 after assigning
the value to the variable.
18. What are all decision control statement in C? (CO1)(K2)
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
19. What will happen if break statement is not used in switch case in C? (CO1)(K2)
Switch case statements are used to execute only specific case statements
based on the switch expression.
If we do not use break statement at the end of each case, program will execute
all consecutive case statements until it finds next break statement or till the
end of switch case block.
NPTEL
Problem solving through Programming in C
https://nptel.ac.in/courses/106/105/106105171/
Coursera
1)C for Everyone: Structured Programming
https://www.coursera.org/learn/c-structured-programming
2) C for Everyone: Programming Fundamentals
https://www.coursera.org/learn/c-for-everyone
Real time Applications
Unit I
Real-Time implementation in C programming
1. Operating Systems
2. Development of New Language
3. Computation Platforms
4. Embedded Systems
5. Graphics and Games
Content beyond syllabus
Unit I
Content beyond syllabus
Problem Solving and Algorithms
Learn a basic process for developing a solution to a problem. This process can
be used to solve a wide variety of problems.
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
OCS752
INTRODUCTION TO C
PROGRAMMING
Department: : Electrical and Electronics Engineering
Batch/Year: 2017-2021
Created by: Dr. S. Meenakshi
Date: 13-07-2020
Table of Contents
Course Objectives
Syllabus
Course Outcomes (Cos)
CO-PO Mapping
Lecture Plan
Activity based learning
Lecture notes
Assignments
Part A Q&A
Part B Qs
List of Supportive online Certification courses
Real time applications in day to day life and to industry
Contents beyond Syllabus
Assessment Schedule (proposed and actual date)
Prescribed Text Books & Reference Books
Mini Project Suggestions
Course Objectives
OCS752 INTRODUCTION TO C PROGRAMMING LTPC
3003
OBJECTIVES
CO2 PO1 3 Identify the data type and operators to solve the problem
CO2 PO3 2 Recognize the need of basic data types and operators
CO2 PO5 2 Apply control flow statement for solving the problem
CO3 PO3 3 Apply the knowledge to find the possible code for function
CO4 PO5 2 Design and Develop program using the selected compound data
Learn by questioning
This will reserve 1000 contiguous memory locations for storing the students’ marks.
Graphically, this can be depicted as in the following figure.
Compared to the basic data type (int, float, char and double) it is an aggregate or
derived data type.
Can you imagine how long we have to write the declaration part by using normal
variable declaration?
int main(void){
int studMark1, studMark2, studMark3, studMark4, …, …,
studMark998, stuMark999, studMark1000;
…
…
return 0;}
This absolutely has simplified our declaration of the variables.
We can use index or subscript to identify each element or
location in the memory.
char cName[30];
Note that the index runs from 0 to 29. In C, an index always starts from 0 and ends
with array's (size-1).
So, take note the difference between the array size and subscript/index terms.
Examples of the one-dimensional array declarations,
The first example declares two arrays named xNum and yNum of type int. Array
xNum can store up to 20 integer numbers while yNum can store up to 50 numbers.
The second line declares the array fPrice of type float. It can store up to 10
floating-point values, fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
The third line declares the array chLetter of type char. It can store a string up to 69
characters.
Note: Why 69 instead of 70? Remember, a string has a null terminating character
(\0) at the end, so we must reserve for it.
Initialization of an array
An array may be initialized at the time of declaration.
Giving initial values to an array.
Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
The first line declares an integer array idNum and it immediately assigns the values
1, 2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.
The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1], and
so on.
Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1],
and so on.
Note: again, for characters we must use the single apostrophe/quote (') to enclose
them.
Also, the last character in chVowel is NULL character ('\0').
Initialization of an array of type char for holding strings may take the following form,
For example, the array chVowel in the previous example could have been written
more compactly as follows,
When the value assigned to a character array is a string (which must be enclosed in
double quotes), the compiler automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.
For unsized array (variable sized), we can declare as follow,
C compiler automatically creates an array which is big enough to hold all the
initializer.
To access all the elements of the array, you must use a loop. That is, we can access
.
all the elements of the array by varying the value of the subscript into the array. But
note that the subscript must be an integral value or an expression that evaluates to
an integral value. int i, marks[10];
for(i=0;i<10;i++)
marks[i] = -1;
99 67 78 56 88 90 34 85
Marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7]
1000 1002 1004 1006 1008 1010 1012 1014
99 67 78 56 88 90 34 85
Marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7]]
for(i=0;i<n;i++)
{ OUTPUT:
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("arr[%d] = %d\t", i, arr[i]);
return 0;
}
Arrays allow programmers to group related items of the same data type in one
variable. However, when referring to an array, one has to specify not only the array
or variable name but also the index number of interest.
Program example 2: Sum of array’s elements
// finding sum of array's element
#include <stdio.h>
// replace every nSize occurrences with 10
#define nSize 10
int main(void){
int iCount, nSum = 0, iNum[nSize] = {6,4,2,3,5,10,12};
for
. (iCount=0; iCount<nSize; iCount++) {
// display the array contents
printf("%d ",iNum[iCount]);
// do the summing up
nSum = nSum + iNum[iCount];
}
// display the sum
printf("\nSum of %d numbers is = %d\n", iCount, nSum); OUTPUT:
return 0;
}
#include <stdio.h>
void main()
{
int list[10];
int n;
int i, neg=0, zero=0, pos=0;
printf("\n enter the size of the list\n");
scanf("%d",&n);
printf("Enter the elements one by one");
for(i=0;i<n;i++)
{
printf("\n Enter number %d number",i); OUTPUT:
scanf("%d", &list[i]);
}
for(i=0;i<n;i++)
{
if(list[i]<0)
neg=neg+1;
else
if(list[i]==0)
zero=zero+1;
else
pos=pos+1;
}
printf("No of Negative numbers in given list are %d", neg);
printf("No of Zeros in given list are %d", zero);
printf("No of Positive numbers in given list are %d", pos);
}
2) Selection
An array allows selection of an element for given index.
Array is called as random access data structure.
Algorithm:
Step 1: enter size of the list
Step 2: enter the merit list one by one
Step 3: get into menu of two choice 1-querya and 2. quit
Step 4: get the pos value and find the value in that pos value
Step 5. print that value
#include<stdio.h>
#include<conio.h>
void main()
{
float merit[10];
int size,i,pos,choice;
float percentage;
printf("\n Enter the size of the list");
scanf("%d", &size);
printf("\n Enter the merit list one by one");
for(i=0; i < size; i++)
{
printf("\n Enter Data:");
scanf("%f", &merit[i]);
}
do
{
printf("\n menu");
printf("\n Querry…….1");
printf("\n Quit…………2");
printf("\n Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter position");
scanf("%d", &pos);
percentage=merit[pos];
printf("\n percentage=%4.2f", percentage); OUTPUT:
break;
case 2:
printf("\n Quitting");
}
printf("\n press a key to continue…:");}
while(choice!=2);}
3) Insertion
Insertion is the operation that inserts an element at a given location of the list.
To insert an element at ith location of the list, then all elements from the right of
i+ 1th location have to be shifted one step towards right.
Algorithm:
Step 1: Set upper_bound = upper_bound + 1
Step 2: Set A[upper_bound] = VAL
Step 3; EXIT
Step 1:
[INITIALIZATION] SET I = N
Step 2:
Repeat Steps 3 and 4 while I >= POS
Step 3:
SET A[I + 1] = A[I]
Step 4:
SET I = I – 1
[End of Loop]
Step 5: SET N = N + 1
Step 6: SET A[POS] = VAL
Step 7: EXIT
#include <stdio.h>
int main()
{ int array[100], position, i, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (i = n - 1; i >= position - 1; i--)
array[i+1] = array[i];array[position-1] = value;
printf("Resultant array is\n"); OUTPUT:
for (i = 0; i <= n; i++) printf("%d\n", array[i]);
return 0;
}
4) Deletion
Deletion is the operation that removes an element from a given location of the list.
To delete an element from the ith location of the list, then all elements from the
right of i+ 1th location have to be shifted one step towards left to preserve
contiguous locations in the array.
Algorithm:
Step 1: Set upper_bound = upper_bound - 1
Step 2: EXIT
#include <stdio.h>
int main()
{
int array[100], position, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( i = 0 ; i< n ; i++ )
scanf("%d", &array[i]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if ( position >= n+1 )
printf("Deletion not possible.\n");
else
{
for ( i= position - 1 ; i < n - 1 ; i++ )
array[i] = array[i+1]; OUTPUT:
printf("Resultant array is\n");
for( i = 0 ; i < n - 1 ; i++ )
printf("%d\n", array[i]);
}
return 0;
}
5) Searching
Search is an operation in which a given list is searched for a particular value. A list
can be searched sequentially wherein the search for the data item starts from the
beginning and continues till the end of the list. This method is called linear Search..
It is straightforward and works as follows: we compare each element with the
element to search until we find it or the list ends.
linear Search
#include<stdio.h>
void main(){
int numlist[20];
int n,pos, val,i;
printf("\n enter the size of the list");
scanf("%d", &n);
printf("\n Enter the elements one by one");
for(i=0;i<n;i++){
scanf("%d", &numlist[i]);}
printf("\n Enter the value to be searched");
scanf("%d", &val);
for(i=0;i<n;i++){
if(val== numlist[i]) {
printf("%d is present at location %d.\n",val,i+1);
break; }
if(i==n)
printf("%d isn't present in the array.\n",val);
}}
OUTPUT:
Binary Search
Binary search in C language to find an element in a sorted array. If the array isn't
sorted, you must sort it using a sorting technique such as bubble sort, insertion or
selection sort. If the element to search is present in the list, then we print its
location. The program assumes that the input numbers are in ascending order.
#include<stdio.h>
int main(){
int c, first, last, midd, 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 the value to find:\n");
scanf("%d", &search);
first = 0;
last = n - 1;
OUTPUT:
Test Yourself –2.0 & 2.1 Topics
(Arrays in C - Introduction to Arrays – One dimensional arrays)
2. What is the index number of the last element of an array with 29 elements?
A. 29
B. 28
C. 0
D. Programmer-defined
3. You need to decide on an optimal search algorithm to be used to search for a data which
is to be stored in an alphabetically sorted order. Which method would you use?
a) Linear Search
b) Binary Search
c) Radix Search
d) None of the above
4. Which of the following correctly accesses the seventh element stored in foo, an array with
100 elements?
A. foo[6];
B. foo[7];
C. foo(7);
D. foo;
5. Which of the following gives the memory address of the first element in array foo, an
array with 100 elements?
A. foo[0];
B. foo;
C. &foo;
D. foo[1];
Assume that the starting address is 1000 as an analogy, what is the address of the fourth
element of the array?
9. Double adNumber[4];
How many bytes are allocated for the above array declaration?
ii) Identify the errors, if any in each of declaration, by assumption ROW and
COLUMN are declared as symbolic constants.
a) Float values [10,14];
incorrect
b) Int sum[];
correct
c) Double salary[i+ROW]
incorrect
For examples,
int xInteger[3][4];
float matrixNum[20][25];
The first line declares xInteger as an integer array with 3 rows and 4 columns.
Second line declares a matrixNum as a floating-point array with 20 rows and 25
columns.
Therefore, a two dimensional mXn array is an array that contains m*n data elements
and each element is accessed using two subscripts, i and j where i<=m and j<=n
C C
Col Col Col
int marks[3][5] R/C 0 1
ol ol
4
2 3
Row
0
Row
1
Row
2
Second
Dimension
There are two ways of storing a 2-D array can be stored in memory. The first way is
row major order and the second is column major order.
2 3 4 1 2 3
3000 3002 3004 3006 3008 3010
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
2 1 3 2 4 3
3000 3002 3004 3006 3008 3010
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
Initialization of two Dimensional/2D Arrays
A two dimensional array is initialized in the same was as a single dimensional array
is initialized.
For example,
int marks[2][3]={90, 87, 78, 68, 62, 71};
int marks[2][3]={{90,87,78},{68, 62, 71}};
row0 row1
Write a program to print the elements of a 2D array
#include<stdio.h>
#include<conio.h>
main(){
int arr[2][2] = {12, 34, 56,32};
int i, j;
for(i=0;i<2;i++) {
printf("\n");
for(j=0;j<2;j++)
printf("%d\t", arr[i][j]);
}
return 0;}
If we assign initial string values for the 2D array it will look something like the
following,
char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold",
"Jodie"};
Here, we can initialize the array with 6 strings, each with maximum 9 characters
long.
If depicted in rows and columns it will look something like the following and can be
considered as contiguous arrangement in the memory.
Take note that for strings the null character (\0) still needed.
From the shaded square area of the figure we can determine the size of the array.
For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of
the colored square. In general, for
array_name[x][y];
For example,
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
And if you want to illustrate the 3D array, it could be a cube with wide, long and
height dimensions.
Accessing of two Dimensional/2D Arrays
The element of a 2D-Array can be accssed using 2 subscripts [][], a[0][0] to access
the element at the 0th row and oth column.
for(i=0;i<row;i++) {
for(j=0;j<col;;j++)
scanf("%d", &arr[i][j]);
//accessing elemnet of ith row and jth col.
}
The contents of the array in memory Re-run the program, enter the
after the three strings are read in the following data: "you", "my" and
array. "lav". lustrates the content as done
previously.
23/25
Operations on 2D array
#include <stdio.h>
void main()
{
int arr1[2][2],i,j;
printf("\n\nRead a 2D array of size 2x2 - print the matrix and sum of the
matrix:\n");
/* Stored values into the array*/
printf("Read elements in the matrix :\n");
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
} }
printf("\nPrint the matrix is : \n");
int sum=0;
for(i=0;i<2;i++) {
printf("\n");
for(j=0;j<2;j++){
sum=sum+arr1[i][j];
printf("%d\t",arr1[i][j]);
}} OUTPUT
printf("\n\n");
printf("Sum of the array is %d",sum);
}
4) Transpose
Transpose of a matrix in C language: This C program prints transpose of a matrix. It
is obtained by interchanging rows and columns of a matrix. For example, consider
the following 3 X 2 matrix:
12
34
56
Transpose of the matrix:
135
246
When we transpose a matrix then its order changes, but for a square matrix, it
remains the same.
#include <stdio.h>
void main(){
int arr1[50][50],brr1[50][50],i,j,r,c;
printf("\n\nTranspose of a Matrix :\n");
printf("---------------------------\n");
printf("\nInput the rows and columns of the matrix : ");
scanf("%d %d",&r,&c);
printf("Input elements in the first matrix :\n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
} }
printf("\nThe matrix is :\n");
for(i=0;i<r;i++) {
printf("\n");
for(j=0;j<c;j++) OUTPUT
printf("%d\t",arr1[i][j]); }
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
brr1[j][i]=arr1[i][j]; } }
printf("\n\nThe transpose of a matrix is : ");
for(i=0;i<c;i++){
printf("\n");
for(j=0;j<r;j++){
printf("%d\t",brr1[i][j]); } }
printf("\n\n");}
GUIDED ACTIVITY 2 – SWAP 2 VARIABLES
#include<stdio.h>
#include <conio.h> #include<stdio.h>
void main ( ) #include <conio.h>
{ void main ( )
{
int a,b; int a,b,temp;
clrscr( ); clrscr( );
printf(" \nEnter the value of a:"); printf(" \nEnter the value of a:");
scanf("%d",&a); scanf("%d",&a);
printf(" \nEnter the value of b:");
printf(" \nEnter the value of b:"); scanf("%d",&b);
scanf("%d",&b); temp=a;
a=a+b; a=b;
b=a-b; b=temp;
printf(" \nThe value of a is:%d",a);
a=a-b; printf(" \nThe value of b is:%d",b);
printf(" \nThe value of a is:%d",a); getch( );
printf(" \nThe value of b is:%d",b); }
getch( );
} Output:
Enter the value of a:5
Output: Enter the value of b:4
Enter the value of a:5
Enter the value of b:6 The value of a is:4
The value of b is:5
The value of a is:6
The value of b is:5
5) Sorting
Internal Sorting :
If all the data that is to be sorted can be accommodated at a time in memory is
called internal sorting.
External Sorting :
It is applied to Huge amount of data that cannot be accommodated in memory all
at a time. So data in disk or file is loaded into memory part by part. Each part that is
loaded is sorted separately, and stored in an intermediate file and all parts are
merged into one single sorted list.
Bubble Sort
Insertion Sort
Selection Sort
Quick Sort
Merge Sort
Exercise Program 2: Sort the numbers using bubble sort
Unsorted Sorted
10 54 54 54 54 54
47 10 47 47 47 47
12 47 10 23 23 23
54 12 23 10 19 19
19 23 12 19 10 12
23 19 19 12 12 10
: ");
scanf ("%d", &count);
For J = 1 to N - pass
printf("Enter the elements : \n");
for ( i = 0; i < count; i++) {
printf ("num[%d] : ", i ); scanf( "%d",
&num[ i ] ); A[J–1]>A[J]
} T
8 23 78 45 8 32 56
23 8 78 45 23 32 56
32 8 23 45 78 32 56
45 8 23 32 78 45 56
56 8 23 32 45 78 56
8 23 32 45 56 78
Selection_Sort ( A [ ] , N ) selection_sort ( int A[ ] , int n ) {
Step 1 : Repeat For K = 0 to N – 2 int k , j , pos , temp ;
Begin for ( k = 0 ; k < n - 1 ; k++ ) {
Step 2 : Set POS = K pos = k ;
Step 3 : Repeat for J = K + 1 to N – 1
for ( j = k + 1 ; j <= n ; j ++ ) {
Begin
If A[ J ] < A [ POS ]
if ( A [ j ] < A [ pos ] )
Set POS = J pos = j ; }
End For temp = A [ k ] ;
Step 5 : Swap A [ K ] with A [ POS ] A [ k ] = A [ pos ] ;
End For A [ pos ] = temp ;
Step 6 : Exit }}
Insertion Sort
TEMP
78 23 45 8 32 36
23
23 78 45 8 32 36
45
23 45 78 8 32 36
8
8 23 45 78 32 36
32
8 23 32 45 78 36
36
8 23 32 36 45 78
Insertion_Sort ( A [ ] , N ) insertion_sort ( int A[ ] , int n ) {
Step 1 : Repeat For K = 1 to N – 1 int k , j , temp ;
Begin for ( k = 1 ; k < n ; k++ ) {
Step 2 : Set Temp = A [ K ] temp = A [ k ] ;
Step 3 : Set J = K – 1 j = k - 1;
Step 4 : Repeat while Temp < A [ J ] AND J >= 0 while ( ( temp < A [ j ] ) && ( j >= 0 ) ) {
Begin A[j+1] =A[j];
Set A [ J + 1 ] = A [ J ] j--;
Set J = J - 1 }
End While A [ j + 1 ] = temp ;
Step 5 : Set A [ J + 1 ] = Temp }}
End For
Step 4 : Exit
k = 1; k < n ; k++
temp = a [ k ]
j=k-1
a[j+1]=a[j]
j=j-1
a [ j + 1 ] = temp
return
Selection sort
k = 0; k < n - 1 ; k++
pos = k
j = k + 1 ; j < n ; j++
a[ j ] < a[ pos ]
pos = j
temp = a[ k ]
a [ k ] = a [ pos ]
a [ pos ] = temp
return
Comparison : Bubble sort – Insertion sort – Selection sort
Bubble Sort :
-- very primitive algorithm like linear search, and least efficient .
-- No of swapping are more compare with other sorting techniques.
-- It is not capable of minimizing the travel through the array like
insertion sort.
Insertion Sort :
-- sorted by considering one item at a time.
-- efficient to use on small sets of data.
-- twice as fast as the bubble sort.
-- 40% faster than the selection sort.
-- no swapping is required.
-- It is said to be online sorting because it continues the sorting a list as
and when it receives
new elements.
-- it does not change the relative order of elements with equal keys.
-- reduces unnecessary travel through the array.
-- requires low and constant amount of extra memory space.
-- less efficient for larger lists.
Selection sort :
-- No of swapping will be minimized. i.e., one swap on one pass.
-- generally used for sorting files with large objects and small keys.
-- It is 60% more efficient than bubble sort and 40% less efficient than
insertion sort.
-- It is preferred over bubble sort for jumbled array as it requires less
items to be exchanged.
-- uses internal sorting that requires more memory space.
-- It cannot recognize sorted list and carryout the sorting from the
beginning, when new elements
are added to the list.
Topics to be covered – matrix operations (* addition,
subraction, multiplicaion, inverse, determinent, sum of
principal diagonal element)
How it Works
To add or subtract matrices we simply add or subtract corresponding entries
in each matrix resp.
OUTPUT
Multiplication of two matrices
How it Works
Two matrices can be multiplied only if the number of columns in the first matrix is equal to
the number of rows in the second matrix.
Let A be the matrix of size 2x3 and B be the matrix of size 3x2. then, A*B is given by. In
general, if matrix A is of size mxn, and B is of size nxp, then the size of marix A*B will be
m x p.
Determinant of a 2D matrix
For eg1. a = a b | a | = ad-bc
cd
eg2. a = a b c |a| = a(ei-fh)-b(di-gf)+c(dh-eg)
def
ghi
#include<stdio.h>
void main(){
int a[3][3],i,j,det;
printf("enter 3x3 matrix:\n");
for (i=0;i<3;i++){
for (j=0;j<3;j++){
scanf("%d",&a[i][j]);}}
det=a[0][0]*(a[1][1]*a[2][2]-a[2][1]*a[1][2])
-a[0][1]*(a[1][0]*a[2][2]-a[2][0]*a[1][2])
+a[0][2]*(a[1][0]*a[2][1]-a[2][0]*a[1][1]);
printf("\ndeterminant is %d", det);
}
#include<stdio.h>
int main() { int array1[3][3][3], i, j, k;
printf("\n Enter the elements of the matrix");
printf("\n ******************************");
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for(k=0;k<2;k++){
printf("\n array[%d][ %d][ %d] =
", i, j, k);
scanf("%d", &array1[i][j][k]);}
}}
printf("\n The matrix is : ");
printf("\n *********************************")l
for(i=0;i<2;i++){
printf("\n\n");
for(j=0;j<2;j++){
printf("\n");
for(k=0;k<2;k++)
printf("\t array[%d][ %d][ %d] = %d", i,
j, k, array1[i][j][k]);
}}
}
OUTPUT
GUIDED ACTIVITY 2 – Here is the
crossword for you on Arrays
Across
1) Array[size] & Array[____] Down
refer to the same element 1) In array, each block __
2) Elements can be accessed __ the same data type.
randomly by giving the 2) Language does not ___
respective ____ array bound checking
3) Array consists of a set of 3) 2D array can be declared
physically _____ memory without specifying the
locations ______ size.
4) The position of each array 4)_____ are a group of
element is known as array similar elements.
index or _____
Test Yourself – 2.2 Topics
(Arrays in C - Two dimensional arrays)
2. float aiEmployeeInfo[2][5];
How many bytes are allocated for the above array declaration?
3. Int aiEmployeeInfo[2][5];
Which of the following is the CORRECT statement to read value to
array element at row 0 and column 1.
Scanf(":%d", aiEmployeeInfo[0])
Scanf(":%d", &aiEmployeeInfo[0])
Scanf(":%d", aiEmployeeInfo[0][1])
Scanf(":%d", &aiEmployeeInfo[0][1])
2. Write a program in C to merge two arrays of same size sorted in decending K2 CO1
order. Test Data :
Input the number of elements to be stored in the first array :3
Input 3 elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3
Input the number of elements to be stored in the second array :3
Input 3 elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3
Expected Output :
The merged array in decending order is :
332211
3. Write a program in C to separate odd and even integers in separate arrays. K2 CO1
Test Data :
Input the number of elements to be stored in the array :5
Input 5 elements in the array :
element - 0 : 25
element - 1 : 47
element - 2 : 42
element - 3 : 56
element - 4 : 32
Expected Output :
The Even elements are :
42 56 32
The Odd elements are :
25 47
Part A
Question & Answer
Part A
1) What is an Array in C language.? CO4)(K3)
A group of elements of same data type.
2) In genral what is correct statement about C language arrays.
An array address is the address of first element of array itself.
An array size must be declared if not initialized immediately.
Array size is the sum of sizes of all elements of the array.
3) What are the Types of Arrays.?
Types of arrays includes; A) int, long, float, double B) struct, enum and
C) char
4) How do An array Index starts with?
It always starts with 0.
6) What is the output of C Program.? int main() { int a[]; a[4] =
{1,2,3,4}; printf("%d", a[0]); }
Output will be a Compiler error
7) What is the output of C Program.? int main() { int a[] = {1,2,3,4}; int
b[4] = {5,6,7,8}; printf("%d,%d", a[0], b[0]); }
Output will be 1,5
8) What is the output of C Program.? int main() { char grade[] =
{'A','B','C'}; printf("GRADE=%c, ", *grade); printf("GRADE=%d",
grade); }
Output will be GRADE=A, GRADE=some address of array
9) What is the output of C program.? int main() { char grade[] =
{'A','B','C'}; printf("GRADE=%d, ", *grade); printf("GRADE=%d",
grade[0]); }
The output will be 65 65
10) What is the output of C program.? int main() { float marks[3] =
{90.5, 92.5, 96.5}; int a=0; while(a<3) { printf("%.2f,", marks[a]);
a++; } }
The resultant value will be 90.5 92.5 96.5
11) What is the output of C Program.? int main() { int a[3] =
{10,12,14}; a[1]=20; int i=0; while(i<3) { printf("%d ", a[i]); i++; }
}
The output will be 10 20 14
Explanation: a[i] is (i+1) element. So a[1] changes the second element.
12) What is an array Base Address in C language.?
Base address in c include A) Base address is the address of 0th index
element.
B) An array b[] base address is &b[0]
C) An array b[] base address can be printed with printf("%d", b);
13) What is the output of C Program with arrays and pointers.? void
change(int[]); int main() { int a[3] = {20,30,40}; change(a);
printf("%d %d", *a, a[0]); } void change(int a[]) { a[0] = 10; }
Output: 10 10
Explanation: Notice that function change() is able to change the value of
a[0] of main(). It uses Call By Reference. So changes in called
function affected the original values.
14) Define an 2D array in C with two difference egs.? (CO4)(K3)
C looks a two dimensional array as an array of a one dimensional array.
The 2-D array be visualized as a rectangular grid of rows and columns.
15) What is multi-dimensional array? (CO4)(K3)
An array with more than one subscript is called multi-dimensional array.
In General an array with n subscripts is called n-dimensional array.
Part B
Questions
Part B
1. What is an Array and How to create an Array, adv and disadv.of array.
(CO4)(K3)
2. What will happen when you access the array more than its
dimension? (CO4)(K3)
3. Define arrays. Explain the array types with an example program for
each type. (CO4)(K3)
4. Why use arrays and need of an array with eg.? (CO4)(K3)
5. What are the limitations of arrays. (CO4)(K3)
6. Describe how to declare one dimensional array in detail. (CO4)(K3)
7. Can we change the size of an array at run time? (CO4)(K3)
8. Can you declare an array without assigning the size of an array?
(CO4)(K3)
9.What is the default value of Array in detail and why so? (CO4)(K3)
10.How to print element of Array? (CO4)(K3)
12. What is a two dimensional array. Explain its declaration, assignment
and various initialization methods with examples. (CO4)(K3)
13. Is it practically possible to implement multi-dimensional array. If so
justify your answer. (CO4)(K3)
14.Write a C program to arrange the numbers in ascending order..
(CO4)(K3)
15.Write a C program to subtract two matrices and display the resultant
matrices. (CO4)(K3)
16.Write a C program to search an element using binary search.
(CO4)(K3)
17.Write a C program to sort the given names [bubble sort]. (CO4)(K3)
18.Write a program in C to count a total number of duplicate elements in
an array. (CO4)(K3)
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 5
element - 1 : 1
element - 2 : 1
Expected Output :
Total number of duplicate elements found in the array is :
19. Advantages and disadvantages of Array? (CO4)(K3)
20. How to find the missing number in integer array of 1 to 100? (CO4)(K3)
21. How to find largest and smallest number in unsorted array? (CO4)(K3)
22. How to find all pairs on integer array whose sum is equal to given
number? (CO4)(K3)
23. How to rearrange array in alternating positive and negative number?
(CO4)(K3)
24. How to reverse array in place. (CO4)(K3)
25.Write a program to read and display the elements using 1-D array.
(CO4)(K3)
26.Write a C program to sort the given array elements in Ascending order.
Discuss with examples. (CO4)(K3)
27.Write a C program to find the largest and smallest element given in an
array of elements. (CO4)(K3)
28.Write a C program to read N integers into an array A and to find the (i)sum
of odd numbers,(ii) sum of even numbers,(iii) average of all numbers. Output
the results computed with appropriate headings. (CO4)(K3)
29.Write a C program to search an element using linear and binary
techniques. (CO4)(K3)
30. Write a C program for [consider integer data] (i) Bubble sort (ii) Linear
search (CO4)(K3)
31. Write a C program to read N numbers into an array & perform Linear
search (CO4)(K3)
32. Write an algorithm and develop a C program that reads N integer numbers
and arrange them in ascending order using selection Sort (CO4)(K3)
33. Write a C program to print the sum of diagonal elements of 2-D matrix.
(CO4)(K3)
34. Write an algorithm and develop a C program to search an integer from N
numbers in ascending order using binary searching technique. (CO4)(K3)
35. Write a C program to multiply two matrices of different order. (CO4)(K3)
36. Write a C program to add 2 matrices of size n by n. (CO4)(K3)
37. How 2-D array elements are stored in memory/ Explain with example
(CO4)(K3)
38. Perform scalar matrix multiplication. (CO4)(K3)
39. Check whether two matrices are equal or not. (CO4)(K3)
40. Sum of the main diagonal elements of a matrix. (CO4)(K3)
41. Find the sum of minor diagonal elements of a matrix.
42. Possible way to Identity matrix in C. (CO4)(K3)
43. Write a C program to Check the sparse matrix. (CO4)(K3)
44. Check the symmetric matrix. (CO4)(K3)
45. Find the sum of each row and column of a matrix.
(CO4)(K3)
46. Interchange diagonals of a matrix. (CO4)(K3)
47. Write a C program to determine the upper triangular
matrix. (CO4)(K3)
48. Find a lower triangular matrix. (CO4)(K3)
49. Sum of the upper triangular matrix. (CO4)(K3)
50. Write a C program to Find the sum of a lower triangular
matrix. (CO4)(K3)
51. Write a C program to find the transpose of a matrix.
(CO4)(K3)
52. Write a C program to Find determinant of a matrix.
(CO4)(K3)
Supportive Online
Certification
Unit II
Certification Courses
NPTEL
Problem solving through Programming in C
https://nptel.ac.in/courses/106/105/106105171/
Coursera
1)C for Everyone: Structured Programming
https://www.coursera.org/learn/c-structured-programming
2) C for Everyone: Programming Fundamentals
https://www.coursera.org/learn/c-for-everyone
Real time Applications
Unit II
Arrays are used at many places in real life applications and some
applications are listed here.
2D Arrays, generally called Matrices are mainly used in Image
processing
RGB image is a n*n*3 array
It is used in Speech Processing where each speech signal is an array
of Signal Amplitudes
Stacks are used for storing intermediate results in Embedded
systems
The filters that are used to remove noise in a recording are also
arrays
Playfair-cipher is an old encrypting algorithm that uses a 2D array
of alphabets as key to encrypt/decrypt text.
Every string that you see in this answer is an array of characters
An array of strings that gives some meaning is a sentence.
A simple question Paper is an array of numbered questions with
each of them mapped to some marks/points
If had written this answer with numbered bullets, the answer
would consist an array of numbered bullet points. But now, the
answer consists of an array of un-numbered bullet points.
Content beyond syllabus
Unit II
Content beyond syllabus
1) Sorting- Topics covered for Insertion and selection sort.
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
OCS752
INTRODUCTION TO C
PROGRAMMING
Department: : Electrical and Electronics Engineering
Batch/Year: 2017-2021
Created by: Dr. S. Meenakshi and A.S. Vibith
Date: 21-08-2020
Table of Contents
Course Objectives
Syllabus
Course Outcomes (Cos)
CO-PO Mapping
Lecture Plan
Activity based learning
Lecture notes
Assignments
Part A Q&A
Part B Qs
List of Supportive online Certification courses
Real time applications in day to day life and to industry
Contents beyond Syllabus
Assessment Schedule (proposed and actual date)
Prescribed Text Books & Reference Books
Mini Project Suggestions
Course Objectives
OCS752 INTRODUCTION TO C PROGRAMMING LTPC
3003
OBJECTIVES
CO1 PO1 2 Identify the data type and operators to solve the problem
CO5 PO5 2 Design and Develop program using the selected compound data
2 2 2 - 2 - - - - -
CO1
K1 - 1 1
3 3 2 - 2 - - - - -
CO2
K2 - 1 1
3 3 3 - 2 - - - - -
CO3 K2 - 1 1
2 2 2 - 2 - - - - -
CO4 K3 - 1 1
2 2 2 - - - - - - -
CO5 K3 - 1 1
3 3 3 2
CO6 K3 1 1
Unit III - STRINGS
S.No Topics No. Propos Actual Pertain Taxon Mode of
of ed Lecture ing CO omy Delivery
Peri Date Date Level
ods
Learn by questioning
We can also declare a string with size much larger than the number of elements that
are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it and
finally terminates the string with a null character. Rest of the elements in the array
are automatically initialized to NULL.
Now consider the following statements:
char str[3]; str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-time
error because of two reasons. First, the array is initialized with more elements than it
can store. Second, initialization cannot be separated from declaration.
Note: When allocating memory space for a string, reserve space to hold the
null character also.
Let us try to print above mentioned string:
#include <stdio.h>
#include <conio.h>
int main()
{
char str[10]={'H',’E',‘L',‘L',‘O','\0'};
printf("Greeting string message : %s", str);
return 0;
}
Note: that in this method, you have to deliberately append the string with a null
character. The other two functions automatically do this
The string can also be read by calling the getchar() repeatedly to
read a sequence of single characters (unless a terminating
character is entered) and simultaneously storing it in a character
array.
i=0;
getchar(ch);
while(ch !='*’)
{ str[i] = ch;
i++;
getchar(ch);
} str[i] ='\0';
WRITING STRINGS
printf("%s", str);
We use the format specifier %s to output a string. Observe carefully that
there is no'&’ character used with the string variable. We may also use
width and precision specifications along with %s. The width specifies the
minimum output field width. If the string is short, the extra space is either
left padded or right padded. A negative width left pads short string rather
than the default right justification. The precision specifies the maximum
number of characters to be displayed, after which the string is truncated.
For example,
printf ("%5.3s", str);
The above statement would print only the first three characters in a total
field of five characters. Also these characters would be right justified in the
allocated width. To make the string left justified, we must use a minus
sign. For example,
printf ("%–5.3s", str);
The string can be displayed by writing
puts(str);
puts() is a simple function that overcomes the drawbacks of the printf()
function.
Note: When the field width is less than the length of the string, the entire
string will be printed, if the number of characters to be printed is specified
as zero, then nothing is printed on the screen.
The string can also be written by calling the putchar() repeatedly to
print a sequence of single characters
i=0;
while(str[i] !='\0*)
{ putchar(str[i]);
i++;
}
Reading A Line Of Text
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Note: Though, gets() and puts() function handle strings, both these
functions are defined in "stdio.h" header file.
SUPPRESSING INPUT
scanf() can be used to read a field without assigning it to any
variable. This is done by preceding that field's format code with a *.
For example, given:
scanf("%d*c%d", &hr, &min);
The time can be read as 9:05 as a pair. Here the colon would be read
but not assigned to anything.
Using a Scanset
The ANSI standard added the new scanset feature to the C
language. A scanset is used to define a set of characters which may
be read and assigned to the corresponding string. A scanset is
defined by placing the characters inside square brackets prefixed
with a %
int main()
{
char str[10];
printf("\n Enter string: " );
scanf(""%[aeiou]", str );
printf( "The string is : %s", str);
return 0;
}
The code will stop accepting character as soon as the user will enter
a character that is not a vowel.
However, if the first character in the set is a ^ (caret symbol), then
scanf() will accept any character that is not defined by the scanset.
For example, if you write
scanf("%[^aeiou]", str );
3.2 String operations (using built-in
string functions)
In this section, we will learn about different operations that can be
performed on strings using built in functions.
C provides string manipulating functions in the "string.h" library.
String in C – Library Functions
#include<stdio.h>
#include<string.h> //c header file for string library functions
void main(){
char str1[10]="DeNnis" , str2[10]="RitChiE";
int len;
len=strlen(str1);
//strupr(str1);
//strlwr(str2);
printf("\n Length of string is %d", len);
//printf("\n upper case is %s" , str1);
//printf("\n lower case is %s" ,str2);
strrev(str1);
printf("\n Reverse of string is %s", str1);
}
OUTPUT:
Length of string is 6
Reverse of string is sinNeD
Note: strupr() strlwr() - This is a non-standard function that works only with
older versions of Microsoft C.
ii) Concatenate – copy & append
Concatenating two strings to form a new string
strcat( ) function in C language concatenates two given strings. It
concatenates source string at the end of destination string. Syntax
for strcat( ) function is given below.
char * strcat ( char * destination, const char * source );
Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
As you know, each string in C is ended up with null character (‘\0’).
In strcat( ) operation, null character of destination string is
overwritten by source string’s first character and null character is
added at the end of new destination string which is created after
strcat( ) operation.
#include<stdio.h>
#include<string.h> //c header file for string library functions
void main(){
char str1[10]="mic" , str2[10]="mouse";
char str3[10]="donald" , str4[10]="duck";
char str5[10]="denny", str6[10];
strcat(str1 ,str2);
printf("\n After concatenating strings: %s" , str1);
strncat(str3 ,str4 ,2); //appends first two char of str4 to str3
printf("\n After concatenating first two characters: %s" , str3);
strcpy(str6 ,str5);
printf("\n Copied string is %s" , str6);
}
OUTPUT:
iii) Comparing two strings
Comparing the twos strings
If S1 and S2 are two strings, then comparing the two strings will
give either of the following results:
S1 and S2 are equal
S1>S2, when in dictionary order, S1 will come after S2
S1<S2, when in dictionary order, S1 precedes S2
To compare the two strings, each and every character is compared
from both the strings. If all the characters are the same, then the
two strings are said to be equal.
strcmp( ) function in C compares two given strings and returns zero
if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1
> string2, it returns > 0 value. Syntax for strcmp( ) function is given
below.
int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e, "A" and "a" are treated as
different characters.
Example: C program to illustrate
strcmp() , stricmp() , strncmp() , strnicmp()
#include<stdio.h>
#include<string.h> //c header file for string library functions
void main(){
char str1[10]="Charles" , str2[10]="charles";
char str3[10]="charlie";
If (strcmp(str1 , str2)==0)
printf("\n Equal strings");
else
printf("\n Strings are different");
If (stricmp(str1 , str2)==0)
printf("\n Equal strings");
else
printf("\n Strings are different");
If (strncmp(str2 , str3 , 4)==0)
printf("\n First four characters are same");
else
printf("\n First four characters are different");
}
OUTPUT:
Strings are different
Equal strings
First four characters are different
iv) Substring /find out occurrence?
C substring program to find substring of a string and its all subsrngs.
A substring is itself a string that is part of a longer string. For
example, substrings of string "the" are "" (empty string), "t", "th",
"the", "h", "he" and "e."
Note:
The header file "string.h" does not contain any library function
to find a substring directly like substr() but can find either
using strchr /strnchr/strstr() or by manually by applying logic
and similarly for Insertion and Deletion as well.
Example: C program to illustrate strchr() , strrchr() , strstr()
#include<stdio.h>
#include<string.h> //c header file for string library functions
void main(){
char str1[15]="Miscky Vickys";
printf("\n Using strchr : %s" , strchr(str1 ,'i'));
printf("\n Using strrchr : %s" , strrchr(str1 ,'i'));
printf("\n Using strstr : %s" , strstr(str1 ,'ky'));
}
OUTPUT:
Using strchr : iscky Vickys
Using strrchr : iscky
Using strstr : ky Vickys
v) Indexing
vi) replacement
strset( ) function sets all the characters in a string to given character.
Syntax for strset( ) function is given below.
char *strset(char *string, int c);
strnset( ) function sets portion of characters in a string to given
character. Syntax for strnset( ) function is given below.
char *strnset(char *string, int c);
strnset( ) function is non standard function which may not available
in standard library in C.
OUTPUT:
Using strset : **********
Using strnset : ********60
Note: strset( ) function is non standard function which may not
available in standard library in C.
3.3 String operations (without using string
built-in/lib functions)
In this section, we will learn about different operations that can be performed on
strings without using built in functions which includes :
i) Length – ii) Compare – *iii) Concatenate – *iv) Copy – v) Reverse – vi) Substring
– vii) Insertion – viii) Indexing – ix) Deletion – x) Replacement
shows an algorithm that calculates the length of a string. In this algorithm, I is used
as an index for traversing string STR. To traverse each and every character of
STR, we increment the value of I. Once we encounter the null character, the
control jumps out of the while loop and the length is initialized with the value of
I.
for (i=0;str[i]!='\0';i++)
length = length+1;
#include <stdio.h>
int main()
{
int i,j=0,len=0;
char str1[100], str2[100];
printf("\nEnter the string1 : ");
gets(str1);
printf("Enter the string2 : ");
gets(str2);
for (i=0;str1[i]!='\0';i++)
len=len+1; // lengthof the first string
j=len;
for (i=0;str2[i]!='\0';i++){
str1[j]=str2[i]; // 2nd string copied to 1st string //from jth
position
j=j+1;}
str1[j]='\0';
#include <stdio.h>
#include <conio.h>
int main()
{
char Dest_Str[100], Source_Str[50];
int i=0, j=0;
printf("\n Enter the source string : ");
gets(Source_Str);
printf("\n Enter the destination string : ");
gets(Dest_Str);
while(Dest_Str[i] != '\0')
i++;
while(Source_Str[j] != '\0')
{
Dest_Str[i] = Source_Str[j];
i++;
j++;
}
Dest_Str[i] = '\0';
printf("\n After appending, the destination string is : ");
puts(Dest_Str);
return 0;
}
OUTPUT
Enter the source string : How are you?
Enter the destination string : Hello,
After appending, the destination string is : Hello,How are you?
iv) Copy
Copying the contens of one string to another string.
#include <stdio.h>
int main()
{
int i;
char str1[100], str2[100];
printf("\n Enter the string1 : ");
gets(str1);
for (i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("The copied string is %s",str2);
return 0;
}
OUTPUT
v) Reverse
#include <stdio.h>
int main()
{
int i,j=0,len=0;
char str1[100], rev[100];
printf("\nEnter the string1 : ");
gets(str1);
for (i=0;str1[i]!='\0';i++)
len=len+1;
for (i=len-1;i>=0;i--)
{
rev[j]=str1[i];
j=j+1;
}
rev[j]='\0';
printf("The reversed string is %s",rev);
return 0;
}
Outpt
vi) Substring
To extract a substring from a given string, we need the following
three parameters:
the main string,
the position of the first character of the substring in the given string,
and
the maximum number of characters/length of the substring.
For example, if we have a string
str[] = "Welcome to the world of programming";
Then, SUBSTRING(str, 15, 5) = world
Figure shows an algorithm that extracts a substring from the middle
of a string.
In this algorithm, we initialize a loop counter I to M, that is, the
position from which the characters have to be copied. Steps 3 to 6
are repeated until N characters have been copied. With every
character copied, we decrement the value of N. The characters of
the string are copied into another string called the SUBSTR. At the
end, a null character is appended to SUBSTR to terminate the
string.
Write a program to extract a substring from the middle of a given
string.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
printf("\n Enter the main string : ");
gets(str);
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n);
i=m;
while(str[i] != '\0' && n>0)
{
substr[j] = str[i];
i++; j++; n--;
}
substr[j] = '\0';
printf("\n The substring is : "); puts(substr);
return 0;
}
OUTPUT
Enter the main string : Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 4
The substring is : i th
viii) Indexing –program
Pattern Matching
This operation returns the position in the string where the string
pattern first occurs. For example,
INDEX("Welcome to the world of programming", "world") = 15
However, if the pattern does not exist in the string, the INDEX
function returns 0.
Figure shows an algorithm to find the index of the first occurrence of
a string within a given text
This program
takes a string
from user
and for loop
executed
until all
characters of
string is
checked. If
any
character
inside a
string is not a
alphabet, all
characters
after it
including null
character is
shifted by 1
position
backwards.
3.4 Introduction to Pointers
Understanding The Computer’s Memory
Every computer has a primary memory. All our data and programs need to be
placed in the primary memory for execution.
The primary memory or RAM (Random Access Memory which is a part of the
primary memory) is a collection of memory locations (often known as cells) and
each location has a specific address. Each memory location is capable of storing 1
byte of data
Generally, the computer has four areas of memory each of which is used for a
specific task. These areas of memory include- stack, heap and global memory.
Stack- A fixed size of stack is allocated by the system and is filled as needed
from the bottom to the top, one element at a time. These elements can be
removed from the top to the bottom by removing one element at a time. That is,
the last element added to the stack is removed first.
Heap- Heap is a contiguous block of memory that is available for use by the
program when need arise. A fixed size heap is allocated by the system and is
used by the system in a random fashion.
When the program requests a block of memory, the dynamic allocation technique
carves out a block from the heap and assigns it to the program.
When the program has finished using that block, it returns that memory block to
the heap and the location of the memory locations in that block is added to the
free list.
Global Memory- The block of code that is the main() program (along with other functions
in the program) is stored in the global memory. The memory in the global area is
allocated randomly to store the code of different functions in the program in such a way
that one function is not contiguous to another function. Besides, the function code, all
global variables declared in the program are stored in the global memory area.
Other Memory Layouts- C provides some more memory areas like- text segment, BSS and
shared library segment.
The text segment is used to store the machine instructions corresponding to the compiled
program. This is generally a read-only memory segment
BSS is used to store un-initialized global variables
Shared libraries segment contains the executable image of shared libraries that are being
used by the program.
Intro to pointers
Every variable in C has a name and a value associated with it. When a variable is
declared, a specific block of memory within the computer is allocated to hold the
value of that variable. The size of the allocated block depends on the type of the
data.
int x = 10;
When this statement executes, the compiler sets aside 2 bytes of memory to hold
the value 10. It also sets up a symbol table in which it adds the symbol x and the
relative address in memory where those 2 bytes were set aside.
Thus, every variable in C has a value and an also a memory location (commonly
known as address) associated with it. Some texts use the term rvalue and lvalue
for the value and the address of the variable respectively.
The rvalue appears on the right side of the assignment statement and cannot be
used on the left side of the assignment statement. Therefore, writing 10 = x; is
illegal.
#include<stdio.h>
void main(){
int x=10;
printf("\n The Address of x = %u",&x);
printf("\n The Value of x = %d",x);}
OUTPUT
The Address of x = 1002
The Value of x = 10
Declaring Pointer Variables
Actually pointers are nothing but memory addresses.
A pointer is a variable that contains the memory location of another
variable.
The general syntax of declaring pointer variable is
data_type *ptr_name;
Example: Example:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main(){
{
int x=5; int y=10;
int *a;
a=&x; int *a;
printf("\n The Value of x = %d",x);
printf("\n The Address of x = %u",&x); a=&y;
printf("\n The Value of a = %d",a);
printf("\n The Value of x = %d",*a); printf("\n The Value of y = %d",y);
}
The Value of x = 5 printf("\n The Address of y = %u",&y);
The Address of x = 8758
printf("\n The Value of a = %d",a);
The Value of a = 8758
The Value of x = 5 printf("\n The Address of a = %u",&a);}
The Value of y = 10
The Address of y = 5001
The Value of a = 5001
The Address of a = 8000
De-referencing A Pointer Variable
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
printf("\n Enter the number : ");
scanf("%d", &num);
printf("\n The number that was entered is : %d", *pnum);
return 0;
}
OUTPUT:
Enter the number : 10
The number that was entered is : 10
Guided Activity on Pointer and Dereferencing pointer
Value in
Allots some memory
‘option’
location
char option = 4042 (for example)
‘Y’; with a name option ‘Y’
and
stores value ‘Y’ in it option
Variable
Memory Address of variable
‘option’ 4042
Creates a pointer
variable with a name
char *ptr = ‘ptr’
NULL; Which can hold a
Memory address ptr
Memory address
of
4042 ‘Y’
ptr = &option;
Variable ‘option’
option
Is copied to the ptr
Pointer ‘ptr’
4042
int main() { n1 n2
pointer variables are
declared
int n1, n2 ;
p NU q NU
int *p = "NULL", *q = "NULL";
LL LL
n1 = 6;
p = & n1; Prints 6 6
p q
pointer ‘q’ assigned with
p = q; pointer ‘q’
*p = 7 ; p q
printf ("\n %d value5 %d ", *p , *q ) ;
}
Prints 7 7
When two pointers are referencing with one variable, both pointers
contains address of the same variable, and the value changed
through with one pointer will reflect to both of them.
VAC-C/C++ TRG
Pointer operators / expressions
*ptr2 +=1;
#include <stdio.h>
int main() {
int arr [5] = { 12, 31, 56, 19, 42 }; Prints 31
int *p;
p = arr + 1; Prints 12 31 56
printf("%d \n", *p);
printf("%d %d %d\n", *(p-1), *(p), *(p + 1));
--p;
printf("%d", *p);
Prints 12
arr[0] or *( arr + 0 ) p - 1
12
arr[1] or *( arr + 1 ) p
31
arr[2] or *( arr + 2 ) p +1
56
arr[3] or *( arr + 3 ) p +2
19
arr[4] or *( arr + 4 ) p +3
42
1)A null pointer which is a special pointer value that is known not to
point anywhere. This means that a NULL pointer does not point to
any valid memory address.
if ( ptr == NULL)
{ Statement block;
int main( ) {
void* p;
int x = 7;
float y = 23.5;
p = &x;
printf("x contains : %d\n", *( ( int *)p) );
p = &y;
printf("y contains : %f\n", *( ( float *)p) );
}
OUTPUT
x contains 7
y contains 23.500000
Pointers And Arrays
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3]={2,3,7};
int *b;
b=a;
printf("\n The Value of a[0] = %d",a[0]);
printf("\n The Address of a[0] = %u",&a[0]);
printf("\n The Value of b = %d",b);
}
OUTPUT
The Value of a[0] = 2
The Address of a[0] = 8744
The Value of b = 8744
Guided Activity : Pointer and Arrays
Even though pointers and arrays work alike and strongly related, they are not
synonymous. When an array is assigned with pointer, the address of first
element of the array is copied into the pointer.
#include<stdio.h>
int main() Pointer is an address variable,
{ having no initialized value by
int a[3] = { 12, 5 ,7}, b[3]; default. The address stored in
int *p ,*q; Prints 12 12 the pointer can be changed
time to time in the program.
p = a;
printf("%d %d\n", *p, *a);
Prints 12 12
q = p;
printf("%d %d",*p,*q);
b = a; /* error */
} Array name is an address
constant, initialized with the
address of the first element
(base address )in the array. The
address stored in array name
cannot be changed in the
program.
Pointers And Two Dimensional Array
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j )
Look at the code given below which illustrates the use of a pointer to a two
dimensional array.
#include<stdio.h>
main()
{ int arr[2][2]={{1,2}.{3,4}};
int i, (*parr)[2];
parr=arr;
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf(" %d", (*(parr+i))[j]);
}
}
OUTPUT
1234
Pointers And Strings
int *ptr[10]
int *ptr[10];
ptr[0]=&p;
ptr[1]=&q;
ptr[2]=&r;
ptr[3]=&s;
ptr[4]=&t
Can you tell what will be the output of the following statement?
Yes, the output will be 4 because ptr[3] stores the address of integer
variable s and *ptr[3] will therefore print the value of s that is 4.
The advantage of pointer array is that the length of each row in the
array may be different. The important application of pointer array is to
store character strings of different length. Example :
char *day[ ] = { "Sunday", "Monday", "Tuesday", "Wednesday",
Thursday", "Friday", "Saturday" };
Pointers To Pointers (Double Indirection)
You can use pointers that point to pointers. The pointers in turn, point to data (or
even to other pointers). To declare pointers to pointers just add an asterisk (*) for
each level of reference.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
printf("\n The Value of b = %d",b);
printf("\n The Address of b = %u",&b);
printf("\n The Value of c = %d",c);
printf("\n The Address of c = %u",&c);
}
OUTPUT
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000
Drawbacks of Pointers
Although pointers are very useful in C, they are not free from
limitations. If used incorrectly, pointers can lead to bugs that
are difficult to unearth. For example, if you use a pointer to
read a memory location but that pointer is pointing to an
incorrect location, then you may end up reading a wrong
value. An erroneous input always leads to an erroneous
output. Thus however efficient your program code may be,
the output will always be disastrous. Same is the case when
writing a value to a particular memory location.
Let us try to find some common errors when using pointers.
int x, *px;
x=10;
*px = 20;
Error: Un-initialized pointer. px is pointing to an unknown
memory location. Hence it will overwrite that location’s
contents and store 20 in it.
int x, *px;
x=10;
px = x;
Error: It should be px = &x;
int x=10, y=20, *px, *py; px = &x, py = &y; if(px<py)
printf("\n x is less than y"); else
printf("\n y is less than x");
Error: It should be if(*px< *py)
Exercise Programs
3.5 Exercise Programs:
Exercise program1 : To find the frequency of a character in a
string
we will learn how to find occurrence of a particular character in a string
using C program?
Here, we are reading a character array/string (character array is declaring with
the maximum number of character using a Macro MAX that means maximum
number of characters in a string should not more than MAX (100), then we are
reading a character to find the occurrence and counting the characters which are
equal to input character.
For example:
If input string is "Hello world!" and we want to find occurrence of 'l' in the
string, output will be 'l' found 3 times in "Hello world!".
#include <stdio.h>
#define MAX 100
int main(){
char str[MAX]={0};
char ch;
int count,i;
//input a string
printf("Enter a string: ");
scanf("%[^\n]s",str); //read string with spaces
This program counts the frequency of characters in a string, i.e., which character is
present how many times in the string. For example, in the string "code" each of the
characters 'c,' 'd,' 'e,' and 'o' has occurred one time. Only lower case alphabets
are considered, other characters (uppercase and special characters) are ignored. You
can modify this program to handle uppercase and special symbols.
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int c = 0, count[26] = {0}, x;
printf("Enter a string\n");
gets(string);
while (string[c] != '\0') {
/** Considering characters from 'a' to 'z' only and ignoring others. */
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] -'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
printf("%c occurs %d times in the string.\n", c +'a', count[c]);
return 0;
}
OUTPUT
Exercise program 2: To find the number of vowels, consonants
and white spaces in a given text
#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;
vowels = consonant = digit = space = 0;
printf("Enter a line of string: ");
gets(line);
//fgets(line, sizeof(line), stdin);
for (int i = 0; line[i] != '\0'; ++i) {
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U') {
++vowels;
} else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
++consonant;
} else if (line[i] >= '0' && line[i] <= '9') {
++digit;
} else if (line[i] == ' ') {
OUTPUT
++space;
} }
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;}
/* C Program to Sort array of nos ascending and descending order */
#include <stdio.h>
#include <string.h>
void main()
{
int a[10], t ;
int i, j, n;
#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
3. Define Strings.
The group of characters, digit and symbols enclosed within quotes is
called as String (or) character Arrays. Strings are always terminated
with „\0‟ (NULL) character. The compiler automatically adds „\0‟ at
the end of the strings.
NPTEL
Problem solving through Programming in C
https://nptel.ac.in/courses/106/105/106105171/
Coursera
1)C for Everyone: Structured Programming
https://www.coursera.org/learn/c-structured-programming
2) C for Everyone: Programming Fundamentals
https://www.coursera.org/learn/c-for-everyone
Real time Applications
Unit III
1) Phonebook application
a small phonebook code challenge to build the shortest : Functions
include add contact, remove contact, search contact and display
contacts.
Content beyond syllabus
Unit III
Content beyond syllabus
1) Character manipulation functions in c using Ctype.h library file
Assessment Schedule
Unit III
Prescribed Text book &
References
Unit III
Text books & References
TEXT BOOK
1. Reema Thareja, "Programming in C", Oxford University Press,
Second Edition, 2016
REFERENCES
1. Kernighan, B.W and Ritchie,D.M, "The C Programming
language", Second Edition, Pearson Education, 2006
2. Paul Deitel and Harvey Deitel, "C How to Program", Seventh
edition, Pearson Publication
3. Juneja, B. L and Anita Seth, "Programming in C", CENGAGE
Learning India pvt. Ltd., 2011
4. Pradip Dey, Manas Ghosh, "Fundamentals of Computing and
Programming in C", First Edition, Oxford University Press, 2009
5. ER and ETA , “CC Foundation Program Reference materials”
Infosys Ltd.
Mini Project Suggestions
Unit III
1) Contact Management System
2) Personal diary Management system
Thank you
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
OCS752
INTRODUCTION TO C
PROGRAMMING
Department: : Electrical and Electronics Engineering
Batch/Year: 2017-2021
Created by: Dr. S. Meenakshi and A.S. Vibith
Date: 21-08-2020
Table of Contents
Course Objectives
Syllabus
Course Outcomes (Cos)
CO-PO Mapping
Lecture Plan
Activity based learning
Lecture notes
Assignments
Part A Q&A
Part B Qs
List of Supportive online Certification courses
Real time applications in day to day life and to industry
Contents beyond Syllabus
Assessment Schedule (proposed and actual date)
Prescribed Text Books & Reference Books
Mini Project Suggestions
Course Objectives
OCS752 INTRODUCTION TO C PROGRAMMING LTPC
3003
OBJECTIVES
CO1 PO1 2 Identify the data type and operators to solve the problem
CO5 PO5 2 Design and Develop program using the selected compound data
2 2 2 - 2 - - - - -
CO1
K1 - 1 1
3 3 2 - 2 - - - - -
CO2
K2 - 1 1
3 3 3 - 2 - - - - -
CO3 K2 - 1 1
2 2 2 - 2 - - - - -
CO4 K3 - 1 1
2 2 2 - - - - - - -
CO5 K3 - 1 1
3 3 3 2
CO6 K3 1 1
Unit IV - FUNCTIONS
S.N Topics No. Propos Actual Pertain Taxon Mode of
o of ed Lecture ing CO omy Delivery
Peri Date Date Level
ods
Learn by questioning
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.
1.Program Control – Functions used to simply sub-divide and control the program.
These functions are unique to the program being written. Other programs may use
similar functions, maybe even functions with the same name, but the content of the
functions are almost always very different.
b) Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch
.
c) Debugging of the code would be easier if you use functions, as errors are easy
to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by
function calls.
Terminologies of Functions
• A function f that uses another function g, is known as the calling function and g
is known as the called function
• The input that the function takes are known as argument / parameter.
• When a called function returns some result back to the calling function, it is said
to return that result.
• The calling function may or may not pass parameters to the called function. If
the called function accepts arguments, the calling function will pass parameters,
else it will not do so.
Scope of a Function:
A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed. There are three
places where variables can be declared in C programming language −
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. The following example shows
how local variables are used. Here all the variables a, b, and c are local to main()
function.
#include <stdio.h>
int main ()
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 20;
b = 10;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program
show how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int x;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 20;
b = 10;
x = a + b;
printf ("value of a = %d, b = %d and x = %d\n", a, b, x);
return 0;
}
A program can have same name for local and global variables but the value
of local variable inside a function will take preference.
Example
#include <stdio.h>
/* global variable declaration */
int x = 30;
int main ()
/* local variable declaration */
int x = 10;
printf ("value of x = %d\n", x);
return 0;
}
Types of Functions
Types of function
• User-defined function
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file
using #include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is defined in
the math.h header file.
Example:
#include<stdio.h>
#include<math.h>
void main()
{
float number, root;
printf(“Enter the number”);
scanf(“%f”,&number);
root=sqrt(number);
printf(“Square root of %.2f=%.2f”,number,root);
}
Output
User-defined function
The functions that we create in a program are known as user defined functions or in
other words you can say that a function created by user is known as user defined
function.
Syntax
Example:
#include <stdio.h>
int addition(int number1, int number2)
{
int sum;
/* Arguments are used here*/
sum = number1+number2;
3. A large program can be divided into smaller modules. Hence, a large project can
be divided among many programmers.
Function Prototype
Function Prototype:
The function prototypes are used to tell the compiler about the number of
arguments and about the required datatypes of a function parameter, it also tells
about the return type of the function. By this information, the compiler cross-checks
the function signatures before calling it. If the function prototypes are not
mentioned, then the program may be compiled with some warnings, and sometimes
generate some strange output.
If some function is called somewhere, but its body is not defined yet, that is defined
after the current line, then it may generate problems. The compiler does not find
what is the function and what is its signature. In that case, we need to function
prototypes. If the function is defined before then we do not need prototypes.
Example:
#include<stdio.h>
main() {
function(50);
}
void function(int x) {
printf("The value of x is: %d", x);
}
Output:
The value of X is : 50
This shows the output, but it is showing some warning like below
[Warning] conflicting types for 'function'
[Note] previous implicit declaration of 'function' was here :
Example:
Using Prototype:
#include<stdio.h>
void function(int); //prototype
main() {
function(50);
}
void function(int x) {
printf("The value of x is: %d", x);
}
Output:
The value of x is: 50
Function Definition
Function Definition:
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.
Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Syntax:
{
………………………………………..
statements
………………………………….......
return (variable);
}
The number of arguments and the order of arguments in the function header must
be same as that given in the function declaration statement.
The function definition itself can act as an implicit function declaration. So the
programmer may skip the function declaration statement in case the function is
defined before being used.
Example:
Actual arguments
Formal arguments
Categories of functions
A function, depending on whether arguments are present or not and whether a value
is returned or not, may belong to one of the following categories.
1. Function with no argument and no return value
2. Function with argument and no return value
3. Function with no argument and return value
4. Function with argument and return value
int sum();
int main()
{
int num;
num = sum();
printf("\nSum of two given values = %d", num);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = sqrt(a) + sqrt(b);
return sum;
}
Pass by Value:
The call by value method of passing arguments to a function copies the actual value
of an argument into the formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect on the argument.
By default, C programming uses call by value to pass arguments. In general, it means
the code within a function cannot alter the arguments used to call the function.
Consider the function swap() definition as follows.
int temp;
return;
}
Example:
call the function swap() by passing actual values
#include<stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Output:
To pass a value by reference, argument pointers are passed to the functions just
like any other value. So accordingly you need to declare the function parameters as
pointer types as in the following function swap(), which exchanges the values of
the two integer variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Example:
call the function swap() by passing values by reference
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
strcat():
strcat( ) function in C language concatenates two given strings. It concatenates
source string at the end of destination string.
Syntax for strcat( ) function is given below.
Example Program:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “Welcome to " ;
char target[ ]= " C Programming" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "\nTarget string after strcat( ) = %s", target ) ;
}
Output:
Source string = Welcome to
Target string = C Programming
Target string after strcat( ) = C Programming Welcome to
Strncat()
strncat( ) function in C language concatenates (appends) portion of one string at the
end of another string.
Syntax for strncat( ) function is given below.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " fresh2refresh" ;
char target[ ]= "C tutorial" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strncat ( target, source, 5 ) ;
printf ( "\nTarget string after strncat( ) = %s", target ) ;
}
Output:
Source string = Welcome
Target string = C Programming
Target string after strncat( ) = C Programming Welc
Strcpy()
•If destination string length is less than source string, entire source string value won’t
be copied into destination string.
For example, consider destination string length is 10 and source string length is 20.
Then, only 10 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “Welcome" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
Output:
Sourcestring = Welcome
target string =
target string after strcpy( ) = Welcome
Strlen():
•strlen( ) function counts the number of characters in a given string and returns the
integer value.
•It stops counting the character when null character is found. Because, null character
indicates the end of the string in C.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
int len;
char array[20]=“Programming" ;
len = strlen(array) ;
printf ( "\string length = %d \n" , len ) ;
return 0;
}
Output:
String Length = 11
Strcmp():
strcmp( ) function in C compares two given strings and returns zero if they are
same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value.
Syntax for strcmp( ) function is given below.
Example:
In this program, strings “fresh” and “refresh” are compared. 0 is returned when
strings are equal. Negative value is returned when str1 < str2 and positive value is
returned when str1 > str2.
#include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmp ( str1, "fresh" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, "f" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
return 0;
}
Output:
0-11
strchr()
strchr( ) function returns pointer to the first occurrence of the character in a given
string.
Syntax for strchr( ) function is given below.
Example:
In this program, strchr( ) function is used to locate first occurrence of the character
‘i’ in the string “This is a string for testing”. Character ‘i’ is located at position 3 and
pointer is returned at first occurrence of the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a string for testing";
char *p;
p = strchr (string,'i');
printf ("Character i is found at position %d\n",p-string+1);
printf ("First occurrence of character \"i\" in \"%s\" is" \" \"%s\"",string, p);
return 0;
}
Output:
Character i is found at position 3
First occurrence of character “i” in “This is a string for testing” is “is is a string for
testing”
Strdup():
strdup( ) function in C duplicates the given string.
Syntax for strdup( ) function is given below.
char *strdup(const char *string);
strdup( ) function is non standard function which may not available in standard
library in C.
Example:
strlwr( ) function is non standard function which may not available in stand library in C.
Example:
In this program, string ” PROGRAMMING In C ” is converted into lower case using
strlwr( ) function and result is displayed as “programming in c”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “PROGRAMMING In C";
printf("%s\n",strlwr (str));
return 0;
}
Output:
programming in c
Strupr():
strupr( ) function converts a given string into uppercase.
Syntax for strupr( ) function is given below.
char *strupr(char *string);
strupr( ) function is non standard function which may not available in stand library in C.
Example:
In this program, string “programming IN c” is converted into uppercase using strupr( )
function and result is displayed as “PROGRAMMING IN C”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “programming In C";
printf("%s\n",strupr(str));
return 0;
}
Output:
PROGRAMMING IN C
Strrev():
strrev( ) function reverses a given string in C language.
Syntax for strrev( ) function is given below
.
char *strrev(char *string);
strrev( ) function is non standard function which may not available in standard
library in C.
Example:
In below program, string “Hello” is reversed using strrev( ) function and output is
displayed as “olleH”.
#include<stdio.h>
#include<string.h>
void main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
}
Output:
String before strrev( ) : Hello
String after strrev( ) : olleH
Strncpy():
strncpy( ) function copies portion of contents of one string into another string. Syntax
for strncpy( ) function is given below.
Example:
strncpy ( str1, str2, 4) – It copies first 4 characters of str2 into str1.
Output:
source string = welcome2c
target string =
target string after strncpy( ) = welcom
Strcmpi()
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not
case sensitive. i.e, “A” and “a” are treated as same characters. Where as, strcmp()
function treats “A” and “a” as different characters.
strcmpi() function is non standard function which may not available in standard library
in C.
Both functions compare two given strings and returns zero if they are same.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = “welcome" ;
char str2[ ] = "rewelcome" ;
int i, j, k ;
i = strcmpi ( str1, “WELCOME" ) ;
j = strcmpi ( str1, str2 ) ;
k = strcmpi ( str1, "f" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
return 0;
}
Output:
0-11
Srttok():
strtok( ) function in C tokenizes/parses the given string using delimiter.
Syntax for strtok( ) function is given below.
Output:
A function that calls itself is known as a recursive function. And, this technique is known
as recursion.
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Example:
Output:
Factorial of 5 is 120
Output:
0
1
1
2
3
5
8
13
21
Exercise Programs
Exercise Programs:
Calculate the total amount of power consumed by ‘n’ devices
(Passing an array to a function):
#include <stdio.h>
#include <stdlib.h>
int main()
int size,i,n[50],s;
scanf("%d",&size);
s=devices(n ,size);
return 0;
scanf("%d",&unit);
double amount;
if((unit>=1)&&(unit<=50))//between 1 - 50 units
amount=unit*1.50;
}
else if((unit>50)&&(unit<=150))//between 50 150 units
amount=((50*1.5)+(unit-50)*2.00);
amount=(50*1.5)+((150-50)*2.00)+(unit-150)*3.00;
amount=(50*1.5)+((150-50)*2.00)+((250-150)*3.00)+(unit-250)*4;
else{
amount=0;
return amount;
int total=0;
int i;
int unit=0;
int p;
for (i=0;i<size;i++)
{
p=calc_Electricity(unit);
n[i]=p;
total=total+n[i];
Output:
Enter the number of devices : 3
int main()
int k,s,i;
int a[3]={0,1,2};
menudriven(a);
int i,n,s,p,j;
scanf("%d",&n);
for(j=0;j<3;j++){
switch(a[j])
case 0:
if(i%5==0)
p=p+1;}}
if (i%3==0)
p=p+1;}}
case 2:
p=0;
if (i%3==0&&i%5==0)
p=p+1 ;}
}}
Output:
Enter the value of n : 100
3. Predict Output.
#include <stdio.h>
int main()
{
printf("%d", main);
return 0;
}
a. Address of main function b. Compiler Error
c. Runtime Error d. Some random value
4. In C program, what is the meaning of following function prototype with
empty parameter list.
void fun()
{
/*…*/
}
a. Function can only be called without any parameter
b. Function can be called with any number of parameters of any types
c. Function can be called with any number of integer parameters.
d. Function can be called with one integer parameter.
5. Output of the following
#include<stdio.h>
void dynamic(int s, ...)
{
printf("%d ", s);
}
int main()
{
dynamic(2, 4, 6, 8);
dynamic(3, 6, 9);
return 0;
}
a. 2 3
b. Compiler Error
c. 43
d. 32
6. Predict Output.
#include <stdio.h>
int main()
{
int (*ptr)(int ) = fun;
(*ptr)(3);
return 0;
}
int fun(int n)
{
for(;n > 0; n--)
printf("C Program");
return 0;
}
a) strcpy()
b) strcat()
c) strncon()
d) memcon()
a) strcat()
b) strcon()
c) strncat()
d) memcat()
17. Which of the following is the variable type defined in header string. h?
a) sizet
b) size
c) size_t
d) size-t
18. What is the use of function char *strchr(ch, c)?
Test Data :
Enter the first number : 10
Function definition:
statements;
return x;
The major difference between actual and formal arguments is that actual
arguments are the source of information; calling programs pass actual arguments to
called functions. The called functions access the information using corresponding
formal arguments. The following piece of code demonstrates actual and formal
arguments.
return (expression);
11. How arguments are passed to functions in C? CO4 (K3)
3. List the Function Prototypes and explain it with examples CO4 (K3)
5. Recall the various types of functions supported by C. Give examples for each of
the C functions. CO4 (K3)
6. Summarize the rules that apply to a function call in C. what relationship must
be maintained between actual arguments and formal argument? CO4 (K3)
7. Outline predefined function and user defined function with example CO4 (K3)
8. Illustrate a program to find the factorial of a number using recursion CO4 (K3)
10. Build a function to reverse a given string and use it to check whether the given
string is a palindrome. CO4 (K3)
11. Construct a program to sort the array of elements in ascending order using
functions CO4 (K3)
12. Distinguish the following i)Global and local variables (6) ii)Automatic and static
variables CO4 (K3)
13. Inspect a program to find the biggest of the given three values and use it to
find the total obtained by a student which in turn is the sum of the best of
three test scores and the best of three assignment scores CO4 (K3)
14. Write a c program to assess the reverse() function which accepts a string and
display it in reverse CO4 (K3)
15. Create a C program to replace the punctuations from a given sentence by the
space character using passing an array to a function CO4 (K3)
Supportive Online
Certification
Unit IV
Certification Courses
NPTEL
Problem solving through Programming in C
https://nptel.ac.in/courses/106/105/106105171/
Coursera
1)C for Everyone: Structured Programming
https://www.coursera.org/learn/c-structured-programming
2) C for Everyone: Programming Fundamentals
https://www.coursera.org/learn/c-for-everyone
Real time Applications
Unit IV
Functions are used at many places in real life applications and some
applications are listed here.
Functions, commonly used in calculation or computation purpose
To repeated use of calculation we can use functions
To calculate area and circumferences of different shapes.
Major imaging activity
String based activity and simple calculation too we are using
functions in the form of built-in or user defined function.
Pointer related calculation
Content beyond syllabus
Unit IV
Content beyond syllabus
1) Comparison between with using string built-in function and without using string
built-in function
2) Argument of Functions
Assessment Schedule
Unit IV
Prescribed Text book &
References
Unit IV
Text books & References
TEXT BOOK
1. Reema Thareja, "Programming in C", Oxford University Press,
Second Edition, 2016
REFERENCES:
1. Kernighan, B.W and Ritchie,D.M, "The C Programming
language", Second Edition, Pearson Education, 2006
2. Paul Deitel and Harvey Deitel, "C How to Program", Seventh
edition, Pearson Publication
3. Juneja, B. L and Anita Seth, "Programming in C", CENGAGE
Learning India pvt. Ltd., 2011
4. Pradip Dey, Manas Ghosh, "Fundamentals of Computing and
Programming in C", First Edition, Oxford University Press, 2009
5. ER and ETA , “CC Foundation Program Reference materials”
Infosys Ltd.
Mini Project Suggestions
Unit IV
1) Scientific calculator
2) Library Management System
Thank you
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
OCS752
INTRODUCTION TO C
PROGRAMMING
Department: : Electrical and Electronics Engineering
Batch/Year: 2017-2021
Created by: Dr. S. Meenakshi and A.S. Vibith
Date: 21-10-2020
Table of Contents
Course Objectives
Syllabus
Course Outcomes (Cos)
CO-PO Mapping
Lecture Plan
Activity based learning
Lecture notes
Assignments
Part A Q&A
Part B Qs
List of Supportive online Certification courses
Real time applications in day to day life and to industry
Contents beyond Syllabus
Assessment Schedule (proposed and actual date)
Prescribed Text Books & Reference Books
Mini Project Suggestions
Course Objectives
OCS752 INTRODUCTION TO C PROGRAMMING LTPC
3003
OBJECTIVES
CO1 PO1 2 Identify the data type and operators to solve the problem
CO5 PO5 2 Design and Develop program using the selected compound data
2 2 2 - 2 - - - - -
CO1
K1 - 1 1
3 3 2 - 2 - - - - -
CO2
K2 - 1 1
3 3 3 - 2 - - - - -
CO3 K2 - 1 1
2 2 2 - 2 - - - - -
CO4 K3 - 1 1
2 2 2 - - - - - - -
CO5 K3 - 1 1
3 3 3 2
CO6 K3 1 1
Unit V - STRUCTURE
S.N Topics No. Propos Actual Pertain Taxon Mode of
o of ed Lecture ing CO omy Delivery
Peri Date Date Level
ods
Learn by questioning
C Data Types:
Primary data types
Derived data types
User-defined data types
Derived
Types
Array – Collection of one or more related variables of similar data type grouped under a
single name
Structure – Collection of one or more related variables of different data types, grouped
under a single name
Need of structures
In a Library, each book is an object, and its characteristics like title, author, no of pages, price
are grouped and represented by one record.
The characteristics are different types and grouped under a aggregate variable of different
types.
A record is group of fields and each field represents one characteristic. In C, a record is
implemented with a derived data type called structure. The characteristics of record are
called the members of the structure.
Book-1 Book-2 Book-3
BookID: 1211 BookID: 1212 BookID: 1213
Title : C Primer Plus Title : The ANSI C Progg. Title : C By Example
Author : Stephen Prata Author : Dennis Ritchie Author : Greg Perry
Pages : 984 Pages : 214 Pages : 498
Price : Rs. 585.00 Price : Rs. 125.00 Price : Rs. 305.00
STRUCTURE- BOOK
struct book {
int book_id ; Structure
char title[50] ; tag
char author[40] ;
int pages ;
float price ;
};
• A Structure is defined to be a collection of different data items, that
are stored under a common name.
• A structure is same as that of records. It stores related information
about an entity. Structure is basically a user defined data type that
can store related information (even of different data types) together.
Declaration of structures
• A structure is declared using the keyword struct followed by a
structure name. All the variables of the structures are declared within
the structure. A structure type is defined by using the given syntax.
• By declaring a stucture type By declaring a structure variable
struct struct-name { struct stru-name Sv1,Sv2,Sv3;
data_type var-name; (or)
data_type var-name; struct stru-name {
…}; data_type var-name;
data_type var-name;
} sv1, sv2 , sv3;
Example :
struct student {
int r_no;
char name[20];
char course[20];
float fees; };
The structure definition does not allocates any memory. It just gives a
template that conveys to the C compiler how the structure is laid out
in memory and gives details of the member names. Memory is
allocated for the structure when we declare a variable of the structure.
For ex., we can define a variable of student by writing as :
struct student stud1;
Here, struct student is a data type and stud1 is a variable. Look at another
way of declaring variables. In the following syntax, the variables are
declared at the time of structure declaration.
struct student{
int r_no;
char name[20]; char course[20]; float fees;
} stud1, stud2;
In this declaration we declare two variables stud1 and stud2 of the
structure student. So if you want to declare more than one variable of the
structure, then separate the variables using a comma. When we declare
variables of the structure, separate memory is allocated for each variable.
This is shown in Fig.
last but not the least, structure member names and names of the structure
follow the same rules as laid down for the names of ordinary variables.
However, care should be taken to ensure that the name of structure and the
name of a structure member should not be the same. Moreover, structure
name and its variable name should also be different.
The typedef (derived from type definition) keyword enables the programmer to create a
new data type name by using an existing data type. By using typedef, no new data is created,
rather an alternate name is given to a known data type. The general syntax of using the
typedef keyword is given as:
typedef existing_data_type new_data_type;
Note that typedef statement does not occupy any memory; it simply defines a new type. For
example, if we write
typedef int INTEGER;
then INTEGER is the new name of data type int. To declare variables using the new data type
name, precede the variable name with the data
type name (new). Therefore, to define an integer variable, we may now write
INTEGER num=5;
When we precede a struct name with typedef keyword, then the struct becomes a
new type. It is used to make the construct shorter with more meaningful names for
types already defined by C or for types that you have declared. With a typedef
declaration, becomes a synonym for the type.
For example, writing
typedef struct student{
int r_no;
char name[20];
char course[20];
float fees;};
Now that you have preceded the structure’s name with the keyword typedef, the
student becomes a new data type. Therefore, now you can straight away declare
variables of this new data type as you declare variables of type int, float, char,
double, etc. to declare a variable of structure student you will just write,
student stud1;
Note that we have not written struct student stud1.
NOTE: Do not forget to place a semicolon after the declaration of structures and
unions.
Accessing the members of a structure
Each member of a structure can be used just like a normal variable, but its
name will be a bit longer. A structure member variable is generally
accessed using a ‘.’ (dot operator).
The syntax of accessing a structure a member of a structure is:
struct_var.member_name
stud1.r_no membership operator
The dot operator is used to select a particular member of the structure. For
example, to assign values to the individual data members of the structure
variable studl, we may write
stud1.r_no = 01;
stud1.name = "Rahul";
stud1.course = "BCA";
stud1.fees = 45000;
To input values for data members of the structure variable stud1, we may write
scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);
Or, by writing,
struct student stud1 = {01, "Rahul", "BCA", 45000};
Figure illustrates how the values will be assigned to individual fields of the structure.
#include <stdio.h>
#include <string.h>
struct employee {
int empid;
char name[35];
int age;
float salary;};
int main() {
struct employee emp1 ;
printf("Enter the details of employee 1 : ");
scanf("%d %s %d %f" , &emp1.empid, emp1.name, &emp1.age, &emp1.salary);
printf("Emp ID:%d\nName:%s\n Age:%d\n Salary:%f",emp1.empid,
emp1.name, emp1.age,emp1.salary);}
Output :
Example program 2: Write a program using structures to read
student 3 marks and display the total and average of the
student.
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10];
int m1;
int m2;
int m3;
};
struct stud s;
void main() {
float tot,avg;
printf("\nEnter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s.regno,&s.name,&s.m1,&s.m2,&s.m3);
tot=s.m1+s.m2+s.m3;
avg=tot/3;
printf("\nThe student Details are:");
printf("\n%d\t%s\t%f\t%f",s.regno,s.name,tot,avg);
}
Output :
Enter the student regno,name,m1,m2,m3:100
aaa
87
98
78
Output:
Copying and Comparing Structures
We can assign a structure to another structure of the same type. For
example, if we have two structure variables stud1 and stud2 of type
struct student given as
struct student stud1 = {01, "Rahul", "BCA", 45000};
struct student stud2;
Then to assign one structure variable
to another, we will write
stud2 = stud1;
Figure Values of structure variables
This statement initializes the members of stud2 with the values
of members of stud1. Therefore, now the values of stud1 and
stud2 can be given as shown in Fig.
C does not permit comparison of one structure variable with
another. However, individual members of one structure can be
compared with individual members of another structure. When
we compare one structure member with another structure’s
member, the comparison will behave like any other ordinary
variable comparison.
For example, to compare the fees of two students, we will write
if(stud1.fees > stud2.fees) //to check if fees of stud1 is greater
than stud2
OUTPUT:
int day;
int month;
int year; };
struct student {
int roll_no;
char name[100];
float fees;
scanf("%d", &stud1.roll_no);
scanf("%s", stud1.name);
scanf("%f", &stud1.fees);
}
OUTPUT:
5.2 Arrays Of Structures
In the above examples, we have seen how to declare a structure and assign values
to its data members. Now, we will discuss how an array of structures is declared. For
this purpose, let us first analyse where we would need an array of structures.
In a class, we do not have just one student. But there may be at least 30 students.
So, the same definition of the structure can be used for all the 30 students. This
would be possible when we make an array of structures. An array of structures is
declared in the same way as we declare an array of a built-in data type.
Another example where an array of structures is desirable is in case of an
organization. An organization has a number of employees. So, defining a separate
structure for every employee is not a viable solution. So, here we can have a
common structure definition for all the employees. This can again be done by
declaring an array of structure employee.
The general syntax for declaring an array of structure can be given as,
struct struct_name struct_var[index];
Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = "RASHI";
stud[i].course = "MCA";
stud[i].fees = 60000;
In order to initialize the array of structure variables at the time of declaration, we can
write as follows:
struct student stud[3] = {{01, "Aman", "BCA", 45000},{02, "Aryan", "BCA", 60000},
{03,"John", "BCA", 45000}};
struct student
{
int sub[3] ;
int total ;
};
int main( ) {
struct student s[3];
int i,j;
for(i=0;i<3;i++) {
printf("\n\nEnter student %d marks:",i+1);
for(j=0;j<3;j++) {
scanf("%d",&s[i].sub[j]);
}
}
for(i=0;i<3;i++) {
s[i].total =0;
for(j=0;j<3;j++) {
s[i].total +=s[i].sub[j];
}
printf("\nTotal marks of student %d is: %d",
i+1,s[i].total );
}
}
OUTPUT:
OUTPUT:
Enter student 1 marks: 60 60 60
Enter student 2 marks: 70 70 70
Enter student 3 marks: 90 90 90
OUTPUT:
The coordinates of the point are: 2 3
Guided activity on structures and functions
struct fraction {
int numerator ;
int denominator ;
};
int main ( ) {
struct fraction f1 = { 7, 12 } ;
show ( f1 ) ;
}
OUTPUT:
7 / 12
PASSING STRUCTURES THROUGH POINTERS
C allows to crerate a pointer to a structure. Like in other
cases, a pointer to a structure is never itself a
structure, but merely a variable that holds the
address of a structure. The syntax to declare a pointer
to a structure can be given as
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr;
OR
struct struct_name *ptr;
For our student structure we can declare a pointer
variable by writing
struct student *ptr_stud, stud;
The next step is to assign the address of stud to the
pointer using the address operator (&). So to assign
the address, we will write
ptr_stud = &stud;
To access the members of the structure, one way is to
write
/* get the structure, then select a member */
(*ptr_stud).roll_no;
An alternative to the above statement can be used by using
‘pointing-to’ operator (->) as shown below.
/* the roll_no in the structure ptr_stud points to */
ptr_stud->roll_no = 01;
#include<stdio.h>
#include<string.h>
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
main()
{ struct student stud1, *ptr_stud1;
ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
strcpy(ptr_stud1->name, "Rahul");
strcpy(ptr_stud1->course, "BCA");
ptr_stud1->fees = 45000;
printf("\n DETAILS OF STUDENT");
printf("\n ---------------------------------------------");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME =", puts(ptr_stud1->name));
printf("\n COURSE = ", puts(ptr_stud1->course));
printf("\n FEES = %f", ptr_stud1->fees);
}
OUTPUT:
DETAILS OF STUDENT
---------------------------------------------
ROLL NUMBER = 1
NAME = Rahul
COURSE = BCA
FEES = 45000.000000
Guided activity on Pointer to a structure
struct product
{ Accessing structure members
int prodid;
char name[20];
through pointer :
};
int main() i) Using . ( dot ) operator :
{
( *ptr ) . prodid = 111 ;
struct product inventory[3];
struct product *ptr; strcpy ( ( *ptr ) . Name, "Pen") ;
printf("Read Product Details : \n");
for(ptr = inventory;ptr<inventory +3;ptr++) { ii) Using - > ( arrow ) operator :
scanf("%d %s", &ptr->prodid, ptr->name); ptr - > prodid = 111 ;
}
strcpy( ptr->name , "Pencil") ;
printf("\noutput\n");
for(ptr=inventory;ptr<inventory+3;ptr++)
{
printf("\n\nProduct ID :%5d",ptr->prodid);
printf("\nName : %s",ptr->name);
}
}
111 Pen
112 Pencil
113 Book
Product ID : 111
Name : Pen
Product ID : 112
Name : Pencil
Product ID : 113
Name : Book
5.4 SELF REFERENTIAL STRUCTURES
Prints P.Kiran
printf ( " %s ", s1. name ) ;
OUTPUT:
GUIDED ACTIVITY – Here is the activity you on (self referential
structure – foundation for linked list)
struct node {
int rollno; struct node *next;
Creating a Singly Linked List
}; /* deleting n2 node */
int main() { n1->next = n4;
struct node *head,*n1,*n2,*n3,*n4; free(n2);
/* creating a new node */ }
n1=(struct node *) malloc(sizeof(struct node));
n1->rollno=101; 150 101 NULL
n1->next = NULL; head 150 n1-node
/* referencing the first node to head pointer */
head = n1; 150 101 720 102 NULL
/* creating a new node */ 720
150
n2=(struct node *)malloc(sizeof(struct node)); n1-node n2-node
n2->rollno=102;
n2->next = NULL; 150 101 720 102 910 104 NULL
/* linking the second node after first node */ 150 720 910
n1-node n2-node n3-node
n1->next = n2;
/* creating a new node * /
n3=(struct node *)malloc(sizeof(struct node)); 150 101 400 102 720 104 NULL
n3->rollno=104; head 150 400 910
n3->next=NULL; n1-node n2-node 103 910 n3-node
/* linking the third node after second node */ 720
n4-node
n2->next = n3;
/* creating a new node */
n4=(struct node *)malloc (sizeof (struct node)); 150 101 720 103 910 104 NULL
n4->rollno=103; head 150
720 910
n4->next=NULL; n3-node
n1-node n4-node
/* inserting the new node between 102 720
second node and third node */
400
n2->next = n4; n2-node
n4->next = n3;
Implementing Singly Linked List
int main(){
struct date d1 = {7, 3, 2005};
struct date d2 = {24, 10, 2005};
date_print(d1);
int cmp = date_cmp(d1, d2);
if (cmp == 0)
printf(” is equal to”);
else if (cmp > 0)
printf(” is greater i.e. later than “);
else printf(” is smaller i.e. earlier than”);
date_print(d2);
return 0;}
struct date {
int day, month, year; };
int main() {
struct date dt1 = {05, 10, 2020};
struct date dt2 = {17, 05, 2004};
int cmp = date_diff(dt1, dt2);
return cmp;}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Print current date and time in C
int main(void){
// variables to store date and time components
int hours, minutes, seconds, day, month, year;
// time_t is arithmetic time type
time_t now;
// Obtain current time
// time() returns the current time of the system as a time_t value
time(&now);
// Convert to local time format and print to stdout
printf("Today is : %s", ctime(&now));
// localtime converts a time_t value to calendar time and
// returns a pointer to a tm structure with its members
// filled with the corresponding values
struct tm *local = localtime(&now);
return 0;
}
Compute the number of days an employee came late to the office by considering his
arrival time for 30 days (Use array of structures and functions)
#include <stdio.h>
#include <time.h>
struct student{
char lastName[100];
char firstName[100];
char *date;
int age;
int id;};
int main(){
int n=1;
struct student s[n];
int x;
do{
printf("main menu :\n1.add\n2.delete\n3.diplay\n4.exit\n");
scanf("%d",&x);
switch(x){
case 1:
for(int i=0;i<n;i++){
printf("Enter first name\n");
scanf("%s",s[i].firstName);
printf("Enter last name\n");
scanf("%s",s[i].lastName);
printf("Enter your id\n");
scanf("%d",&s[i].time);
printf("Enter your age\n");
scanf("%d",&s[i].age);
time_t timer;
timer=time(NULL);
s[i].date = asctime(localtime(&timer));
//s[i].time=time(&now);
}
for(int i=0;i<n;i++){
printf("id\tfirstName\tlastName\tage\tdate\n%d\t%s\t%s\t%d\t%s",s[i].id,s[i].firstNa
me,s[i].lastName,s[i].age,s[i].date);
}
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
printf("wrong choice");
break;
}
}while(x!=4);
return 0;
}
Note: time_t t;
time(&t);
printf("\n current time is : %s",ctime(&t));
Quiz
Test Yourself –5.1 to 5.6 Topics
(quiz)
6. Develop a structure namely Book and create array of Book structure with K2 CO3 S
size of ten.
7. Invent the application of size of operator to this structure. Consider the K2 CO3 S
declaration:
struct
{
char name;
int num;
} student;
2. Explain about the structures and its operations with example programs K3 CO3 S
(13)
3. Explain about array of structures and nested structures with example.(13) K3 CO3 A
statement. (13)
5. Write a C program using structures to prepare the employee payroll. (13) K3 CO3 A
6. Compute the number of days an employee came late to the office by K3 CO3 S
considering his arrival time for 30 days (Use array of structures and function)
Supportive Online
Certification
Unit V
Certification Courses
NPTEL
Problem solving through Programming in C
https://nptel.ac.in/courses/106/105/106105171/
Coursera
1)C for Everyone: Structured Programming
https://www.coursera.org/learn/c-structured-programming
2) C for Everyone: Programming Fundamentals
https://www.coursera.org/learn/c-for-everyone
Real time Applications
Unit V
Functions are used at many places in real life applications and some
applications are listed here.
commonly used in calculation or computation purpose
Major imaging activity
Content beyond syllabus
Unit V
Content beyond syllabus
1) Comparison between structure and union
Assessment Schedule
Unit V
Prescribed Text book &
References
Unit V
Text books & References
TEXT BOOK
1. Reema Thareja, "Programming in C", Oxford University Press,
Second Edition, 2016
REFERENCES:
1. Kernighan, B.W and Ritchie,D.M, "The C Programming
language", Second Edition, Pearson Education, 2006
2. Paul Deitel and Harvey Deitel, "C How to Program", Seventh
edition, Pearson Publication
3. Juneja, B. L and Anita Seth, "Programming in C", CENGAGE
Learning India pvt. Ltd., 2011
4. Pradip Dey, Manas Ghosh, "Fundamentals of Computing and
Programming in C", First Edition, Oxford University Press, 2009
5. ER and ETA , “CC Foundation Program Reference materials”
Infosys Ltd.
Mini Project Suggestions
Unit V
1) Scientific calculator using strcture
2) Employee Management System
Thank you
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.