0% found this document useful (0 votes)
50 views174 pages

C Language Material Ameerpet Technologies

The document provides a comprehensive introduction to the C programming language, covering its history, application structure, programming elements, and variable types. It explains the importance of functions, local and global variables, and data types, along with practical examples and syntax. Additionally, it discusses the use of C software and libraries for developing applications, emphasizing the platform dependency of C programs.

Uploaded by

aswinmatriz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views174 pages

C Language Material Ameerpet Technologies

The document provides a comprehensive introduction to the C programming language, covering its history, application structure, programming elements, and variable types. It explains the importance of functions, local and global variables, and data types, along with practical examples and syntax. Additionally, it discusses the use of C software and libraries for developing applications, emphasizing the platform dependency of C programs.

Uploaded by

aswinmatriz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 174

C

Programming
&
Logical Thinking

SRINIVAS GARAPATI

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet,


Hyderbad-500016. Contact – 9119556789 / 7306021113
Contents
S No Topic Page Num
01 Introduction to C 02
02 Programming Elements 04
03 C Application Structure 05
04 Variables in C 06
05 Functions and calling 08
06 Local and Global Variables 11
07 Data types in C 14
08 Operators in C 20
09 Control Statements in C 31
10 Loop statements in C 44
11 Menu Driven Programs 62
12 Nested Loops in C 65
13 Range based programs 67
14 Pattern programs in C 72
15 Functions in C 81
16 Arrays in C 87
17 String Handling in C 106
18 Structures in C 116
19 Unions in C 124
20 Pointers in C 127
21 Dynamic Memory Allocation 142
22 File Handling in C 148
23 Enumeration in C 156
24 Typedef in C 158
25 Storage Classes in C 160
26 Command Line Arguments in C 167
27 Pre-Processor in C 170

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Introduction to C

History:
 C is a Programming language developed by Dennis Ritchie in 1972.
 It is mainly used in development of Operating Systems, Embedded software, Device
drivers, application software etc.

Programming language:
 Programming languages are used to develop applications.
 Computer applications Store data and perform operations on data.

For example: Banking application store Accounts data and perform transactions like
withdraw, deposit etc.

Applications: are mainly two types


1. Standalone application:
 Application runs from single machine.
 Data connection (internet) is not required to run.
 Standalone applications are
o System software: Controls Hardware components and other software
components. For example, Operating System.
o Application software: is used to perform specific user task. For example,
MS-Office, VLC Player, Browser etc.

Note: C is Platform Dependent by which we can develop only Standalone applications

Platform Dependency:
 Platform means “Operating System”
 C and C++ Compilers convert the source program into specific Operating system
understandable code. Hence the compiled code is compatible to same Operating system
on which it has compiled.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
2. Web application:
 Application runs from multiple machines connected in a network.
 Web application installed in server.
 Data connection is required to run the application.
 Examples: gmail.com, icici.com, irctc.in etc.

Note: We use technologies to develop Web applications which are platform independent

C-software:
 C is a standalone software.
 We have different types of C-software to develop and run C Programs. For example,
Turbo-C, C-Free, Code Blocks etc.
 Download and install any C IDE to write and run programs easily.

Download the latest version of C-Free from:


https://c-free.soft32.com/

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Programming Elements

Program Elements: Program is a set of instructions. Every Program consists,


1. Identity
2. Variables
3. Functions

1. Identity:
o Identity of a program is unique.
o Programs, Classes, Variables and Methods having identities
o Identities are used to access these members.

2. Variable:
o Variable is an identity given to memory location.
or
o Named Memory Location
o Variables are used to store information of program(class/object)

Syntax Examples

int age = 23;


datatype identity = value; double salary = 35000.00;
char gender = ‘M’;
char* name = “Amar”;

3. Function:
 Function is a block of instructions with an identity
 Function performs operations on data(variables)
 Function takes input data, perform operations on data and returns results.

Syntax Example

returntype identity(arguments) int add(int a, int b)


{ {
body; int c = a+b;
} return c;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Application Structure

Program:
 C program consists variables and functions.
 Program execution starts with main() function automatically.

Main.c
#include<stdio.h>
void main()
{
printf("Hello");
}

Application:
 C application contains more than one program.
 We connect these programs by calling one program functions from another program.
 We connect these programs using #include.
 Only one program contain main() function from which application execution starts.

Main.c Arithmetic.c
#include<stdio.h>
#include<arithmetic.c> void add()
void main() {
{ printf("Add");
// invoking functions }
add(); void subtract()
subtract(); {
} printf("Subtract");
}

#include:
 A pre-processor directive is used to connect the programs in C application.

Library:
 Library is a collection of pre-define programs called Header-files.
 Header-file contains Variables and Methods.
 Library is used to develop C application quickly.
 Some of the header file names as follows:

stdio.h math.h conio.h string.h graphics.h


printf() sqrt() clrscr() strlen() circle()
scanf() rand() getch() strrev() line()

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Variables in C
Variables:
 Variable is an Identity given to memory location.
 Variable is used to store information.
 We need to specify the datatype of every variable.

Syntax:
datatype identifier = value;

Examples:
char name[] = “amar”
int age = 23
char* mail = “[email protected]
char gender = ‘M’;
double salary = 35000;

Note: Value of a variable will change. For example “age of a person”

Variable Declaration, Assignment, Modify and Initialization:


Declaration:
 Creating a variable without value.
 For example
o int a ;

Assignment:
 Assigning a value to the variable which is already declared.
 For example,
o int a ; // declaration
o a=10 ; // assignment

Modify:
 Increase or decrease the value of a variable
 For example,
o int a ; // declaration
o a=10 ; // assignment
o a=a+20; //modify

Initialization:
 Defining a variable along with value
 For example,
o int a = 10 ; // initialization
o a = a+20 ; // modify

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Rules to create variable:
 Variable contains alphabets(A-Z , a-z) or Digits (0-9) and only one symbol( _ ).
 Variable should not starts with digit
o int 5a = 10; (error)
o int a5 = 10;
o int 1stRank; (error)

 Variable should not contain spaces. 8355832471


o int acc num = 1001; (error)
o int acc_num = 1001;

 Variable should not allow other symbols except _


o int acc_num ;
o int acc-num;

 variable can starts with special symbol _


o int _acc_num;
o int _1rank;

 Variable should not match with keywords.


o int if = 10 ;
o int else = 20 ;

Variables classified into:


1. Local variables:
a. Defining a variable inside the block or function.
b. We cannot access local variables outside to the block.
2. Global variables:
a. Defining a variable outside to all functions.
b. We can access global variable from all functions.

Note: We will discuss briefly about Local and Global variables after Functions concept

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Functions and Calling
Main() function:
 Main() function must be defined in every C program
 C program execution starts from main() function.
 Main() function automatically invoke by Operating system.

User function:
 Defining other functions along with main() function.
 We must declare(prototype) of user function.

Calling the function:


 Only main() function invokes automatically by OS
 All other functions in C program must be called manually.
 User function logic executes only when we call.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
The following program clearly explains how the control back to calling function after execution
of called function.
Calling Function: the function from which other function called.
Called Function: the function which is called from other function.

We can invoke the function any number of times once it has defined.

 We can define any number of functions in C-Program.


 We can define the functions in any order.
 We invoke the defined functions in any order.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Execution flow of HelloWorld program briefly:
 Every C Program execution starts with main() function.
 OS invokes main() function automatically.
 #include is a pre-processor directive which is used to connect programs in C application.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Local and Global variables

Local variables:
 A variable inside the function or block.
 Local variable cannot access outside of that block.
int main()
{
int a ; -> local variable
}

Local variables automatically initialize with garbage values. We cannot guess garbage
value.
#include<stdio.h>
int main()
{
int a;
printf("%d \n", a); -> Prints unknown value.
return 0;
}

Format specifiers:
 Formatting the result is very important before display to user.
 We use following format specifiers to read and print different types of data values.
Data type Format specifier
int %d
char %c
float %f
string %s

Display information of different data types:


#include<stdio.h>
int main (){
char* name = "Amar";
int age = 23;
float salary = 35000;
char gender = 'M';
printf("Name is : %s \n", name);
printf("Age is : %d \n", age);
printf("Salary is : %f \n", salary);
printf("Gender is : %c \n", gender);
return 0;
}
We can access local variables only from the same function in which they have defined.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void test();
int main (){
int a=10;
printf("a value in main : %d \n", a);
test();
return 0;
}
void test(){
printf("a value in test :%d \n", a); // Error :
}

Global Variables:
 Defining a variable outside to all functions.
 Global variables can be accessed from all the functions.

#include<stdio.h>
void test();
int a=10;
int main (){
printf("a value in main : %d \n", a);
test();
return 0;
}
void test(){
printf("a value in test :%d \n", a);
}

Global variables automatically initialize with default values:


Datatype Default Value
int 0
float 0.00000
char Blank
string Null
#include<stdio.h>
int a;
float b;
int main (){
printf("int : %d \n", a);
printf("float : %f \n", b);
return 0;
}
Escape Sequences: Performs specific action when we use inside the String.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
\b Backspace
\n New line
\r Carriage return
\t Horizantal tab
\v Vertical tab
\\ Backslash
\' Single quote
\" Double quote
\0 Null

Display String in multiple lines:


#include<stdio.h>
int main (){
printf("String \ndisplayed \nin \nMultiple \nLines");
return 0;
}

Display information with tab spaces:


#include<stdio.h>
int main (){
int a=10, b=20, c=30;
printf("%d\t%d\t%d", a, b, c);
return 0;
}

Display Message with Single Quotations:


#include<stdio.h> #include<stdio.h>
int main () int main ()
{ {
printf("'C' Tutorial\n"); printf("\'C\' Tutorial\n");
return 0; return 0;
} }

Display Message with Double Quotations:


#include<stdio.h>
int main (){
printf("\"C-Language\" Tutorial\n");
return 0;
}

Data Types in C

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Data type:
 We need to specify the data type in variable declaration.
 Data type specifies, the type of data is allowed to store.

Data types are classified into:

Primitive types: In the above diagram primitive types are generalized. Primitive types sub
classified as follows

Following table describes the data type with size, format specifier and limits:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Character data type: Char type is used to store alphabets, symbols and digits. We represents
character with single quotes.
#include <stdio.h>
int main(){
char v1 = 'a';
char v2 = '5';
char v3 = '$';
printf("v1 value is : %c \n", v1);
printf("v2 value is : %c \n", v2);
printf("v3 value is : %c \n", v3);
return 0;
}

How character stores into memory?


 Every character represented by an integer value called ASCII.
 The range of ASCII from 0 to 255(1 byte limits)
 Each character occupies 1 byte memory to store the corresponding integer value.

#include <stdio.h>
int main(){
char v1 = 'a';
char v2 = '5';
char v3 = '$';
printf("%c ascii value is : %d \n", v1, v1);
printf("%c ascii value is : %d \n", v2, v2);
printf("%c ascii value is : %d \n", v3, v3);
return 0;
}

Output:
a ascii value is : 97
5 ascii value is : 53
$ ascii value is : 36

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
limits.h: It is a header file providing constant variables assigned with limits of each data type..

Program to display short int information (size and limits):


#include <stdio.h>
#include <limits.h>
int main()
{
printf("Signed short min : %d \n", SHRT_MIN);
printf("Signed short min : %d \n", SHRT_MAX);
printf("Unsigned short max : %d \n", USHRT_MAX);
return 0;
}

Program to display Character type info:


#include <stdio.h>
#include <limits.h>
int main(){
printf("signed char min val : %d \n", SCHAR_MIN);
printf("signed char max val : %d \n", SCHAR_MAX);
printf("unsigned char max val : %d \n", UCHAR_MAX);
return 0;
}

What happens when we try to store the value beyond the limits of datatype?
 Every variable can store the value within the limits only.
 When limit exceeded, it counts the value in the specified limit and store some other
value.

#include<stdio.h>
int main(){
char ch = 130;
printf("ch val : %d \n", ch); // prints -126
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
char c1=256, c2=1024;
printf("c1 : %d \n", c1);
printf("c2 : %d \n", c2);
return 0;
}
Output:
c1 : 0
c2 : 0

Short int limits:

#include<stdio.h>
int main()
{
short s = 32769;
printf("s val : %d \n", s);
return 0;
}

#include<stdio.h>
int main()
{
short s = -32744;
printf("s val : %d \n", s);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
sizeof(): a pre-defined function used to find the size of Variable, value, Datatype etc.

Program to find the sizes of different variables:


#include <stdio.h>
int main(){
char c;
short s;
float f;
printf("char size : %d \n", sizeof(c)); // prints-1
printf("short size : %d \n", sizeof(s)); // prints-2
printf("float size : %d \n", sizeof(f)); // prints-4
return 0;
}

Program to find the sizes of data types directly:


#include <stdio.h>
int main(){
printf("char size : %d \n", sizeof(char));
printf("short size : %d \n", sizeof(short));
return 0;
}

Finding the size of expression: In expression, which type occupies highest memory will be the
output.
short + long  long
float + double  double

#include <stdio.h>
int main(){
char c;
short s;
printf("char + short : %d \n", sizeof(c+s));
return 0;
}

ASCII(American Standards Code of Information Interchange): ASCII represents all the


characters of language with constant integer values.
A-65 a-97 0-48 #-35
B-66 b-98 1-49 $-36
.. .. .. ..
.. .. .. ..
Z-90 z-122 9-57 ..
scanf():

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 C library is a Collection of Header files.
 Header file contains Variables and Functions.
 printf() and scanf() functions belongs to stdio.h header file.
 Printf() function is used to display the information on Monitor(standard output).
 Scanf() function is used to read information from keyboard(standard input)

Address operator:
 We need to specify the location (memory address) using variable to read the data.
 ‘&’ is called Address operator in C.

#include <stdio.h>
int main()
{
int a;
printf("Enter a value : ");
scanf("%d", &a);
printf("a value is : %d \n", a);
return 0;
}

Program to display the address of variable:


#include <stdio.h>
int main()
{
int val=10;
char sym='$';
printf("Address of val : %d \n", &val);
printf("Value of val : %d \n", val);
printf("Address of sym : %d \n", &sym);
printf("Value of sym : %c \n", sym);
return 0;
}

Operators in C

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Operator: It is a symbol that performs operation on data.

Assignment operator: This operator is used to store value into variable.


Syntax: Example:
variable = value; a = 10
a = b = 10;

Example codes on Assignment operator:


#include<stdio.h> #include<stdio.h>
int main(){ int main()
short a, b, c, d; {
a = 10; short a, b, c, d;
b = a; a = 10;
c = a+b; b = c = a;
d = sizeof(c); d = a+b+c;
printf("%d,%d,%d,%d \n", a, b, c, d); printf("d val : %d \n", d);
return 0; return 0;
} }

Arithmetic operators: performs all arithmetic operations on data.


 Operators are +, -, *, / , %
 Division(/) operator returns the quotient after division.
 Mod(%) operator returns remainder after division.

We cannot apply Mod(%) operation on decimal data:


#include <stdio.h>
int main(){
float a=5, b=2;
printf("Quotient : %f \n", a/b); // prints 2.500000
printf("Remainder : %f \n", a%b); // Error:
return 0;
}

We can specify the length of digits while displaying decimal value:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
float a=5, b=2;
printf("%.2f \n", a/b); // prints 2.50
return 0;
}

Operators Priority: We need to consider the priority of operators if the expression has more
than one operator. Arithmetic operators follow BODMAS rule.
Priority Operator
() First. If nested then inner most is first
*, / and % Next to (). If several, from left to right
+, - Next to *, / , %. If several, from left to right

Examples expressions with evaluations:


5+3-2 5*3%2 5+3*2 (5+3)*2
8-2 15%2 5+6 8*2
6 1 11 16

Basic programs using Arithmetic Operators


Program to add 2 numbers:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter two numbers : \n");
scanf("%d%d", &a, &b);
c = a+b;
printf("Sum is : %d \n", c);
return 0;
}

Program to find the sum and average of 3 numbers:


#include <stdio.h>
int main(){
int a, b, c, sum, average;
printf("Enter two numbers : \n");
scanf("%d%d%d", &a, &b, &c);
sum = a+b+c;
average = sum/3;
printf("Sum is : %d \n", sum);
printf("Average is : %d \n", average);
return 0;
}
Program to find the sum of First N numbers:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main() {
int n, sum;
printf("Enter n value : ");
scanf("%d", &n);
sum = n*(n+1)/2;
printf("Sum of first %d numbers is : %d \n", n, sum);
return 0;
}

Program to swap two numbers:


int main(){
int a, b, c;
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Before swap : %d \t %d \n", a, b);
c = a;
a = b;
b = c;
printf("After swap : %d \t %d \n", a, b);
return 0;
}

Program to display the last digit of given number:


int main(){
int n, last;
printf("Enter number : ");
scanf("%d", &n);
last = n%10;
printf("Last Digit is : %d \n", last);
return 0;
}

Program to remove the last digit of given number:


int main()
{
int n;
printf("Enter number : ");
scanf("%d", &n);
n = n/10;
printf("Removed last digit : %d \n", n);
return 0;
}
Program to swap 2 numbers without using 3rd variable:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include <stdio.h>
int main(){
int a, b;
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Before swap : %d \t %d \n", a, b);
a = a+b;
b = a-b;
a = a-b;
printf("After swap : %d \t %d \n", a, b);
return 0;
}

Calculate total amount to pay based on quantity of fruits purchased:


#include <stdio.h>
int main(){
float quantity, price, amount;
printf("Enter quantity of fruits : ");
scanf("%f", &quantity);
printf("Enter price per dozen : ");
scanf("%f", &price);
price = (quantity/12) * price;
printf("Total amount to pay : %f \n", price);
return 0;
}

Program to display total salary for given basic salary:


#include <stdio.h>
int main(){
float basic, ta, da, hra, total;
printf("Enter basic salary : ");
scanf("%f", &basic);
ta = 0.2*basic;
da = 0.15*basic;
hra = 0.25*basic;
total = basic + ta + da + hra;
printf("Total salary : %f \n", total);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Conditional operator: This operator validates the condition and execution corresponding
statement. It is also called Ternary operator.

Program to display Biggest of 2 numbers:


#include <stdio.h>
int main(){
int a, b;
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
a>b ? printf("A is big \n") : printf("B is big \n");
return 0;
}

Program to check the given number is Even or not:


#include <stdio.h>
int main(){
int n;
printf("Enter number : \n");
scanf("%d", &n);
n%2==0 ? printf("Even \n") : printf("Not even \n");
return 0;
}

We can define conditional statement inside another conditional statement:


Program to check the biggest of 3 numbers:
#include <stdio.h>
int main(){
int a, b, c, big;
printf("Enter 3 numbers : \n");
scanf("%d%d%d", &a, &b, &c);
big = a>b && a>c ? a : b>c ? b : c;
printf("Big one is : %d \n", big);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Relational operators: These operator returns true(1) or false(0) by validating the relation
among the data. Operators are >, <, >=, <=, ==, !=

#include<stdio.h>
int main()
{
printf("5>3 : %d \n", 5>3);
printf("5<3 : %d \n", 5<3);
printf("5==3 : %d \n", 5==3);
printf("5!=3 : %d \n", 5!=3);
return 0;
}

In expression, arithmetic operators evaluates before relational operators:


#include<stdio.h>
int main()
{
printf("5>3+4 : %d \n", 5>3+4);
return 0;
}

Note: All relational operators having same priority. Hence these operators execute from left to
right
#include<stdio.h> Explanation:
int main()
{
int a=25, b=15, c=5, d, e;
d = a>b>c;
e = b<a>c;
printf("%d, %d \n", d, e);
return 0;
}
#include<stdio.h> Explain here:
int main()
{
int a=0, b=0, c=0, d;
d = a>b==c;
printf("Output : %d\n", d);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Modify operators:
 Modify operators increase or decrease the value of variable by 1
 Operators are ++, --
 Modify operators also called unary operators (operate on single operand)

Modify Operators
Increment Operators Decrements Operators
Pre-Increment Post-Decrement Pre-Decrement Pos-Decrement
Example: Example: Example: Example:
int a = 5; int a = 5; int a = 5; int a = 5;
print(++a); // 6 print(a++); // 5 print(--a); // 4 print(a--); // 5
print(a); //6 print(a); //6 print(a); //4 print(a); //4

Expressions with modify operators evaluate as follows:


1. Pre-Increment and Pre-Decrement
2. Substitute values in expression
3. Evaluation of expression
4. Assignment
5. Post-Increment and Post-Decrement

Code snippets to understand the execution flow of Modify operators:


int main(){ int main(){ int main(){
int a=5; int a=5; int a=5;
printf("%d\n", ++a); printf("%d\n", a++); printf("%d\n", --a);
printf("%d\n", a); printf("%d\n", a); printf("%d\n", a);
return 0; return 0; return 0;
} } }
int main(){ int main(){ int main(){
int a=5; int a=5, b; int a=5, b;
printf("%d\n", a--); b = ++a; b = a++;
printf("%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
return 0; printf("b=%d\n", b); printf("b=%d\n", b);
} return 0; return 0;
} }
int main(){ int main(){ int main(){
int a=5, b; int a=5, b; int a=5, b;
b = --a; b = a--; b = ++a + ++a;
printf("a=%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
printf("b=%d\n", b); printf("b=%d\n", b); printf("b=%d\n", b);
return 0; return 0; return 0;
} } }

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() int main()
{ { {
int a=5, b; int a=5, b; int a=5, b;
b = ++a + a++; b = a++ + a++; b = --a + --a;
printf("a=%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
printf("b=%d\n", b); printf("b=%d\n", b); printf("b=%d\n", b);
return 0; return 0; return 0;
} } }
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() int main()
{ { {
int a=5, b; int a=5, b; int a=5, b;
b = --a + a--; b = a-- + a--; b = a++ + ++a + a--;
printf("a=%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
printf("b=%d\n", b); printf("b=%d\n", b); printf("b=%d\n", b);
return 0; return 0; return 0;
} } }

Logical Operators:
 These operators return true (1) or false (0) by evaluating more than one expression.
 Operators are,
o Logical-AND (&&)
o Logical-OR (||)
o Logical-NOT (!)
 Following truth table represents the results of Logical operators’ evaluation

A B A&&B A||B !A !B
T T T T F F
T F F T F T
F T F T T F
F F F F T T

#include <stdio.h>
int main(){
printf("5>3 && 5!=3 = %d \n", 5>3 && 5!=3);
printf("5>3 && 5==3 = %d \n", 5>3 && 5==3);
printf("5>3 || 5==3 = %d \n", 5>3 || 5==3);
printf("5<3 || 5==3 = %d \n", 5<3 || 5==3);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Compound assignment Operators:
 Compound assignment operators reduce the size of modify expression.
 Operators are +=, -=, *=, &&=, >>=

A+=10  A=A+10 Balance += Deposit  Balance = Balance + Deposit


A+=B  A=A+B Balance -= Withdraw  Balance = Balance - Withdraw
X*=Y  X=X*Y

Bitwise operators:
 These operators convert the input into binary data and perform operations.
 Operators are,
a. Bitwise AND (&)
b. Bitwise OR (|)
c. Bitwise XOR (^)
 The following table explains the how Bitwise operations returns the results.

Truth table:
A B A&B A|B A^B
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Note: After performing bitwise operations, results will be displayed in Decimal format only.
Bitwise – AND operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a & b); & 00011001
return 0; ----------
} 00001000 = 8 (In decimal)

Bitwise – OR operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a | b); | 00011001
return 0; ----------
} 00011101 = 29 (In decimal)

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Bitwise – XOR operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a ^ b); ^ 00011001
return 0; -----------
} 00010101 = 21 (In decimal)

Bitwise Complement Operator (~): It changes 1 to 0 and 0 to 1.


For example:
~ 00100011
35 = 00100011 (In Binary) ----------
11011100 = 220 (In decimal)

The bitwise complement of 35 (~35) is -36 instead of 220, but why?


Answer: It is the value of 2’s complement

2's Complement:
 The 2's complement of a number is equal to the complement of that number plus 1.
 Bitwise Complement of Any Number N is -(N+1).

Decimal Binary 2's complement


0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Formula of 2’s complement:


Bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)

Program to understand Bitwise complement operator:


#include <stdio.h>
int main()
{
printf("Output = %d\n", ~35);
printf("Output = %d\n", ~-12);
return 0;
}
Output = -36
Output = 11

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Shift Operators:
 These operators are used to shift binary bits either to Left or Right
 The operators are,
o Left Shift (<<)
o Right Shift(>>)

Theoretical formulas:
 For Right Shift: n/2s
 For Left Shift: n*2s
o Where ‘n’ is the data and ‘s’ is the number of bits to shift

Right Shift operator(>>):


int main(){
int x=32;
int y=x>>2; 32/22
printf("y val : %d\n", y); 32/4
return 0; 8
}

Left Shift operator(<<):


int main(){
int x=2;
int y=x<<3; 2*23
printf("y val : %d\n", y); 2*8
return 0; 16
}

Type Casting: Conversion of data from one type to another type.

 If we perform division operations on integer types, the result will be an integer.


 We need to convert the integer type into float type before division operations.
int main() int main() int main()
{ { {
int a=5, b=2; int a=5, b=2; int a=5, b=2;
float res=a/b; float res=(float)a/b; float res=(float)(a/b);
printf("Res : %f\n",res); printf("Res : %f\n",res); printf("Res : %f\n",res);
return 0; return 0; return 0;
} } }
Output: 2.000000 Output: 2.500000 Output: 2.000000

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Control Statements in C
Sequential statements:
 Statement is a line of code.
 Sequential Statements execute one by one from top-down approach.

#include<stdio.h>
int main(){
int a, b, c;
a = 10;
b = a;
c = a*b;
printf("c value : %d \n", c);
return 0;
}

Control statements: Statements execute randomly and repeatedly based on conditions.

If block: execute a block of instructions only when condition is valid.


Syntax Flow Chart

if(condition)
{
statements;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to give 15% discount to Customer if the bill amount is >= 5000
#include<stdio.h>
int main(){
float bill=0, discount=0;
printf("Enter Bill amount : ");
scanf("%f", &bill);
if(bill>=5000)
{
discount = 0.15*bill;
bill = bill-discount;
}
printf("Final bill to pay : %f \n", bill);
printf("Your discount is : %f \n", discount);
return 0;
}
Output: Enter Bill amount : 6000.0
Final bill to pay : 5100.0
Your discount is : 900.0

Program to give 20% bonus to Employees having more than 5 years’ experience
#include<stdio.h>
int main(){
int exp=0;
float salary=0, bonus=0;
printf("Enter Employee salary : ");
scanf("%f", &salary);
printf("Enter Expierience : ");
scanf("%d", &exp);
if(exp>5)
{
bonus = 0.20 * salary;
salary = salary + bonus;
}
printf("Your salary : %f \n", salary);
printf("Bonus : %f \n", bonus);
return 0;
}
Output: Enter Employee salary : 25000
Enter Expierience : 6
Your salary : 30000.000000
Bonus : 5000.000000

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
if - else block: Else block can be used to execute an optional logic if the given condition has
failed.
Syntax Flow Chart

if (condition){
If – Stats;
}
else{
Else – Stats;
}

Program to check the input number is Positive or Not:


Positive Number: The number greater than 0 is called positive number.
#include<stdio.h>
int main(){
int num;
printf("Enter number : ");
scanf("%d", &num);
if(num>0)
printf("Positive number \n");
else
printf("Not Positive number \n");
return 0;
}

Program to check the Person eligible for Vote or Not:


#include<stdio.h>
int main(){
int age;
printf("Enter age : ");
scanf("%d", &age);
if(age>=18)
printf("You are eligible for Vote \n");
else
printf("You are not eligible for Vote \n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to find the biggest of 2 numbers:
#include<stdio.h>
int main(){
int a, b;
printf("Enter a value : ");
scanf("%d", &a);
printf("Enter b value : ");
scanf("%d", &b);
if(a>b)
printf("a is big \n");
else
printf("b is big \n");
return 0;
}

Program to check the number is Even or not:


Even Number: The number which is divisible by 2 is called Even number.
#include<stdio.h>
int main(){
int n;
printf("Enter number : ");
scanf("%d", &n);
if(n%2==0)
printf("%d is Even \n", n);
else
printf("%d is not Even \n", n);
return 0;
}

Program to check the number divisible by both 3 and 5 or not:


We use logical AND(&&) operator to check more than 1 condition is True.
#include<stdio.h>
int main(){
int n;
printf("Enter number : ");
scanf("%d", &n);
if(n%3==0 && n%5==0)
printf("%d divisible by both 3 and 5 \n", n);
else
printf("%d is not divisible by both 3 and 5 \n", n);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check the character is Vowel or not:
Vowels are a, e, i, o, u.
#include<stdio.h>
int main()
{
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
printf("Given character is Vowel \n");
else
printf("Given character is not Vowel \n");
return 0;
}

Program to check the character is Upper case alphabet or not:


#include<stdio.h>
int main()
{
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if(ch>='A' && ch<='Z')
printf("Upper case Alphabet character \n");
else
printf("Not an Upper case Alphabet character \n");
return 0;
}

Program to check the number between 30 and 50 or not:


#include<stdio.h>
int main()
{
int n;
printf("Enter number : ");
scanf("%d", &n);
if(n>=30 && n<=50)
printf("Number between 30 and 50\n");
else
printf("Not between 30 and 50 \n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check the login details are correct or not:
#include<stdio.h>
int main(){
char user[20];
int pwd;
printf("Enter user name : ");
scanf("%s", user);
printf("Enter password : ");
scanf("%d", &pwd);
if(strcmp(user, "amar")==0 && pwd==1234)
printf("Login success\n");
else
printf("Login failed\n");
return 0;
}

Program to check the character is alphabet or not:


#include<stdio.h>
int main(){
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
printf("Alphabet character \n");
else
printf("Not an Alphabet character \n");
return 0;
}

Program to check the character is Symbol or not:


#include<stdio.h>
int main(){
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if(!((ch>='A' && ch<='Z') || (ch>='a' && ch<='z') || (ch>='0'&&ch<='9')))
printf("It's a symbol\n");
else
printf("It's not a symbol\n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
If-else-if ladder:
 It is allowed to defined multiple if blocks sequentially.
 It executes only one block among the multiple blocks defined.

Program to check the number is positive or negative or zero:


#include<stdio.h>
int main(){
int n;
printf("Enter a number : ");
scanf("%d", &n);
if(n>0)
printf("Positive number\n");
else if(n<0)
printf("Negative number\n");
else
printf("zero");
return 0;
}

Program to check the Character is Alphabet or Digit or Symbol:


#include<stdio.h>
int main(){
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if(ch>='A' && ch<='Z')
printf("Upper case alphabet\n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
else if(ch>='a' && ch<='z')
printf("Lower case alphabet\n");
else if(ch>='0' && ch<='9')
printf("Digit\n");
else
printf("Symbol \n");
return 0;
}

Program to find the biggest of 3 numbers:


#include<stdio.h>
int main(){
int a, b, c;
printf("Enter 3 numbers : ");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
printf("A is big\n");
else if(b>c)
printf("B is big\n");
else
printf("C is big\n");
return 0;
}

Program to check the input year is Leap or not:


 If the year divisible by 400 is called Leap year
 If the year divisible by 4 is called Leap year.
 If the year divisible by 100 is not leap year (except 400 multiples)
#include<stdio.h>
int main(){
int n;
printf("Enter year : ");
scanf("%d", &n);
if(n%400==0)
printf("Lep year \n");
else if(n%4==0 && n%100!=0)
printf("Lep year \n");
else
printf("Not leap year \n");

return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check profit or loss:
#include<stdio.h>
int main()
{
int originalCost, sellingPrice;
printf("Enter Original Cost : ");
scanf("%d", &originalCost);
printf("Enter Selling Price : ");
scanf("%d", &sellingPrice);
if(originalCost < sellingPrice)
printf("Profit\n");
else if(originalCost > sellingPrice)
printf("Loss\n");
else
printf("No Loss No Profit \n");
return 0;
}

C program to calculate electricity bill based on units


0-100 units -> 0.8 per unit;
101-200 units -> 1.0 per unit;
201-300 units -> 1.2 per unit;
Above 300 -> 1.5 per unit;

#include<stdio.h>
int main()
{
int units;
float bill;
printf("Enter units consumed : ");
scanf("%d", &units);
if(units>0 && units<=100)
bill = units*0.8;
else if(units>100 && units<=200)
bill = (100*0.8) + (units-100)*1.0;
else if(units>200 && units<=300)
bill = (100*0.8) + (100*1.0) + (units-200)*1.2;
else
bill = (100*0.8) + (100*1.0) + (100*1.2) + (units-300)*1.5;
printf("Bill to pay : %f \n" , bill);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Nested if block: Defining a block inside another block. Inner if block condition evaluates only if
the outer condition is valid. It is not recommended to write many levels to avoid complexity.

Check the number is Even or not only if the number is positive:


#include<stdio.h>
int main(){
int n;
printf("Enter number : ");
scanf("%d", &n);
if(n>0)
{
if(n%2==0)
printf("Even number\n");
else
printf("Not even number\n");
}
else
printf("Not a positive number\n");
return 0;
}

Check biggest of 2 numbers only if the numbers are equal:


#include<stdio.h>
int main()
{
int a, b;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter 2 numbers : ");
scanf("%d%d", &a, &b);
if(a!=b)
{
if(a>b)
printf("a is big\n");
else
printf("b is big\n");
}
else
printf("Both are equal numbers\n");
return 0;
}

Check the person is eligible to donate blood or not:


#include<stdio.h>
int main(){
int age, weight;
char gender;
printf("Enter gender : ");
scanf("%c", &gender);
printf("Enter age : ");
scanf("%d", &age);
printf("Enter weight : ");
scanf("%d", &weight);
if(gender=='M' || gender=='m')
{
if(age>=18 && age<=60)
{
if(weight>=50)
printf("You can donate blood \n");
else
printf("Under weight \n");
}
else
printf("Invalid age \n");
}
else
printf("Invalid Gender\n");
return 0;
}

Print student grade only if the student passed in all subjects:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Minimum pass marks must be >=35
Display the Grade only if the student passed in all subjects.
If the average >= 60 then print “A-Grade”
If the average >= 50 then print “B-Grade”
If the average >= 40 then print “C-Grade”

#include<stdio.h>
int main(){
int m1, m2, m3;
printf("Enter 3 marks : ");
scanf("%d%d%d", &m1, &m2, &m3);
if(m1>=35 && m2>=35 && m3>=35)
{
int avg = (m1+m2+m3)/3;
if(avg>=60)
printf("Grade-A\n");
else if(avg>=50)
printf("Grade-B\n");
else
printf("Grade-C\n");
}
else
printf("Student failed\n");
return 0;
}

C program to check the triangle is Equilateral or Isosceles or Scalene


Check the type of triangle only if it is valid (sum of 3 angles equals to 180)
If all angles are equal then it is called “Equilateral”
If any 2 angles are equal then it is called “Isosceles”
If 3 angles are unique then it is called “scalene”

#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter angles of triangle : ");
scanf("%d%d%d", &a, &b, &c);
if(a+b+c==180)
{
if(a==b && b==c)
printf("Equilateral triangle \n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
else if(a==b || b==c || a==c)
printf("Isosceles triangle \n");
else
printf("Scalene triangle \n");
}
else
printf("Invalid angles given \n");
return 0;
}

Read month number and display days:


If the month is invalid (not from 1 to 12) then display “Invalid month”
Month-2 has 28 or 29 days
Months-4,6,9,11 has 30 days
Remaining months has 31 days

#include<stdio.h>
int main()
{
int month;
printf("Enter month : ");
scanf("%d", &month);
if(month>=1 && month<=12)
{
if(month==2)
printf("28 days \n");
else if(month==4 || month==6 || month==9 || month==11)
printf("30 days \n");
else
printf("31 days \n");
}
else
printf("Invalid month given \n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Introduction to Loops

Loop: A Block of instructions execute repeatedly as long the condition is valid.

Note: Block executes only once whereas Loop executes until condition become False

Java Supports 3 types of Loops:


1. For Loop
2. While Loop
3. Do-While Loop

For Loop: We use for loop only when we know the number of repetitions. For example,
 Print 1 to 10 numbers
 Print Array elements
 Print Multiplication table
 Print String character by character in reverse order

While loop: We use while loop when we don’t know the number of repetitions.
 Display contents of File
 Display records of Database table

Do while Loop: Execute a block at least once and repeat based on the condition.
 ATM transaction: When we swipe the ATM card, it starts the first transaction. Once the
first transaction has been completed, it asks the customer to continue with another
transaction and quit.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
For Loop
for loop: Execute a block of instructions repeatedly as long as the condition is valid. We
use for loop only when we know the number of iterations to do.
Syntax Flow Chart
for(init ; condition ; modify)
{
statements;
}

for(start ; stop ; step)


{
statements;
}

C Program to Print 1 to 10 Numbers:


int main() {
int i;
for(i=1 ; i<=10 ; i++){
printf("%d \n", i);
}
return 0;
}

C Program to Print Numbers from 10 to 1:


int main(){
int i;
for(i=10 ; i>=1 ; i--){
printf("%d \n", i);
}
return 0;
}

C Program to Print 1 to N:
int main(){
int n, i;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
printf("%d \n", i);
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display A to Z
#include<stdio.h>
int main(){
char ch;
for(ch='A' ; ch<='Z' ; ch++){
printf("%c", ch);
}
return 0;
}

C Program to display ASCII values from A to Z


#include<stdio.h>
int main(){
char ch;
for(ch='A' ; ch<='Z' ; ch++){
printf("%c : %d \n", ch, ch);
}
return 0;
}

C Program to display ASCII character set


#include<stdio.h>
int main(){
int x;
for(x=0 ; x<256 ; x++){
printf("%d : %c \n", x, x);
}
return 0;
}

C program to display Multiplication table for given number


#include<stdio.h>
int main(){
int n, i;
printf("Enter table number : ");
scanf("%d", &n);
for(i=1 ; i<=10 ; i++)
{
printf("%d x %d = %d \n", n, i, n*i);
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display Sum of First N numbers
int main(){
int n, i, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
sum = sum+i;
}
printf("Sum of first %d numbers is : %d \n", n, sum);
return 0;
}

C Program to display Factorial of Given Number


int main(){
int n, i, fact=1;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
fact = fact*i;
}
printf("Factorial of %d is : %d \n", n, fact);
return 0;
}

C Program to display Even numbers from 1 to 10


int main(){
int i;
for(i=1 ; i<=10 ; i++){
if(i%2==0)
printf("%d is even \n", i);
}
return 0;
}

C Program to display sum of even numbers from 1 to 10


int main(){
int i, sum=0;
for(i=1 ; i<=10 ; i++){
if(i%2==0)
sum = sum+i;
}
printf("Sum is : %d \n", sum);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C program to display factors of given number
int main(){
int i, n;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
printf("%d is a factor for %d \n", i, n);
}
return 0;
}

C program to count the factors of given number


int main(){
int i, n, count=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
count++;
}
printf("Number of Factors for %d is %d \n", n, count);
return 0;
}

C program to check the input number is prime or not


Prime Number: The Number which is having 2 Factors
int main(){
int i, n, count=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
count++;
}
if(count==2)
printf("%d is Prime number \n", n);
else
printf("%d is not Prime number \n", n);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C program to find the sum of factors for input number
int main(){
int i, n, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
sum=sum+i;
}
printf("Sum of factors of %d is %d \n", n, sum);
return 0;
}

Perfect Number Program: Sum of factors except itself is equals to the same number.
int main(){
int i, n, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is Perfect number \n", n);
else
printf("%d is not a perfect number \n", n);
return 0;
}

Fibonacci series: The series in which sum of 2 consecutive numbers will be the next number
Series: 0, 1, 1, 2, 3, 5, 8, 13, 21,…
int main(){
int i, n, a=0, b=1, c;
printf("Enter limit : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
printf("%d ", a);
c = a+b ;
a=b;
b=c;
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We
use while loop only when don’t know the number of iterations to do.

Syntax Flow Chart

while(condition)
{
statements;
}

Program to display digits of number in reverse order:


int main(){
int n;
printf("Enter num : ");
scanf("%d", &n);
while(n!=0)
{
printf("%d \n", n%10);
n=n/10;
}
return 0;
}

Program to count the digits in given number:


int main(){
int n, count=0;
printf("Enter num : ");
scanf("%d", &n);
while(n!=0)
{
n=n/10;
count++;
}
printf("Digits count : %d \n", count);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to display sum of the digits in the given number:
int main(){
int n, sum=0;
printf("Enter num : ");
scanf("%d", &n);
while(n!=0){
sum = sum + n%10;
n = n/10;
}
printf("Digits sum : %d \n", sum);
return 0;
}

Program to find the sum of even digits in the given number:


int main(){
int n, r, sum=0;
printf("Enter num : ");
scanf("%d", &n);
while(n>0){
r = n%10;
if(r%2==0){
sum = sum+r;
}
n = n/10;
}
printf("Sum of even digits : %d \n", sum);
return 0;
}

Program to count number of zeros in the given number:


int main (){
int n, count=0, d;
printf("Enter a number : ");
scanf("%d", &n);
while(n>0){
d = n%10;
if(d==0)
count++;
n=n/10;
}
printf("Number of Zeros : %d \n", count);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display the first digit of given number:
int main(){
int n;
printf("Enter num : ");
scanf("%d", &n);
while(n>=10){
n = n/10;
}
printf("First Digit : %d \n", n);
return 0;
}

C Program to Find the Sum of First and Last digits of given number:
int main(){
int n, first, last;
printf("Enter num : ");
scanf("%d", &n);
first = n%10;
n=n/10;
while(n>=10){
n = n/10;
}
last = n%10;
printf("Sum of First and Last digits : %d \n", first+last);
return 0;
}

C Program to reverse the given number:


int main(){
int n, rev=0, r;
printf("Enter num : ");
scanf("%d", &n);
while(n>0){
r = n%10;
rev = rev*10 + r;
n = n/10;
}

printf("Reverse number is : %d \n", rev);


return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Palindrome Number Program in C:
The number become same when we reverse is called Palindrome number(121, 1001, 123321)
int main(){
int n, rev=0, r, temp;
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
rev = rev*10 + r;
n = n/10;
}
if(temp==rev)
printf("Palindrome Number \n");
else
printf("Not a palindrome number \n");
return 0;
}

Strong Number Program in C:


Sum of factorials of individual digits equals to the same number is called strong number.
Example: 145  1! + 4! + 5! = 145
int main(){
int n, r, fact, sum=0, temp, i;
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
fact=1;
for(i=1 ; i<=r ; i++){
fact = fact*i;
}
sum = sum + fact;
n = n/10;
}
if(temp==sum)
printf("Strong Number \n");
else
printf("Not a strong number \n");
return 0;
}
C Program to display highest digit in the number:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
int n, r, large=0;
printf("Enter num : ");
scanf("%d", &n);
while(n>0){
r = n%10;
if(r>large){
large = r;
}
n = n/10;
}
printf("Largest digit is : %d \n", large);
return 0;
}

C Program to check the 3 digits number is Armstrong number or not:


Example: 153  1^3 + 5^3 + 3^3 = 153

int main(){
int n, r, sum=0, temp;
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
sum = sum + r*r*r;
n = n/10;
}
if(temp==sum)
printf("Armstrong number \n");
else
printf("Not an Armstrong number \n");
return 0;
}

C Program to check the given number is Armstrong number or not:


2-digit number: Sum of squares of individual digits equals to the same number
3-digit number: Sum of cubes of individual digits equals to the same number
4-digit number: Sum of individual digits power 4 equals to the same number
153 = 1^3 + 5^3 + 3^3 = 153
1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1634
int main(){
int n, r, sum=0, temp, c=0, s, i;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
n=n/10;
c++;
}
n=temp;
while(n>0){
r = n%10;
s=1;
for(i=1 ; i<=c ; i++)
s = s*r;
sum = sum + s;
n = n/10;
}
if(temp==sum)
printf("Armstrong number \n");
else
printf("Not an Armstrong number \n");
}

C Program to find Sum of Digits till Single Digit:


9657 -> 9+6+5+7 -> 27 -> 2+7 -> 9
int main(){
int num, sum, dig;
printf("Enter num : ");
scanf("%d", &num);
printf("%d-> ",num);
while(num/10!=0){
sum = 0;
while(num!=0){
dig=num%10;
sum+=dig;
num/=10;
}
printf("%d->", sum);
num=sum;
}
}
ADAM Number Program in C:
ADAM Number: Take a number then square it then reverse it then find its square root then
reverse. If the given number equals to the final number, then it is called ADAM.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Number(12) -> Square(144) -> Reverse(441) -> Square root(21) -> Reverse(12)

#include<stdio.h>
#include<math.h>
int main (){
int num, temp, r1, r2, sq, rev1 = 0, rev2 = 0;

printf("Enter a number : ");


scanf("%d", &num);

temp = num * num;


printf("Square of the num : %d \n", temp);

while (temp != 0){


r1 = temp % 10;
rev1 = rev1 * 10 + r1;
temp = temp / 10;
}

printf("Reverse Num : %d \n", rev1);

sq = sqrt(rev1);
printf("Sqrt num : %d \n", sq);

while (sq != 0){


r2 = sq % 10;
rev2 = rev2 * 10 + r2;
sq = sq / 10;
}

printf("Reverse Num : %d \n", rev2);


if (rev2 == num)
printf("%d is an Adam number\n", num);
else
printf("%d is not an Adam number\n", num);

return 0;
}

Break and Continue

break: A branching statement that terminates the execution flow of a Loop or Switch case.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
int i;
for(i=1 ; i<=10 ; i++)
{
if(i==5)
break;
printf("i val : %d \n", i);
}
return 0;
}

Break statement terminates the flow of infinite loop also:


#include<stdio.h>
int main()
{
while(1)
{
printf("Infinite Loop \n");
break;
}
return 0;
}

Continue: A branching statement that terminates the current iteration of loop execution.
#include<stdio.h>
int main()
{
int i;
for(i=1 ; i<=10 ; i++)
{
if(i==5)
continue;
printf("i val : %d \n", i);
}
return 0;
}

Switch case

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Switch: It is a conditional statement that executes specific set of statements(case) based on
given choice. Default case executes if the user entered invalid choice. Case should terminate
with break statement.

Syntax FlowChart

switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......

case n : Statements ;
break
default: Statements ;
}

#include<stdio.h>
int main(){
char ch;
printf("Enter character(r, g, b) : ");
scanf("%c", &ch);
switch(ch)
{
case 'r' : printf("Red \n");
break;
case 'g' : printf("Green \n");
break;
case 'b' : printf("Blue \n");
break;
default : printf("Unknown \n");
}
return 0;
}

Program to perform arithmetic operations based on given choice:


#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
int a, b, c, ch;
printf("Arithmetic Opeations");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");

printf("Enter your choice : ");


scanf("%d",&ch);

if(ch>=1 && ch<=4)


{
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
}

switch(ch)
{
case 1: c=a+b;
printf("Add result : %d\n", c);
break;

case 2: c=a-b;
printf("Subtract result : %d\n", c);
break;

case 3: c=a*b;
printf("Multiply result : %d\n", c);
break;

case 4: c=a/b;
printf("Division result : %d\n", c);
break;

default: printf("Invalid choice\n");


}
}

Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Syntax Flow Chart

do
{
statements;
} while(condition);

Check Even numbers until user exits:


#include<stdio.h>
#include<conio.h>
int main()
{
int n;
char ch;
do{
printf("\nEnter number : ");
scanf("%d", &n);

if(n%2==0)
printf("%d is even \n", n);
else
printf("%d is odd \n", n);

printf("Do you want to check another num(y/n) : ");


ch = getch();

}while(ch!='n');
return 0;
}

getch():
 getch() is a pre-defined method belongs to conio.h header file.
 It is used to read character from the console while program is running.

goto: A branching statement used to send the control from one place to another place in the
program by defining labels.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to display 1 to 10 numbers without loop:
#include<stdio.h>
int main(){
int a=1;
top:
printf("a value : %d \n", a);
++a;
if(a<=10)
goto top;
return 0;
}

We can create multiple labels in a single program.


#include<stdio.h>
int main(){
top:
printf("Top \t");
goto bottom;
center:
printf("Center \t");
bottom:
printf("Bottom \n");
goto top;
return 0;
}

We use goto statement to come out of infinite loop also.


#include<stdio.h>
int main(){
while(1){
printf("Infinite loop \n");
goto end;
}
end:
printf("Can break with goto\n");
return 0;
}

Menu Driven Programs


Menu Driven programs are used to perform set of operations continuously until user exits.
Examples: Arithmetic operations, Stack , Queue, Linked List operations etc.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to perform Arithmetic operations using (while and if) :
int main(){
int a, b, ch;
while(1){
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");

printf("Enter your choice : ");


scanf("%d",&ch);

if(ch==1){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Add result : %d\n", a+b);
}
else if(ch==2){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Subtract result : %d\n", a-b);
}
else if(ch==3){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Multiply result : %d\n", a*b);
}
else if(ch==4){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Division result : %d\n", a/b);
}
else if(ch==5){
printf("End \n");
exit(1);
}
else
printf("Invalid choice \n");
}
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to perform Arithmetic operations using (while and switch):
int main()
{
int a, b, c, ch;
while(1){
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&ch);
if(ch>=1 && ch<=4){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
}
switch(ch){
case 1: c=a+b;
printf("Add result : %d\n", c);
break;
case 2: c=a-b;
printf("Subtract result : %d\n", c);
break;
case 3: c=a*b;
printf("Multiply result : %d\n", c);
break;
case 4: c=a/b;
printf("Division result : %d\n", c);
break;
case 5: printf("End\n");
exit(1);
default: printf("Invalid choice\n");
}
}
}

Program to perform Arithmetic operations using (do-while and switch):


int main()
{
int a, b, c, ch;
do

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");

printf("Enter your choice : ");


scanf("%d",&ch);

if(ch>=1 && ch<=4){


printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
}
switch(ch){
case 1: c=a+b;
printf("Add result : %d\n", c);
break;
case 2: c=a-b;
printf("Subtract result : %d\n", c);
break;
case 3: c=a*b;
printf("Multiply result : %d\n", c);
break;
case 4: c=a/b;
printf("Division result : %d\n", c);
break;
}
}while(ch!=5);
}

Nested While loop: Defining a while loop inside another while loop. Loop execution terminates
only when outer loop condition fails.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
int x=1;
while(x<=5)
{
printf("x : %d -> ", x);
int y=1;
while(y <= 5)
{
printf("y : %d \t ", y);
++y;
}
printf("\n");
++x;
}
return 0;
}
Output:
x : 1 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 2 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 3 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 4 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 5 -> y : 1 y : 2 y : 3 y : 4 y : 5

Nested for loop:


 Defining for loop inside another for loop.
 Nested loops are mainly used to process two-dimensional data (Rows & Columns)

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 Outer loop represents number of rows
 Inner loop represents number of columns.

Following program prints the combinations of outer loop and inner loop variable values:
#include<stdio.h>
int main()
{
int i, j;
for(i=1 ; i<=5 ; i++)
{
for(j=1 ; j<=5 ; j++)
{
printf("(%d,%d)\t", i, j);
}
printf("\n");
}
return 0;
}

Output:
(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)
(4,1) (4,2) (4,3) (4,4) (4,5)
(5,1) (5,2) (5,3) (5,4) (5,5)

Range based programs


C Program to print Even number in given Range:
int main (){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int limit, n;
printf("*****Even Numbers in the Given Range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
if(n%2==0)
printf("%d \t", n);
}
return 0;
}

C Program to Print Square and Cube values in the given Range:


int main (){
int limit, n;
printf("*****Square and Cube values in the given Range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
printf("%d -> Square=%d -> Cube=%d \n", n, n*n, n*n*n);
}
return 0;
}

Print Multiplication tables in the given range:


int main (){
int limit, n, i;
printf("*****Multiplication table in given Range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
printf("Table-%d : \n", n);
for(i=1 ; i<=10 ; i++){
printf("%d x %d = %d \n", n, i, n*i);
}
}
return 0;
}

C Program to Print Factorials in Given Range:


int main (){
int limit, n, i;
printf("*****Factorial values in given Range*****\n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int fact=1;
for(i=1 ; i<=n ; i++){
fact = fact*i;
}
printf("Factorial of %d is : %d \n", n, fact);
}
return 0;
}

C Program to print Factors of each number in the given range:


int main (){
int limit, n, i;
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
printf("Factors of %d is : ", n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
printf("%d ", i);
}
printf("\n");
}
return 0;
}

C Program to Print Prime Numbers in the Given range:


int main (){
int limit, n, i;
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int count=0;
for(i=1 ; i<=n ; i++){
if(n%i==0){
count++;
}
}
if(count==2)
printf("%d is prime \n", n);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
return 0;
}
C Program to print Perfect numbers in the given range:
int main (){
int limit, n, i;
printf("*****Perfect Numbers in the Given range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int sum=0;
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is perfect \n", n);
}
return 0;
}
C Program to print Perfect numbers in the given range:
int main (){
int limit, n, i;
printf("*****Perfect Numbers in the Given range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int sum=0;
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is perfect \n", n);
}
return 0;
}

C Program to reverse the numbers in given range:


int main (){
int limit, n, d, x;
printf("*****Reverse the numbers in the Given range*****\n");
printf("Enter Limit : ");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int rev=0;
x=n;
while(x>0){
d = x%10;
rev = rev*10 + d;
x = x/10;
}
printf("%d -> %d \n", n, rev);
}
return 0;
}

C Program to display Palindrome numbers in the given range:


int main (){
int low, high, n, d, x;
printf("*****Palindrome numbers in the Given range*****\n");
printf("Enter Lower Limit : ");
scanf("%d", &low);
printf("Enter Upper Limit : ");
scanf("%d", &high);
for(n=low ; n<=high ; n++)
{
int rev=0;
x=n;
while(x>0)
{
d = x%10;
rev = rev*10 + d;
x = x/10;
}
if(n==rev)
printf("%d \t", n);
}
return 0;
}
C Program to Print Strong Numbers in the given range:
#include<stdio.h>
int main ()
{
int low, high, n, d, x, i;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("*****Strong numbers in the Given range*****\n");

printf("Enter Lower Limit : ");


scanf("%d", &low);

printf("Enter Upper Limit : ");


scanf("%d", &high);

for(n=low ; n<=high ; n++)


{
int sum=0;
x=n;
while(x>0)
{
int fact=1;
d = x%10;
for(i=1 ; i<=d ; i++)
{
fact = fact*i;
}
sum = sum + fact;
x = x/10;
}
if(n==sum)
printf("%d \t", n);
}
return 0;
}

Pattern Programs in C
Basic Patterns:
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){
22222
for (j=1 ; j<=5 ; j++){ 33333

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%d", i); 44444
} 55555
printf("\n");
}
return 0;
}
int main (){
int i, j;
12345
for (i=1 ; i<=5 ; i++){
12345
for (j=1 ; j<=5 ; j++){ 12345
printf("%d", j); 12345
} 12345
printf("\n");
}
return 0;
}
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){
00000
for (j=1 ; j<=5 ; j++){ 11111
printf("%d", i%2); 00000
} 11111
printf("\n");
}
return 0;
}
int main (){
int i, j;
10101
for (i=1 ; i<=5 ; i++){
10101
for (j=1 ; j<=5 ; j++){ 10101
printf("%d", j%2); 10101
} 10101
printf("\n");
}
return 0;
}
int main (){
int i, j;
55555
for (i=5 ; i>=1 ; i--){
44444
for (j=5 ; j>=1 ; j--){ 33333
printf("%d", i); 22222
} 11111

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j;
54321
for (i=5 ; i>=1 ; i--){
54321
for (j=5 ; j>=1 ; j--){ 54321
printf("%d", j); 54321
} 54321
printf("\n");
}
return 0;
}
int main (){
char x, y;
AAAAA
for (x='A' ; x<='E' ; x++){
BBBBB
for (y='A' ; y<='E' ; y++){ CCCCC
printf("%c", x); DDDDD
} EEEEE
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
ABCDE
char x, y;
ABCDE
for (x='A' ; x<='E' ; x++){ ABCDE
for (y='A' ; y<='E' ; y++){ ABCDE
printf("%c", y); ABCDE
}
printf("\n");
}
return 0;
}

#include<stdio.h>
int main (){
*****
int i, j;
*****
for (i=1 ; i<=5 ; i++){ *****
for (j=1 ; j<=5 ; j++){ *****

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("*"); *****
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){
for (j=1 ; j<=5 ; j++){ *****
#####
if(i%2==0)
*****
printf("*"); #####
else *****
printf("#");
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){ #*#*#
for (j=1 ; j<=5 ; j++){ #*#*#
#*#*#
if(j%2==0)
#*#*#
printf("*"); #*#*#
else
printf("#");
}
printf("\n");
}
return 0;
}

Half Triangle Patterns:


int main (){
int i, j;
1
for (i=1 ; i<=5 ; i++){
22
for (j=1 ; j<=i ; j++){ 333
printf("%d", i); 4444

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
} 55555
printf("\n");
}
return 0;
}
int main (){
int i, j;
55555
for (i=5 ; i>=1 ; i--){
4444
for (j=i ; j>=1 ; j--){ 333
printf("%d", i); 22
} 1
printf("\n");
}
return 0;
}
int main (){
int i, j;
1
for (i=1 ; i<=5 ; i++){
12
for (j=1 ; j<=i ; j++){ 123
printf("%d", j); 1234
} 12345
printf("\n");
}
return 0;
}
int main (){
int i, j;
1
for (i=1 ; i<=5 ; i++){
21
for (j=i ; j>=1 ; j--){ 321
printf("%d", j); 4321
} 54321
printf("\n");
}
return 0;
}

int main (){


int i, j;
12345
for (i=5 ; i>=1 ; i--){
1234
for (j=1 ; j<=i ; j++){ 123
printf("%d", j); 12
} 1

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j;
12345
for (i=1 ; i<=5 ; i++){
2345
for (j=i; j<=5 ; j++){ 345
printf("%d", j); 45
} 5
printf("\n");
}
return 0;
}
int main (){
int i, j;
5
for (i=5 ; i>=1 ; i--){
54
for (j=5; j>=i ; j--){ 543
printf("%d", j); 5432
} 54321
printf("\n");
}
return 0;
}
int main (){
int i, j;
5
for (i=5 ; i>=1 ; i--){
45
for (j=i; j<=5 ; j++){ 345
printf("%d", j); 2345
} 12345
printf("\n");
}
return 0;
}

#include<stdio.h>
int main ()
1
{
23
int i, j, k=1; 456
for (i=1 ; i<=5 ; i++){ 7891
for (j=1; j<=i ; j++){ 23456

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%d", k++);
if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main ()
12345
{
6789
int i, j, k=1; 123
for (int i=5 ; i>=1 ; i--){ 45
for (j=1; j<=i ; j++){ 6
printf("%d", k++);
if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
int main ()
{
A
char i, j;
AB
for (i='A' ; i<='E' ; i++) ABC
{ ABCD
for (j='A' ; j<=i ; j++) ABCDE
{
printf("%d", j);
}
printf("\n");
}
return 0;
}

int main (){


char i, j;
EDCBA
for (i='E' ; i>='A' ; i--){
DCBA
for (j=i ; j>='A' ; j--){ CBA
printf("%d", j); BA
} A

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j, k=1;
1
for (int i=1 ; i<=5 ; i++){
01
for (j=1; j<=i ; j++){ 010
printf("%d", k++%2); 1010
} 10101
printf("\n");
}
return 0;
}
int main (){
int i, j, k=1;
10101
for (int i=5 ; i>=1 ; i--){
0101
for (j=1; j<=i ; j++){ 010
printf("%d", k++%2); 10
} 1
printf("\n");
}
return 0;
}
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){
1
for (j=1; j<=i ; j++){ 00
printf("%d", i%2); 111
} 0000
printf("\n"); 11111
}
return 0;
}

int main (){


int i, j, k;
for (i=1 ; i<=5 ; i++){
for (j=i ; j<5 ; j++){
printf(" "); *
} **
***

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for (k=1 ; k<=i ; k++){ ****
printf("*"); *****
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
*****
for (j=1 ; j<i ; j++){ ****
printf(" "); ***
} **
for (k=i ; k<=5 ; k++){ *
printf("*");
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
for (j=i ; j<5 ; j++){ 1
printf(" "); 12
123
}
1234
for (k=1 ; k<=i ; k++){ 12345
printf("%d", k);
}
printf("\n");
}
return 0;
}

int main (){


int i, j, k;
for (i=1 ; i<=5 ; i++){
1
for (j=i ; j<5 ; j++){ 21
printf(" "); 321
} 4321

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for (k=i ; k>=1 ; k--){ 54321
printf("%d", k);
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=5 ; i>=1 ; i--){
12345
for (j=i ; j<5 ; j++){ 1234
printf(" "); 123
} 12
for (k=1 ; k<=i ; k++){ 1
printf("%d", k);
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
12345
for (j=1 ; j<i ; j++){ 2345
printf(" "); 345
} 45
for (k=i ; k<=5 ; k++){ 5
printf("%d", k);
}
printf("\n");
}
return 0;
}

Functions in C
Variable: Stores data.
Function: Performs operation on data.

Function takes input, performs operations and returns output


Syntax Example

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int identity(arguments) int add(int a, int b)
{ {
-> statements; int res = a+b ;
} return res ;
}

C functions classified into:


1. Built In Functions
2. User Defined Functions

Built in Functions:
 C library is a set of header files
 Header file is a collection of pre-defined functions.
stdio.h conio.h string.h graphics.h
printf() getch() strlen() line()
scanf() clrscr() strrev() circle()
feof() cetche() strcat() bar()
… …. ….. …

Custom Functions: Programmed defined functions based on application requirement


Calculator.c Mobile.c Account.c
add() call() deposit()
subtract() message() withdraw()
multiply() store() ….
divide() …..

Every function consists


1. Prototype:
a. Prototype is called function declaration. Every Custom function must be specified
before main().
2. Definition:
a. Definition is a block of instructions contains function logic. Function executes
when we call that function.
3. Function call:
a. It is a statement and it is used to execute the function logic.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
No arguments and No return values function:
#include<stdio.h>
void sayHi(void);
int main(void)
{
sayHi();
return 0 ;
}
void sayHi(void){
printf("Hi to all \n");
}

With arguments and No return values function: (Even Number Program)


#include<stdio.h>
void isEven(int);
int main(void)
{
int n;
printf("Enter number : ");
scanf("%d", &n);
isEven(n);
return 0 ;
}
void isEven(int num){
if(num%2==0)
printf("%d is Even \n", num);
else
printf("%d is not Even \n", num);
}

With arguments and No return values (Print ASCII value of given character):

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void ascii_value(char);
int main(void){
char sym ;
printf("Enter symbol : ");
scanf("%c", &sym);
asciiValue(sym);
return 0;
}
void asciiValue(char sym)
{
printf("ASCII value is : %d \n", sym);
}

With arguments and With return values function: (addition of 2 numbers)


#include <stdio.h>
int add(int, int);
int main(){
int a, b, res;
printf("Enter two numbers : \n");
scanf("%d%d", &a, &b);
res = add(a,b);
printf("%d + %d = %d\n", a, b, res);
return 0;
}
int add(int x, int y){
int z=x+y ;
return z;
}

No arguments and With return values function:


float getPI(void);
void main(void){
float pi;
fpi = getPI();
printf("PI value is : %f\n", pi);
}
float getPI(void){
return 3.142;
}

Arithmetic Operations Menu Driven program – Using functions

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include <stdio.h>
float add(float,float);
float subtract(float,float);
float multiply(float,float);
float divide(float,float);
int main(){
int choice;
float a,b,c;
while(1){
printf("1.Add\n");
printf("2.Subtract\n");
printf("3.Multiply\n");
printf("4.divide\n");
printf("5.Exit\n");
printf("Enter your choice : ");
scanf("%d" , &choice);

if(choice>=1 && choice<=4){


printf("Enter 2 numbers :\n");
scanf("%f%f", &a, &b);
}

switch(choice){
case 1 : c = add(a,b);
printf("Result : %f\n\n",c);
break ;
case 2 : c = subtract(a,b);
printf("Result : %f\n\n",c);
break ;
case 3 : c = multiply(a,b);
printf("Result : %f\n\n",c);
break ;
case 4 : c = divide(a,b);
printf("Result : %f\n\n",c);
break ;
case 5 : exit(1);
default : printf("Invalid choice \n\n");
}
}
return 0;
}
float add(float x, float y){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
return x+y ;
}
float subtract(float x, float y){
return x-y ;
}
float multiply(float x, float y){
return x*y ;
}
float divide(float x, float y){
return x/y ;
}

Recursion:
Function calling itself
or
Calling a function from the definition of same function.

#include<stdio.h>
void recur(void);
void main(){
recur();
}
void recur(){
printf("Starts \n");
recur();
printf("Ends \n");
}

Program to print 1 to 10 numbers using recursion:


#include<stdio.h>
void print(int);
int main(void){
print(1);
return 0 ;
}
void print(int n){
printf("%d \n", n);
if(n<10)
print(n+1);
}

Program to find the factorial of given number using recursion:


#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int fact(int); int fact(int n)
void main(void) {
{ if(n==0)
int n, factorial; return 1;
printf("Enter one number : "); else
scanf("%d",&n); return n*fact(n-1);
factorial = fact(n); }
printf("result : %d\n",factorial);
}

Program to find sum of first N numbers using Recursion:


#include<stdio.h>
int sum(int); int sum(int n)
void main(void) {
{ if(n==0)
int n, s; return n;
printf("Enter n value : "); else
scanf("%d", &n); return n+sum(n-1);
s = sum(n); }
printf("Sum of %d nums : %d\n", n, s);
}

Arrays in C
Primitive type:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 Variables are used to store data.
 Primitive variable can store only one value at a time.
 For example,
int main(){
int a=5;
a=10;
a=20;
printf("a val : %d \n", a); // prints - 20
return 0;
}

Array:
 Array is used to store more than one value but of same type.
 For example, storing 100 students’ average marks.

Array creation:
 In array variable declaration, we need to specify the size
 Array variable stores base address of memory block.
 Array elements store in consecutive memory location.

Process Array elements:


 Array memory locations must be accessed through their index.
 Index values starts from 0 to Size-1

How to access array elements?


 Array consists multiple values.
 We can simply use loops to process array locations.
Reading Printing
int i; int i;
for(i=0 ; i<5 ; i++) for(i=0 ; i<5 ; i++)
{ {
scanf("%d", &marks[i]); printf("%d", marks[i]);
} }
Array as Local variable:
 Declare array variable inside the function.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 If the array variable is local, all locations initialize with garbage values.
int main()
{
int arr[5], i;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

Array as Global variable:


 Declare array variable outside to all functions.
 Global array variable locations initialize with default values.
int arr[5];
int main()
{
int i;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

Length of array:
 sizeof() function returns the total size of array.
 We can find the length of array by dividing total size with single element size.
int main()
{
float arr[5];
printf("Total size of array : %d \n", sizeof(arr));
printf("Array element size : %d \n", sizeof(arr[0]));
printf("Length of Array : %d \n", sizeof(arr)/sizeof(arr[0]));
return 0;
}

Note: Address of the first element is called the base address.


The address of the ith element is given by the following formula,
Addressi = base_address + i*size_of_element
Array Initialization:
 We can assign values directly in the declaration of array is called Initialization.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 If we assign the elements less than the length of array, other locations get default values.
int main(){
int arr[5] = {10, 20, 30};
int i;
printf("Array default values are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

C Program to display First and Last element of Array:


int main ()
{
int arr[] = {10, 20, 30, 40, 50};
printf("First element : %d \n", arr[0]);
printf("Last element : %d \n", arr[4]);
return 0;
}

C Program to display last element using length:


int main (){
int arr[] = {10, 20, 30, 40, 50};
int len = sizeof(arr)/sizeof(int);
printf("Length : %d \n", len);
printf("Last element : %d \n", arr[len-1]);
return 0;
}

C Program to Check First and Last elements Sum equals to 10 or not in Array:
int main (){
int arr[] = {4, 3, 9, 2, 6};
int first = arr[0];
int last = arr[4];
if(first+last==10)
printf("Equals to 10 \n");
else
printf("Not equals to 10 \n");
return 0;
}

C program to check the First element of Array is Even or Not:


int main ()

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
int arr[] = {4, 3, 9, 2, 6};
if(arr[0]%2==0)
printf("First element is Even \n");
else
printf("First element is not Even \n");
return 0;
}

C Program to replace the First and Last elements of array with 10:
int main ()
{
int arr[] = {4, 3, 9, 2, 6}, i;
arr[0] = 10;
arr[4] = 10;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

C Program to Increase First and Decrease Last elements of Array:


int main ()
{
int arr[] = {4, 3, 9, 2, 6};
int i;
arr[0]++;
arr[4]--;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

C program to swap first and last elements of array:


int main ()
{
int arr[] = {4, 3, 9, 2, 6};
int i, temp;
temp = arr[0];
arr[0] = arr[4];

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
arr[4] = temp;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

Program to reverse the array elements:

C program to read elements into array and display:


int main ()
{
int arr[5], i;
printf("Enter 5 elements : \n");
for(i=0 ; i<5 ; i++){
scanf("%d", &arr[i]);
}
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

C program to display array elements in reverse order:


int main (){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[5] = {10, 20, 30, 40, 50}, i;
printf("Reverse Array : \n");
for(i=4 ; i>=0 ; i--){
printf("%d \n", arr[i]);
}
return 0;
}

C Program to find sum of array elements:


int main (){
int arr[5] = {10, 20, 30, 40, 50}, i, sum=0;
for(i=0 ; i<5 ; i++){
sum = sum + arr[i];
}
printf("Sum of Array elements : %d \n", sum);
return 0;
}

C Program to find average of array elements:


int main (){
int arr[5] = {10, 20, 30, 40, 50}, i, sum=0, avg;
for(i=0 ; i<5 ; i++){
sum = sum + arr[i];
}
printf("Sum of Array elements : %d \n", sum);
avg = sum/5;
printf("Average of array elements : %d \n", avg);
return 0;
}

C Program to display only even numbers in the array:


int main (){
int arr[8] = {8, 5, 1, 7, 4, 3, 2, 9}, i;
printf("Even numbers of Array : \n");
for(i=0 ; i<8 ; i++){
if(arr[i]%2==0)
printf("%d \t", arr[i]);
}
return 0;
}

C program to display the largest element in the array:


int main(){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[8] = {7,2,9,14,3,27,5,4};
int large=arr[0], i;
for(i=1 ; i<8 ; i++){
if(arr[i]>large)
large = arr[i];
}
printf("Largest element is : %d \n", large);
return 0;
}

Pass Array as a parameter to a function:


 We can pass array as input parameter to function.
 By passing array name, the address will be passed as parameter.
 We collect the address in Called Function by declaring same type array.

void display(int[]);
int main(){
int a[5] = {10, 20, 30, 40, 50};
display(a);
return 0;
}
void display(int x[]){
int i;
printf("Array is :\n");
for(i=0 ; i<5 ; i++){
printf("%d\n", x[i]);
}
}

C program to insert element into array:

#include<stdio.h>
int main(){
int arr[20], n, i, ele, loc ;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter size : ");
scanf("%d", &n);
printf("Enter elements : \n");
for(i=0 ; i<n ; i++){
scanf("%d", &arr[i]);
}
printf("Enter element to insert : ");
scanf("%d", &ele);
printf("Enter location to insert : ");
scanf("%d", &loc);
for(i=n-1 ; i>=loc ; i--){
arr[i+1] = arr[i];
}
arr[loc] = ele;
printf("Array elements now : \n");
for(i=0 ; i<=n ; i++){
printf("%d \n", arr[i]);
}
return 0;
}

Write a program to reverse all elements in the array:

#include<stdio.h>
void reverse(int[], int);
int main(){
int a[5] = {10,20,30,40,50}, i;
printf("Before reverse : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", a[i]);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
reverse(a,5);
return 0;
}
void reverse(int a[], int n){
int i,j,temp;
i=0;
j=n-1;
while(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
printf("After reverse : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", a[i]);
}
}

Program to display Array elements with their consecutive locations:


#include<stdio.h>
int main(){
int arr[50], n, i;
printf("Enter size :");
scanf("%d" , &n);
printf("Enter %d elements : \n",n);
for(i=0 ; i<n ; i++){
printf("Enter Ele-%d : ", i+1);
scanf("%d" , &arr[i]);
}

printf("Elements are :\n");


for(i=0 ; i<n ; i++){
printf("arr[%d] : %d \t addr : %u\n", i, arr[i], &arr[i]);
}
return 0;
}

C Program to insert an array into another array at specified location:


int main(){
int a[30], b[10], m, n, i, loc;
printf("Enter size of A : ");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
scanf("%d", &m);
printf("Enter %d elements into A : \n", m);
for(i=0 ; i<m ; i++)
scanf("%d", &a[i]);

printf("Enter size of B : ");


scanf("%d", &n);
printf("Enter %d elements into B : \n", n);
for(i=0 ; i<n ; i++)
scanf("%d", &b[i]);

printf("Enter location in A to insert B : \n");


scanf("%d", &loc);

for(i=m-1 ; i>=loc ; i--)


a[i+n] = a[i];

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


a[loc+i] = b[i];

printf("Array A elements after insertion : \n");


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

Linear Search:
 Linear Search is used to search for an element in the array.
 Linear Search can be applied on Sorted array / Unsorted array.
 In linear search, index element starts with key element. If element found return index else
display Error message.

int main(){
int a[30], m, key, i, n, found=0;
printf("Enter size of array : ");
scanf("%d",&m);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter Elements in array : \n");
for(i=0; i<m; i++){
scanf("%d",&a[i]);
}

printf("Enter the key to be searched: \n");


scanf("%d",&key);

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


if(key==a[i]){
found=1;
printf("Found @ location : %d \n", i);
break;
}
}
if(!found)
printf("Element not found \n");
return 0;
}

C Program to Merge two arrays:

int main(){
int a[30], b[10], m, n, i;

printf("Enter size of A : ");


scanf("%d", &m);
printf("Enter %d elements into A : \n", m);
for(i=0 ; i<m ; i++)
scanf("%d", &a[i]);

printf("Enter size of B : ");


scanf("%d", &n);
printf("Enter %d elements into B : \n", n);
for(i=0 ; i<n ; i++)
scanf("%d", &b[i]);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0 ; i<n ; i++)
a[m+i] = b[i];

printf("After Merge Array A is : \n");


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

Binary Search:
 Binary search can be applied to only sorted array.
 In binary search, we find the mid location and compare with searching element.
 If the searching element less than mid location element, search goes to left side.
 If the searching element greater than mid location, search goes to right side.

int main(){
int a[10],m,i,n,k,low,high;
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter %d elements \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
printf("Enter the key value : ");
scanf("%d",&k);
while(low<=high){
m=(low+high)/2;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
if(k<a[m])
high=m-1;
else if(k>a[m]){
low=m+1;
else if(k==a[m]){
printf("Element found @ loc : %d\n",m);
break;
}
}
return 0;
}

Bubble Sort:
 Simple sorting technique to arrange elements either in Ascending order or Descending
order.
 In Bubble sort, the index element compares with the next element and swapping them if
required.
 For each pass(inner loop completion) highest element bubbled to last location.
 This process continuous until the complete array get sorted.

#include<stdio.h>
int main(){
int arr[7] = {7, 3, 9, 4, 2, 5, 1}, i, j, n=7, t;
for(i=0 ; i<n-1 ; i++){
for(j=0 ; j<n-1-i ; j++){
if(arr[j]>arr[j+1]){
t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}
}
}
printf("Sorted array : ");
for(i=0 ; i<n ; i++){
printf("%d ", arr[i]);
}
return 0;
}

Two dimensional arrays:


 Two-dimensional array stores data of format (Rows & Columns).
 Nested loops are used to access locations.

Print default values of 2-dimensional array:


int main() {
int arr[3][3], i, j;
printf("Array elements are : \n");
for(i=0 ; i<3 ; i++){
for(j=0 ; j<3 ; j++){
printf("%d \t", arr[i][j]);
}
printf("\n");
}
return 0;
}

Two-dimensional array initialization:


int main(){
int arr[3][3] = {10,20,30,40,50,60,70, 80,90}, i, j;
printf("Array elements are : \n");
for(i=0 ; i<3 ; i++){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(j=0 ; j<3 ; j++){
printf("%d \t", arr[i][j]);
}
printf("\n");
}
}

We can also assign values row wise as follows:


int main(){
int arr[3][3] = {{10}, {20,30}, {0,40}}, i, j;
printf("Array elements are : \n");
for(i=0 ; i<3 ; i++){
for(j=0 ; j<3 ; j++){
printf("%d \t", arr[i][j]);
}
printf("\n");
}
}

Write a program to find the size of two-dimensional array:


#include<stdio.h>
int main(){
int a[3][3];
printf("Total size : %d \n", sizeof(a));
printf("Element size : %d \n", sizeof(a[0][0]));
printf("Length : %d \n", sizeof(a)/sizeof(a[0][0]));
printf("Row size : %d \n", sizeof(a[0]));
printf("Row length : %d \n", sizeof(a[0])/sizeof(a[0][0]));
return 0;
}

Read and Display elements of 2-Dimensional array:


#include<stdio.h>
int arr[2][2];
int main(){
int i, j;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter array elements : \n");
for(i=0 ; i<2 ; i++){
for(j=0 ; j<2 ; j++){
scanf("%d", &arr[i][j]);
}
printf("\n");
}

printf("Array elements are : \n");


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

Program to perform Matrix addition in C:

#include<stdio.h>
int main(){
int a[2][2], b[2][2], c[2][2], i, j;

printf("Enter elements of A : \n");


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

printf("Enter elements of B : \n");


for(i=0 ; i<2 ; i++)
for(j=0 ; j<2 ; j++)
scanf("%d", &b[i][j]);
for(i=0 ; i<2 ; i++)

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(j=0 ; j<2 ; j++)
c[i][j] = a[i][j] + b[i][j];

printf("Added matrix is : \n");


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

Transpose of a Matrix program in C:

#include<stdio.h>
int main(){
int arr[3][3]={{10,20,30},{40,50,60},{70,80,90}} ,I ,j ,temp;
printf("Matrix is: \n");
for(i=0 ; i<3 ; i++){
for(j=0 ; j<3 ; j++){
printf("%d\t", arr[i][j]);
}
printf("\n");
}

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


for(j=0 ; j<3 ; j++){
if(i<j){
temp=arr[i][j];
arr[i][j]=arr[j][i];
arr[j][i]=temp;
}
}
printf("\n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}

printf("Transpose of matrix: \n");


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

Program to perform Matrix Multiplication in C:

#include<stdio.h>
int main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
printf("Enter array A \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("Enter array B \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}

printf("Multiplication array \n");


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

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
String Handling in C
String:
 String is a one-dimensional character array.
 String is a collection symbols (alphabets, digits and special symbols).
 Strings must be represented with double quotes.

Syntax: Example:
char identity[size]; char name[20];

Memory representation:
 We can store only 'n-1' characters into an array of size 'n'.
 Last character of every string is '\0'
 ASCII value of '\0' character is 0.

String Format Specifier(%s):


 We use %s to read and display strings.
 To process character by character, we use %c specifier.

Program to display String:


#include<stdio.h>
int main()
{
char str[20] = "Hello" ;
printf("%s all \n" , str);
return 0;
}

We can display complete character array in single statement using %s:


#include<stdio.h>
int main()
{
char str[4] = {'a','b','c'};
printf("String is : %s\n" , str);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
In C, duplicate strings get different memory locations:

== operator only compares the addresses of strings, hence following program outputs
“Strings are not equal”
int main(){
char s1[10] = "abc";
char s2[10] = "abc";
if(s1==s2)
printf("Strings are equal \n");
else
printf("Strings are not equal \n");
return 0;
}

String will be terminated when it reaches '\0' character:


int main(){
printf("Hello \0 World \n");
return 0;
}

Analyze the output of following code:


int main(){
printf("Hello World \0 \n");
printf("Hello \0 World \n");
printf("\0Hello World \n");
return 0;
}

Note: Strings can be processed with \0 character only. ASCII value as follows.
#include<stdio.h>
int main(){
printf("\0 ascii value is : %d \n", '\0');
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Note: In the above program, printf() function stops printing string when \0 reached.

Program to print null character(\0) on console:


int main(){
printf("\\0 ascii value is : %d \n", '\0');
return 0;
}

Program to display Strings with quotations:


Expected Output: It is 'C-lang' class
int main(){
printf("This is 'C-lang' class \n");
return 0;
}

Expected Output: It's a C class


int main(){
printf("It's a C class \n");
return 0;
}

Expected Output: I am attending "C - Online" class


int main(){
printf("I am attending \"C - Online\" class \n");
return 0;
}

Expected Output: She said, "It's a good one"


int main(){
printf("She said, \"It's a good one\" \n");
return 0;
}

Program to read and display string:


int main(){
char name[20];
printf("Enter your name : ");
scanf("%s", name);

printf("Hello %s, Welcome to Strings \n", name);


return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
How %s read input into String variable:
 “%s” takes the base address of memory block.
 It reads character by character and stores from the base address.
 Once input is over, it will add null character at the end of the string.

Program to read multi-word string in C:


 gets() function can read a string with multiple spaces.
 It stops reading characters into array only when we hit "enter" key.

int main(){
char name[20];
printf("Enter multi word name : ");
gets(name);
printf("Hello %s \n", name);
}

Passing String as an argument to the function:


 Like primitive types, we can pass String value as a parameter to the function
 We collect these values into character type argument variables only.
#include<stdio.h>
void display(char[], int);
int main() {
char name[20];
int age;
printf("Enter your name : ");
gets(name);
printf("Enter your age : ");
scanf("%d", &age);
display(name, age);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
void display(char name[], int age){
printf("Name is : %s \n", name);
printf("Age is : %d \n", age);
}

Program to display the String character by character:


int main(){
char name[20];
int i;
printf("Enter your name : ");
gets(name);
i=0;
while(name[i] != '\0'){
printf("%c \n", name[i]);
i++;
}
return 0;
}

string.h functions

strlen() :
 strlen() returns length of string excluding null character.
 Return type is size_t (positive integer)
Prototype is size_t strlen(char s[]);

#include<string.h>
int main(){
char str[20];
size_t len;
printf("Enter string : ");
gets(str);
len = strlen(str);
printf("Length is : %u \n", len);
return 0;
}

Program to find the length of String without using library function:


int main(){
char str[20];
size_t len=0, i=0;
printf("Enter string : ");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
gets(str);
while(str[i] != '\0'){
len++;
i++;
}
printf("Length is : %u \n", len);
return 0;
}

Program to convert Upper case characters into Lower case in String:


#include<string.h>
int main(){
char src[20];
printf("Enter Upper string : ");
gets(src);
strlwr(src);
printf("Lower string : %s \n", src);
return 0;
}

Program to convert Upper case characters into Lower case without Library function:
#include<stdio.h>
#include<string.h>
int main(){
char src[20];
int i=0;
printf("Enter Upper string : ");
gets(src);

while(src[i] != '\0')

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
if(src[i]>='A' && src[i]<='Z')
{
src[i] = src[i]+32;
}
i++;
}
printf("Lower string : %s \n", src);
}

Program to reverse the given string in C:


#include<string.h>
int main()
{
char src[20];
printf("Enter string : ");
gets(src);
strrev(src);
printf("Reverse string : %s \n", src);
}

Program to reverse the String without using Library function:


#include<string.h>
int main()
{
char src[20], temp;
int i, j;

printf("Enter string : ");


gets(src);

i=0;
j=strlen(src)-1;
while(i<j)
{
temp = src[i];
src[i] = src[j];
src[j] = temp;
i++;
j--;
}
printf("Reverse string : %s \n", src);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
strcmp(): Compare strings are return 0 if equal else return the ASCII difference between
mismatching characters.
#include<string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "Hello";

if(strcmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}

Compare Strings without considering the Case using stricmp() function:


#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "HELLO";
char s2[20] = "Hello";

if(stricmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}

C program to compare two strings without using string functions:


strcmp() function compares two string character by character until there is a mismatch
occurs or end of the one of those strings reached whichever occurs first.

#include<stdio.h>
int stringCompare(char[],char[]);
int main()
{
char str1[100], str2[100];
int compare;

printf("Enter first string: ");


gets(str1);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter second string: ");
gets(str2);

compare = stringCompare(str1,str2);
if(compare == 1)
printf("Both strings are equal.\n");
else
printf("Both strings are not equal\n");
return 0;
}
int stringCompare(char str1[],char str2[])
{
int i=0,flag=0;
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i]){
flag=1;
break;
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
return 1;
else
return str1[i]-str2[i];
}

Other String Functions:


void *memchr(const void *str, int c, size_t n)
Searches for the first occurrence of the character c (an unsigned char) in the first n bytes
of the string pointed to, by the argument str.

int memcmp(const void *str1, const void *str2, size_t n)


Compares the first n bytes of str1 and str2.

void *memcpy(void *dest, const void *src, size_t n)


Copies n characters from src to dest.

void *memmove(void *dest, const void *src, size_t n)


Another function to copy n characters from str2 to str1.

char *strcat(char *dest, const char *src)


Appends the string pointed to, by src to the end of the string pointed to by dest.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
char *strncat(char *dest, const char *src, size_t n)
Appends the string pointed to, by src to the end of the string pointed to, by dest up to n
characters long.

int strcmp(const char *str1, const char *str2)


Compares the string pointed to, by str1 to the string pointed to by str2.

int strncmp(const char *str1, const char *str2, size_t n)


Compares at most the first n bytes of str1 and str2.

char *strcpy(char *dest, const char *src)


Copies the string pointed to, by src to dest.

char *strncpy(char *dest, const char *src, size_t n)


Copies up to n characters from the string pointed to, by src to dest.

char *strstr(const char *haystack, const char *needle)


Finds the first occurrence of the entire string needle (not including the terminating null
character) which appears in the string haystack.

char *strtok(char *str, const char *delim)


Breaks string str into a series of tokens separated by delim.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Structures in C
Introduction:
 Applications are used to store and process the information
 We store information using variables and process using functions.
 We use different types of variables to store the information as follows.

Primitive variable: stores only one value at a time.

int a = 10;

Array variable: stores more than one value but of same type.

int arr[5] = {10, 20, 30, 40, 50};

Structure variable: stores more than one value of different data types. We define structures
using struct keyword.
struct Employee
{
int id;
char name[20];
float salary;
};
struct Employee e = {101, "Amar", 35000};

Array of Structures: used to store more than one record details.


struct Employee{
int id;
char name[20];
float salary;
};
struct Employee arr[3];

Memory representation:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Note: Structure is a data type and memory allocate to structure only when we create variable
Structure (Data type) Memory allocation (create variable)
struct Employee
{
int id; struct Employee e;
char name[20];
float salary;
};

Program to find the size (memory allocated to structure): sizeof() functions returns the total
number bytes allocated to structure.

#include<stdio.h>
struct Emp{
int id;
char name[20];
float salary;
};
int main(){
struct Emp x;
printf("size of Emp : %d \n", sizeof(x));
printf("size of Emp : %d \n", sizeof(struct Emp));
return 0;
}

Structure initialization: Like Primitive types and Arrays, we can assign values directly to
structure variables at the time of declaration.
struct identity var = {val1, val2, val3 …};

Accessor (dot operator): We must access the locations of structure through dot(.) operator
#include<stdio.h>
struct Employee {
int id;
char name[20];
float salary;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
};
int main(){
struct Employee e = {101, "amar", 35000};
printf("Employee id : %d \n", e.id);
printf("Employee name : %s \n", e.name);
printf("Employee salary : %f \n", e.salary);
return 0;
}

Program to pass structure as parameter to function:


 Functions can take structure as input parameter.
 We pass the structure variable as parameter and collect into same type of structure
variable.

#include<stdio.h>
struct Employee {
int id;
char name[20];
float salary;
};
void display(struct Employee);
int main(){
struct Employee x = {101, "Amar", 35000};

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
display(x);
return 0;
}
void display(struct Employee y){
printf("Emp id : %d \n", y.id);
printf("Emp name : %s \n", y.name);
printf("Emp salary : %f \n", y.salary);
}

Program to define a function that returns structure:


#include<stdio.h>
struct Emp{
int id;
char name[20];
float salary;
};
struct Emp collect();
int main(){
struct Emp y;
y = collect();
printf("Emp id : %d \n", y.id);
printf("Emp name : %s \n", y.name);
printf("Emp salary : %f \n", y.salary);
return 0;
}
struct Emp collect(){
struct Emp x = {101, "Amar", 35000};
return x;
}

Array of Structures: by creating array type variable to structure data type, we can store multiple
records like Employee details, Customer details, Student details, Account details etc.
struct Emp{ struct Emp e; -> store 1 record
.... struct Emp e1, e2, e3; -> store 3 records
}; struct Emp arr[100]; -> store 100 records

Program to store multiple records into Array variable of structure type:


#include<stdio.h>
struct Emp{
int id;
char name[20];
float salary;
};

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
struct Emp arr[3];
int i;

printf("Enter 3 Emp records : \n");


for(i=0 ; i<3 ; i++)
{
printf("Enter Emp-%d details : \n", i+1);
scanf("%d%s%f", &arr[i].id, arr[i].name, &arr[i].salary);
}
printf("Employee details are : \n");
for(i=0 ; i<3 ; i++)
{
printf("%d \t %s \t %f \n", arr[i].id, arr[i].name, arr[i].salary);
}
return 0;
}

Arrays in structure: If the structure contains Array type variable, we need to process the data
using loops.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct Student
{
int id;
char name[20];
int marks[5];
};

int main()
{
struct Student s;
int i;
printf("Enter Student id and name : \n");
scanf("%d%s", &s.id, s.name);
printf("Enter student marks of 5 subjects : \n");
for(i=0 ; i<5 ; i++)
{
scanf("%d", &s.marks[i]);
}
printf("Student details are : \n");
printf("%d, %s, ", s.id, s.name);
for(i=0 ; i<5 ; i++)
{
printf("%d ,", s.marks[i]);
}
return 0;
}

Store more than one student records including their marks:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct student
{
int id;
char name[20];
int marks[5];
};
int main()
{
struct student a[3];
int i,j;
printf("Enter student details\n");
for(i=0;i<3;i++) {
printf("Enter student id and name\n");
scanf("%d%s",&a[i].id,a[i].name);
printf("Enter marks of student\n");
for(j=0;j<5;j++)
scanf("%d",&a[i].marks[j]);
}
printf("Student details are \n");
for(i=0 ; i<3 ; i++) {
printf("%d \t %s \t ",a[i].id,a[i].name);
for(j=0;j<5;j++)
printf("%d\t",a[i].marks[j]);
printf("\n");
}
return 0;
}

Nested structures: Defining a structure inside another structure. We access the elements of
nested structure using outer structure reference variable.
#include<stdio.h>
struct Emp
{
int num;
float salary;
};
struct Employee
{
struct Emp e;
char name[20];
};

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
struct Employee x;

printf("Enter emp details(num, name, salary) : ");


scanf("%d%s%f", &x.e.num, x.name, &x.e.salary);

printf("Emp name is : %d \n",x.e.num);


printf("Emp name is : %s \n",x.name);
printf("Emp name is : %f \n",x.e.salary);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Unions in C
Introduction:
 Union is a user defined data type.
 Unions were used when memory at premium.
 A union basically allows a variable to have more than one type; but only one of these
types can be used.

Syntax: Example:
union identity union Test
{ {
Members; char c;
}; short s;
};

STRUCTURE UNION
Define with struct keyword. Define with union keyword
The size of the structure is equal to the sum of The size of the union is equal to the size of the
the sizes of its members. largest member.
Each member within a structure is assigned a Memory allocated is shared by individual
unique storage area. members of the union.
Individual members can be accessed at a time. Only one member can be accessed at a time.
Altering the value of a member will not affect Altering the value of any of the member will
other members of the structure. alter other member values.

Program to display size of union: The sum of all sizes of variables defined in structures is the
size of total structure.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct st{
char a;
short b;
float c;
};
union un{
char a;
short b;
float c;
};
int main(){
struct st s ;
union un u ;
printf("Size of structure : %d \n", sizeof(s));
printf("Size of union : %d \n", sizeof(u));
return 0;
}

Accessing members of union: We use dot(.) operator to access the members of union.

Note: We can define any number of variables inside the union, but we cannot use multiple
variables at a time. We will get odd results like follows.

#include<stdio.h>
union un{
int a, b;
};
int main(){
union un u ;
u.a = 10;
printf("b value is : %d \n", u.b);
u.b = 20;
printf("a value is : %d \n", u.a);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
union un
{
char a[2];
int b;
};
int main()
{
union un u ;
u.a[0] = 2 ;
u.a[1] = 3 ;

printf("b value is : %u \n", u.b);


return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointers in C
Introduction:
 Pointers is a derived data type in C.
 Pointer type variables store addresses of memory locations.

Pointers classified into:


1. Typed: These pointers can point to specific type data
int* -> points to integer data
float* -> points to float data
struct Emp* -> points to Emp data

2. Un-typed: Can points to any type of data. It is also called Generic pointer.
void* -> can points to any data.

Operators using with Pointers: Every operation in data processing using pointers is possible
through 2 operators.
1. Address Operator (&): It returns the memory address of specified variable.
2. Pointer operator (*): It returns the value in the specified address.

Following program explains the memory representation of pointer variables:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Call by Value & Call by Reference
Call by value: A copy of the variable is passed to the function.
Call by reference: An address of the variable is passed to the function.

Note: Call by reference is preferred when we have to return more than one variable, like in C
programming where we can only return one variable at a time. Call by reference can be achieved
via pointers.

Swapping two numbers:

Call By Reference: In this example, the output shows the correct result. This happens because
we have sent the exact address of the variable.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Size of Pointer:
 Pointer variable stores address(integer) hence the size of pointer equals to integer size.
 sizeof() function can be used to display the size of each pointer type.

#include<stdio.h>
int main(){
char* a;
short* b;
float* c;
double* d;
printf("char* size : %d \n", sizeof(a));
printf("short* size : %d \n", sizeof(b));
printf("float* size : %d \n", sizeof(c));
printf("double* size : %d \n", sizeof(d));
return 0;
}

Pointer size varies from compiler to compiler:


Compiler Int size Pointer size
16 bit 2 bytes 2 bytes
32 bit 4 bytes 4 bytes
64 bit 8 bytes 8 byte

Pointer increment / decrement: When we modify the pointer, the value increase or decrease
by size bytes.

#include<stdio.h>
int main(){
char x = 'a';
float y = 2.3;
double z = 4.5;
char* p1 = &x;
float* p2 = &y;
double* p3 = &z;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("p1 value is : %u \n", p1);
printf("++p1 value is : %u \n", ++p1);
printf("p2 value is : %u \n", p2);
printf("++p2 value is : %u \n", ++p2);
printf("p3 value is : %u \n", p3);
printf("++p3 value is : %u \n", ++p3);
return 0;
}

Pointer to function: Function has address that we can assign to pointer variable by which we
can invoke the function.

Syntax: <return_type> (*<ptr_name>)(args_list);

Example: int (*fptr)(int,int);

Where: “fptr” is a pointer that points to a function which is taking 2 integers and return integer.

int add(int,int);
int sub(int,int);
int main(){
int r1, r2, r3, r4;
int (*fptr)(int,int);
r1=add(10,20);
r2=sub(10,20);
printf("r1 : %d\nr2 : %d\n",r1,r2);

fptr = &add; /*pointing to add function*/


r3=fptr(30,50);

fptr = &sub; /*pointing to sub function*/


r4=fptr(30,50);
printf("r3 : %d\nr4 : %d\n",r3,r4);
return 0;
}
int add(int x, int y){
return x+y;
}
int sub(int x, int y){
return x-y;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointer type-casting:
 Converting one type of pointer variable into another type to access the data.
 (type*) syntax is used to perform type casting.

#include<stdio.h>
void main(){
int i = 100;
int* ip;
char* cp;
ip = &i;
cp = (char*)ip;
printf("i value : %d\n", *ip);
printf("i value : %d\n", *cp);
}

Pointer to Pointer:
 It is also called “double pointer”
 A “Pointer to Pointer” variable holds the address of another “Pointer variable”

#include<stdio.h>
int main()
{
int x = 10;
int* px = &x;
int** ppx = &px;

printf("x val : %d \n", x);


printf("x val : %d \n", *px);
printf("x val : %d \n", **px);
return 0;
}

Array internal pointer representation:


 Generally, we access elements of array using their index.
 For example, arr[i]
 The expression arr[i] converts into *(arr+i)

#include<stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
printf("Array elements are : \n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0 ; i<5 ; i++)
printf("%d\n", arr[i]);

printf("Array elements are : \n");


for(i=0 ; i<5 ; i++)
printf("%d\n", *(arr+i));
return 0;
}

In multiple ways, we can access the elements of array:


#include<stdio.h>
int main()
{
int arr[5] = {10,20,30,40,50};
int i;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d, %d, %d, %d \n", arr[i], *(arr+i), *(i+arr), i[arr]);
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointers to Arrays:
 Array variable stores address of memory block hence it is pointer type.
 We can assign array variable directly to pointer variable and access the element using
that pointer variable.

#include<stdio.h>
void main(){
int a[5] = {10,20,30,40,50}, i;
int *p = a;
p=a;
for(i=0; i<5; i++){
printf("%d\t",a[i]);
printf("%d\t",p[i]);
printf("%d\t",*(p+i));
printf("%d\t",*(i+p));
printf("%d\n",i[p]);
}
}

#include<stdio.h>
int main(){
int arr[5] = {10,20,30,40,50};
int *p = arr;
printf("%d \n", *++p);
printf("%d \n", *(p+2));
printf("%d \n", *++p+3);
return 0;
}

#include<stdio.h>
int main(){

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[5] = {10,20,30,40,50};
int *ptr = arr;
printf("%d \n", *(++ptr+1));
return 0;
}

#include<stdio.h>
int main(){
int arr[5] = {10,20,30,40,50},i;
int* ptr;
ptr = arr;
printf("%u\n", *++ptr + 3);
printf("%u\n", *(ptr-- + 2) + 5);
printf("%u\n", *(ptr+3)-10);
return 0;
}

#include<stdio.h>
int main(){
int arr[5] = {8, 3, 4, 9, 2},i;
int* ptr;
ptr = arr;
printf("%u\n", *(--ptr+2) + 3);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%u\n", *(++ptr + 2) - 4);
printf("%u\n", *(ptr-- +1 ) + 2);
return 0;
}

#include<stdio.h>
int main(){
int arr[5] = {5, 2, 7, 3, 6},i;
int* ptr;
ptr = arr;
printf("%d\n", *(ptr++ + 1) - 2);
printf("%d\n", *(ptr-- + 3) - 10);
printf("%d\n", *(--ptr + 2 ) + 5);
return 0;
}

Pointer to String:
 A char* can points to a single character or a String.
 Char* holds the base address.
 We can process the strings using %s

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 To process character by character, we use %c

#include<stdio.h>
void main(){
char* s = "Harsha" ;
printf("%s \n", s);
printf("%c \n", s);
printf("%c \n", *s);
printf("%c \n", *(s+3));
printf("%c \n", *s+3);
}

void main(){
char* s = "Sathya" ;
printf("%c \n", *++s+2);
printf("%c \n", *++s);
printf("%c \n", *(s+2));
printf("%c \n", *s--);
printf("%c \n", *--s);
}
#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n", *str++ + 3);
printf("%s\n", ++str+2);
}

#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n" , *(str++ + 2)+3);
printf("%c\n" , *++str+2);
printf("%s\n" , --str-1);
}

#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n",*((str-- +2)+1)-3);
printf("%c\n", *(--str + 3)-32);
printf("%c\n",*(++str+2)+4);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void main(){
char sport[ ]= "cricket";
int x=1 , y;
y=x++ + ++x;
printf(“%c”,sport[++y]);
}

Array of Pointers: If the array is Pointer type, it can store multiple references called Array of
Pointers.
#include<stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
int* ptr[5];
for(i=0 ; i<5 ; i++){
ptr[i] = &arr[i];
}
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", *ptr[i]);
}
return 0;
}

We can access elements without using index as follows:


#include<stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
int* ptr[5];
for(i=0 ; i<5 ; i++){
*(ptr+i) = arr+i;
}

printf("Array elements are : \n");


for(i=0 ; i<5 ; i++){
printf("%d \n", **(ptr+i));
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
A function can return the string using char* return type.
#include<stdio.h>
char* read(void);
int main(){
char* name;
name = read();
printf("Name returned by read function is : %s \n", name);
return 0;
}
char* read(void){
char* name;
printf("Enter your name : ");
gets(name);
return name;
}

Array of Strings:
 We can declare an array variable that stores list of pointers(strings base address).
 We can process all the strings using array variable.

#include<stdio.h>
int main()
{
char* list[5] = {"C", "Java", "Python", "Android", "IOS"};
int i;

printf("List is : \n");
for(i=0 ; i<5 ; i++)
{
printf("%s \n", list[i]);
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main()
{
char* list[5] = {"C", "Java", "Python", "Android", "IOS"};
int i;

printf("List is : \n");
for(i=0 ; i<5 ; i++)
{
/* printf("%c \n", list[i]); */
printf("%c \n", *list[i]);
}
return 0;
}

#include<stdio.h>
void main()
{
char *s[ ] = {"black", "white", "pink", "violet"};
char **ptr[ ] = {s+3, s+2, s+1, s};
char ***p;
p = ptr;
++p;
printf("%s\n", (*(*p+1)+1)+2);
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
A function returning address:
A function can return address of aggregate data type variable or user defined data type
variable to access the data.

#include<stdio.h>
int* add(int,int);
void main(){
int a, b, *c;
printf("enter two numbers : ");
scanf("%d%d",&a,&b);
c = add(a,b);
printf("sum : %d\n",*c);
}
int* add(int x, int y) {
int z;
z=x+y;
return &z;
}

Dangling pointer:
 In the above code, add function returns the address of local variable.
 Local variables will be deleted once the function execution completes.
 As we return the address of location, the value of that location may change by another
function before processing the data.
 Hence Dangling pointers will not provide accurate results(values).

#include<stdio.h>
int *fun()
{
int x = 5;
return &x;
}
int main()
{
int *p = fun();
fflush(stdin);
printf("%d", *p);
return 0;
}

How to read complex pointers in C Programming?


Assign the priority to the pointer declaration considering precedence and associative according
to following table.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Operator Precedence Associative
(),[] 1 Left to right
*, identifier 2 Right to left
Data type 3

Where:
() : This operator behaves as function operator.
[] : This operator behaves as array subscription operator.
* : This operator behaves as pointer operator.
Identifier : it is name of pointer variable.
Data type : Data types also includes modifier (like signed int, long double etc.)
How to read following pointer?
char (* ptr)[3]

Step 1: () and [] enjoys equal precedence. So rule of associative will decide the priority. Its
associative is left to right So first priority goes to ().
Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of associative (right to
left) first priority goes to ptr and second priority goes to *.
Step3: Assign third priority to [].
Step4: Since data type enjoys least priority so assign fourth priority to char.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Dynamic Memory Allocation

 Applications are used to store and process information.


 We use variables to store the information.
 We allocate memory to variables in 2 ways
o Static memory allocation
o Dynamic memory allocation

Using pointers, we can create variables which are ready to hold addresses of memory blocks.
The size of memory block specified at runtime through Dynamic memory allocation.

stdlib.h: stdlib.h library contains pre-defined functions to allocate and de-allocate the memory
at runtime.
1. malloc(): allocates memory dynamically to structure variables
2. calloc(): allocates memory dynamically to array variables
3. realloc(): used to modify the size of Array created by calloc()
4. free(): used to release the memory which is allocated.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointer type casting:
 One type of pointer can points to same type of data.
 Incompatible pointer type error occurs, when we try to access another type of data.
 We can typecast from one type to another type as follows.

#include<stdio.h>
int main(){
int x=10;
int* p1;
char* p2;

p1 = &x;
printf("x value is : %d \n", *p1);

p2 = (char*)p1;
printf("x value is : %d \n", *p2);
return 0;
}

malloc() : Allocates numbers of bytes specified by the Size of Structure.


Prototype: void* malloc(size_t size);

 "size_t" represents "unsigned" value.


 On success, it returns base address of allocated block.
 On failure, it returns NULL.

#include<stdio.h>
#include<stdlib.h>
struct Emp
{
int num;
char name[20];
float salary;
};

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct Emp));
if(p==NULL)
printf("Memory allocation failed \n");
else
printf("Memory allocation success \n");
return 0;
}

 We access locations of structure memory using dot(.) operator.


 If a pointer is pointing to structure, we use arrow(->) operator to access the location.

#include<stdio.h>
#include<stdlib.h>
struct Emp{
int num;
char name[20];
float salary;
};
int main(){
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct Emp));
if(p==NULL){
printf("Memory allocation failed \n");
}
else{
printf("Enter Emp details :\n");
scanf("%d%s%f", &p->num, p->name, &p->salary);
printf("Name is : %s \n", p->name);
}
return 0;
}

calloc() : Allocate memory to Arrays using pointers.


void* calloc(size_t n , size_t size);

 First argument specifies number of elements in the array.


 Second argument specifies size of each element.
 If memory is available, it allocates n*size bytes and returns first byte address.
 If no memory, it returns NULL.
 After allocating the memory all the byte locations are initialized with "0" by default.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, *arr, i;

printf("Enter size of array : ");


scanf("%d", &n);

arr = (int*)calloc(n, sizeof(int));


if(arr==NULL){
printf("Failed in memory allocation \n");
}
else{
printf("Array elements are : \n");
for(i=0 ; i<n ; i++)
{
printf("%d \n", *(arr+i));
}
}
return 0;
}

Read and find the sum of array elements :


#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, *arr, i, sum=0;

printf("Enter size of array : ");


scanf("%d", &n);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
arr = (int*)calloc(n, sizeof(int));
if(arr==NULL){
printf("Failed in memory allocation \n");
}
else{
printf("Enter array elements : \n");
for(i=0 ; i<n ; i++)
scanf("%d", arr+i);
for(i=0 ; i<n ; i++)
sum = sum + *(arr+i);

printf("Sum is : %d \n", sum);


}
return 0;
}

realloc() :
 It is used to increase/decrease the size of array which is created by calloc()
 Using calloc(), we can create the size with fixed size
 Dynamic memory : Size varies depends on requirement
 We can modify the size of array using realloc() function
void* realloc(void* ptr, size_t size);

#include<stdlib.h>
void main(){
int *p1, *p2, m, n;
printf(“enter size of array : “);
scanf(“%d”,&m);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
p1 = (int*)calloc(m,sizeof(int));
if(p1 == NULL){
printf(“calloc failed\n”);
exit(1);
}
else
printf(“memory allocated..\n”);

printf(“Enter new size of array : “);


scanf(“%d”,&n);

p2=(int*)realloc(p1 , n*sizeof(int));
if(p2 == NULL){
printf(“realloc failed\n”);
exit(1);
}
else
printf(“memory re-aquired..\n”);
free(p1);
free(p2);
}

free() :
 The memory which has allocated dynamically must be released explicitly using free
function.
 Function prototype is:
o void free(void* ptr);
 Using free() 147unction , we can de-allocate the memory of any type of pointer.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
File Handling in C

File: A collection of Data or Program or Records identified by a Name.

FILE* pointer:
 FILE is a pre-defined structure type variable.
 FILE* can points to any type of file.
 Once we make the pointer pointing to a file, then we can perform all FILE operations
such as reading, writing, appending and so on.

Modes of Files:
Read mode(“r”):
 Opens file in Read mode.
 If file is present, it opens and returns pointer to that file.
 If file is not present, it returns NULL pointer.

Write mode(“w”):
 Opens file in Write mode.
 If file is present, it opens and removes the existing contents of File.
 If file is not present, it creates the new file with specified name.

Append mode(“a”):
 Opens file in append mode.
 If file is present, it opens and places the cursor at the end of existing data to add the new
contents.
 If file is not present, it creates the new file with specified name.

Opening a File:
 fopen() is a pre-defined function that opens a file in specified mode.
 On success, it opens and returns the pointer to file.
 On failure, it returns NULL pointer.
FILE* fopen(char* path, char* mode);

#include<stdio.h>
int main(){
FILE* p;
p = fopen("c:/users/srinivas/desktop/code.c", "r");
if(p==NULL)
printf("No such file to open \n");
else
printf("File opened in read mode \n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Reading File character by character:
 fgetc() is a pre-defined function belongs to stdio.h
 fgetc() function read the input file character by character.
 On success, it reads the character and returns ASCII value of that character
 On Failure, it returns -1(EOF)
int fgetc(FILE* stream);

#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL)
{
printf("No such file to open \n");
}
else
{
printf("File contents : \n");
while((ch=fgetc(p)) != -1)
{
printf("%c", ch);
}
}
return 0;
}

EOF (End Of File):


 It is pre-defined constant variable.
 EOF is a macro(constant)
 Constant variables represent in capital letters(in all programming languages)
 EOF is assigned with value -1
 EOF represents “End Of File” while processing file data.

#include<stdio.h>
int main(){
printf("EOF value is : %d \n", EOF);
printf("EOF character is : %c \n", EOF);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Closing the File: fclose() is used to close the file after use.
 It is recommended to release every resource(file) after use.
 On success, it returns 0.
 On Failure, it returns -1.
int fclose(FILE* stream);

We must release Resource (File, Database) after use. Improper shutdown causes loss of data.

#include<stdio.h>
int main(){
FILE* p;
int r1, r2;
p = fopen("code.c", "r");
if(p != NULL){
r1 = fclose(p);
printf("On success : %d \n", r1);
r2 = fclose(p);
printf("On failure : %d \n", r2);
}
return 0;
}

Writing character into File:


fputc(): A pre-defined function is used to write character into file.
void fputc(int x, FILE* stream);

#include<stdio.h>
int main(){
FILE *src, *dest;
int ch;
src = fopen("code.c", "r");
dest = fopen("output.txt", "w");
if(src != NULL){
while((ch = fgetc(src)) != EOF){
fputc(ch, dest);
}
printf("Data copied...\n");
fclose(dest);
fclose(src);
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
fseek(): It is used to move the cursor position in the opened file, to perform read and write
operations.
int fseek(FILE* steam, long offset, int origin);

Parameters:
 “offset” is a long type variable that represents the number of bytes to move.
o Positive offset moves the cursor in forward direction
o Negative offset moves the cursor in backward direction.
 Origin comes with
o SEEK_SET : Start of the file
o SEEK_CURR : Current cursor position
o SEEK_END : End of the file
 On success, if specified location is present, it moves the cursor and returns 0
 On failure, it returns -1.

#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
fseek(p, 100, SEEK_SET);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}
fclose(p);
}
return 0;
}

rewind(): Reset the cursor position to start of the file.


void rewind(FILE* stream);

#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}
else{
fseek(p, -50, SEEK_END);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}

rewind(p);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}
fclose(p);
}
return 0;
}

Reading String from the file:


fgets() is used to read specified number of characters(String) at a time.
char* fgets(char* str, int size, FILE* stream);

 It reads “size” bytes from specified “stream” and stores into “str”.
 On Success, it returns the pointer to string that has read.
 On failure, it returns NULL pointer.
 It reads only size-1 characters into String every time. Last character of every string is
null(\0) by default.

#include<stdio.h>
int main(){
FILE* p;
char str[10];
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
fgets(str, 10, p);
printf("The string is : %s \n", str);
fclose(p);
}
return 0;
}
Reading the complete file using fgets():
#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
FILE* p;
char str[10];
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
while(fgets(str, 10, p)){
printf("%s \t", str);
}
fclose(p);
}
return 0;
}

Writing String into File:


fputs() is used to write a string on to the file.
void fputs(char* str , FILE* stream);

#include<stdio.h>
int main(){
FILE *src, *dest;
char str[10];
src = fopen("code.c", "r");
if(src==NULL){
printf("No such file to open \n");
}
else{
dest = fopen("data.txt", "w");
while(fgets(str, 10, src)){
fputs(str, dest);
}
printf("Contents copied...\n");
fclose(src);
fclose(dest);
}
return 0;
}

feof():
 It used to test whether End of File has reached or not

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 It returns -1 when End of File has reached else returns 0
int feof(FILE* stream)

Reading File Character by Character:


#include<stdio.h>
int main(){
FILE *src;
int ch;
src = fopen("code.c", "r");
if(src==NULL){
printf("No such file to open \n");
}
else{
while(!feof(src)){
ch = fgetc(src);
printf("%c", ch);
}
fclose(src);
}
return 0;
}

Renaming the File:


 rename() function is used to rename the specified file.
 On success, it returns 0
 On failure, it returns -1
int rename(char* old, char* new);

#include<stdio.h>
int main(){
char old[20] = "data.txt";
char new[20] = "modified_data.txt";

if(rename(old, new)==0)
printf("successfully renamed...\n");
else
printf("Failed in renaming the file...\n");
return 0;
}

Remove the file from specified location:


 remove() is used to rename the specified file.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 On success, it returns 0
 On failure, it returns -1
int remove(char* target);

#include<stdio.h>
int main()
{
char target[20] = "data.txt";

if(remove(target)==0)
printf("successfully removed...\n");
else
printf("Failed in removing the file...\n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Enumeration in C

Introduction:
 An enumeration consists of a set of named integer constants.
 Each enumeration-constant in an enumeration-list names a value of the enumeration set.

Syntax:
enum identifier
{
enumerator-list
};

By default, the first enumeration-constant is associated with the value 0.


enum colors
{
black,
red,
green,
blue,
white
};
int main()
{
int i;
enum colors c;
for(i=0 ; i<5 ; i++)
{
printf("%d \n", c=i);
}
return 0;
}

If we don’t set values explicitly, by default values set in increasing order by one:
#include<stdio.h>
int main()
{
enum months {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
enum months month;
printf("month=%d\n",month=Feb);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
By using constant integer values, we can use the functionality of enum set elements:
#include<stdio.h>
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
int main()
{
enum Day today;
int x;
printf("Enter Day of Week(0 to 6) : ");
scanf("%d",&x);
today=x;
if(today==Sunday || today==Saturday)
printf("Enjoy! Its the weekend\n");
else
printf("Week day - do your work\n");
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Typedef in C

Introduction:
 typedef is a user-defined data type specifier.
 Using typedef we can define identifiers (synonyms) for data types.
 We can use synonyms instead of original data types.

Advantage: Synonyms to data types become more readable than complex identities

Giving the name Integer to int type:


#include<stdio.h>
int main()
{
typedef int Integer ;
Integer a=10,b=20,c;
c = a+b;
printf("res : %d\n",c);
return 0;
}

Creating Synonym to Array:


#include<stdio.h>
int main()
{
typedef int Arry[5];
int i;
Array arr = {10,20,30,40,50};
printf("Array elements are\n");
for(i=0 ; i<5 ; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}

The main advantage of typedef declaration is giving simple identity for complex types.
For example, char* can simply represent with name String.
#include<stdio.h>
typedef char* String;
String read(void);
int main(){
String name;
name = read();

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("welcome %s\n",name);
}
String read(){
String name;
printf("Enter one name : ");
gets(name);
return name;
}

Typedef declaration to Structures:


 Generally, identity of Structure is a combination of two words.
 For example, struct Emp
 We can give one word to structure type then representation become easy.

#include<stdio.h> #include<stdio.h>
typedef struct Emp{ struct Emp{
int eno; int eno;
char* ename; char* ename;
float esal; float esal;
} Employee; };
int main() int main()
{ {
Employee e; typedef struct Emp Employee;
} Employee e;
}

By using typedef declarations, we can shorten the size of instructions:


#include<stdio.h>
struct Emp{
int eno;
char* ename;
float esal;
};
int main()
{
typedef struct Emp Employee;
typedef struct Emp* Ptr;
Ptr e;
e = (Ptr)malloc(sizeof(Employee));
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Storage classes in C

Introduction:
 We need to specify the storage class along with datatype in variable declaration.
 Storage class describes
o Memory location of variable
o Default value of variable
o Scope of variable
o Lifetime of variable
 Storage classes classified into
o Automatic Storage classes
o Register Storage classes
o Static Storage classes
o External Storage classes

Syntax:
storage_class datatype name ;
Example:
auto int a ;
static int b ;

Block scope of a variable:


 Defining a variable inside the block.
 We can access that variable from the same block only.
 We cannot access from outside of the block or from other block.

#include<stdio.h>
int main()
{
{
int a=10;
printf("a val : %d \n", a);
}

{
int b=20;
printf("b val : %d \n", b);
printf("a val : %d \n", a); // Error :
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Function scope of a variable:
 Defining a variable inside the function.
 We can have number of blocks inside the function.
 Function scope variable can access throughout the function and from all block belongs
to that function.

#include<stdio.h>
int main()
{
int a=10; /* function scope */

{
int a=20; /* block scope */
printf("Inside First block, a val : %d \n", a);
}

{
printf("Inside Second block, a val : %d \n", a);
}

printf("Inside function, a val : %d \n", a);


return 0;
}

Note: If we don’t provide any value to local variable, by default the value is “Garbage value”
#include<stdio.h>
int main()
{
int a;
{
int a=10;
printf("a val : %d \n", a);
}

{
printf("a val : %d \n", a);
}

return 0;
}
Program scope:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
 Defining a variable outside to all function
 We can also call it as Global variable
 We can access the global variable throughout the program.

#include<stdio.h>
void test(void);
int a=10; /*program scope*/
int main(){
int a=20; /*function scope */
{
int a=30; /*block scope */
printf("In block : %d \n", a);
}
printf("In main : %d \n", a);
test();
return 0;
}
void test(){
printf("In test : %d \n", a);
}

Automatic Storage classes:


Keyword: auto
Memory location: Inside the RAM
Default value: Garbage Value
Scope: Belongs to Block in which it has defined.

Note: auto variables must be local. If we don’t give storage class to local variable, it is auto
default.

#include<stdio.h>
int main(){
auto int a=10;
{
auto int a;
printf("In block : %d \n", a);
}
printf("In main : %d \n", a);
return 0;
}

We cannot define auto variables globally:


#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
auto int a=30; /* Error : */
int main(){
auto int a=10;
printf("In main : %d \n", a);
return 0;
}

Register storage classes:


Keyword: register
Memory allocation: Inside CPU registers
Scope: Within the block or method

Note: Register variable must be defined as local variable.

Auto v/s Register variables:


 “auto” variables get memory in RAM
 “register” variables get memory inside Registers.
 “Register” variables can access much faster than “auto” variables.

Note: Repeated variables in the logic must be defined as register variables. For example “Loop
counters”

Can’t we declare all variables as register?


 No, Registers is a small memory area. Hence, we cannot store maximum number of
variables into registers.
 Only local variables and repeated variables need to store into registers.

We cannot define register variables globally:


#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
register int a=30;
int main()
{
auto int a=10;
printf("In main : %d \n", a);
return 0;
}

Static storage classes:


Keyword: static
Memory: Inside RAM
Scope: Static variables can be either local or global. If the variable is local, can access within the
block. If it is global, we can access throughout the program.
Default value: 0

#include<stdio.h>
static int x=10;
void test();
int main(){
static int y;
printf("y val : %d \n", y);
test();
return 0;
}
void test()
{
printf("x val : %d \n", x);
}

Local variables memory will be deleted as soon as function execution completes.


#include<stdio.h>
void test();
int main()
{
test();
test();
test();
test();
return 0;
}
void test()
{
auto int x=5;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
x=x+2;
printf("x val : %d \n", x);
}

Static variable memory will be deleted only when program execution completes.
#include<stdio.h>
void test();
int main()
{
test();
test();
test();
test();
return 0;
}
void test(){
static int x=5;
x=x+2;
printf("x val : %d \n", x);
}

External storage classes:


Keyword: extern
Memory: Inside RAM
Scope: Can access anywhere in the application

Note: External variables always global variables. These variables get memory only when we
initialize with any value.

External variables cannot be global:


#include<stdio.h>
int main()
{
extern int a=10;
printf("a value is : %d \n", a);
return 0;
}

Global variables must be initialized with value. Runtime error raises if we access external
variable without value.
#include<stdio.h>
extern int a;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
printf("a value is : %d \n", a);
return 0;
}

Memory allocates only when we initialize:


#include<stdio.h>
extern int a=10;
int main()
{
printf("a value is : %d \n", a);
return 0;
}

The declaration statement will not consider, memory allocates only when we assign value:
#include<stdio.h>
extern int a;
extern int a;
extern int a;
extern int a=10;
int main()
{
printf("a value is : %d \n", a);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Command Line Arguments in C
Accepting Command Line arguments:
Every C application runs by Computer Operating System. OS runs the program from its
environment. Every OS consists CUI and GUI mode. To read command line arguments, we need
to run the C program from CUI OS mode.

Run application from Command prompt:


 Cmd Prompt is Ms-DOS
 It is Command User Interface.
 OS takes command as input and open specified application which is present in that
machine.
 We compile and run the code from command line using tcc compiler as follows

Code program:
#include<stdio.h>
int main(){
printf("Hello...\n");
return 0;
}
Note: save into "turboc" folder with name Program.c

Open command prompt:


Compilation:
C:/turboc> tcc Program.c
-> Generate Program.exe file

Execution:
C:/turboc>Program.exe
-> Generate output.

main() prototype: Regular main() function prototype is slightly different from the main()
function taking command line arguments. We must define main() function as follows
int main(int argc , char* argv[ ])

where:
‘argc’ = argument count ( Number of arguments passed at command line including file
name)
‘argv’ = argument vector(list) (List of arguments - default type is String)

Why argument type is String by default?


Answer: In any programming language, only String type can hold any data.
main(int[]) --> can take only integers
main(float[]) --> can take only float values.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
main(char* []) --> can hold any type of data.
char* a = "10";
char* b = "23.45";
char* c = "g";
char* d = "CBook";

How can we convert String to corresponding primitive type?


We collect the input in String format from command line. dos.h header file is providing
functions for this data conversions. The two functions used for data conversions as follows
1. int atoi(char* s) : Converts input string to integer on success
2. float atof(char* s) : Converts input string to float on success

Program to display Arguments count:


#include<stdio.h>
int main(int argc , char* argv[]){
printf("Count is : %d \n", argc);
return 0;
}

cmd/> Program
Output : Count is : 1

cmd/> Program 10 20 30 40 50
Output : Count is : 6

cmd/> Program 10 23.45 g online


Output : Count is : 5

Program to display list of input arguments:


#include<stdio.h>
int main(int argc , char* argv[]){
int i;
if(arc==1){
printf("No input values \n");
}
else{
printf("Arguments are :\n");
for(i=1 ; i<argc ; i++){
printf("%s\n", argv[i]);
}
}
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
cmd/> Program
Output : No input values

cmd/> Program 10 23.45 g online


Arguments are :
10
23.45
g
online

Reading input from command line and add:


#include<stdio.h>
int main(int argc , char* argv[]){
int i;
if(arc<3){
printf("Insufficient input values \n");
}
else{
char* s1 = argv[1]);
char* s2 = argv[2]);

int x = atoi(s1);
int y = atoi(s2);
printf("Sum is : %d \n" , x+y);
}
return 0;
}

cmd/> Program
Output : Insufficient input values

cmd/> Program 10 20
Output : Sum is : 30

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pre-Processor in C

Introduction:
 Pre-processor program that modifies the text of a C program before it is compiled.
 Pre-processing includes
o Inclusion of other files
o Definition of symbolic constants and macros
o Conditional compilation of program code
o Conditional execution of preprocessor directives

Preprocessing, Compiling and Linking:


one.c --> PREPROCESSOR -> tmp.c(temporary) -> COMPILER -> one.obj ->
LINKER -> one.exe (final Executable)

Inclusion of header files:


 C application is a collection of Source files(.c) and Header files(.h)
 #include directive is used to connect the files in C application

We include Library file as well as Custom defined Files:


#include <filename>
 Searches standard library for file
 Use for standard library files
#include "filename"
 Searches current directory, then standard library
 Use for user-defined files

if you have a header file ‘header.h’ as follows,


int x;
int biggest(int x, int y)
{
retrun x>y?x:y;
}

and a main program called ‘program.c’ that uses the header file, like this,
#include "header.h"
int main (void)
{
x=biggest(10,20);
printf(“big :%d”,x);
return 0;
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Macros(#define):
 We use #define to create Macro constants.
 Constants recommended to define in Upper case.
 At the time or pre-processing all Macros replaced with their values.

Syntax:
#define identifier replacement-text

Example:
#define PI 3.14159

Function-like Macros
 You can also define macros looks like a function call.
 For example,
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
 Would cause
area = CIRCLE_AREA( 4 );
 To become
area = ( 3.14159 * ( 4 ) * ( 4 ) );

Conditional Compilation (#if, #ifdef, #ifndef, #else, #elif, #endif)


Six directives are available to control conditional compilation. They delimit blocks of
program text that are compiled only if a specified condition is true.

#if directive:
It is conditional compilation directive. If the condition is valid then the code defined
inside the block gets compiled.

Syntax:
#if <Constant_expression>
-------------
-------------
#endif

If constant expression will return 0 then condition will FALSE if it will return any non-zero
number condition will TRUE.
#include<stdio.h>
#if 0
int main(){
printf("HELLO WORLD");
return 0;
}
#endif
Runtime Error: undefined symbol main

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#else directive: The code which is defined in else-block gets compiled if the condition fails.
#include<stdio.h>
#if(-4)
int main(){
printf("WELCOME TO C-WORLD ");
return 0;
}
#else
int main(){
printf("HELLO WORLD");
return 0;
}
#endif

Output: WELCOME TO C-WORLD

#include<stdio.h>
int main()
{
int var = 5;
#if var
printf("%d",var);
#else
printf("%d",var);
#endif
return 0;
}
Compile time Error: Directive #if will not think expression constant var as integer variable and
also it will not throw an error. Then what is var for directive #if?

Directive #if will treat var as undefined macro constant.


#include<stdio.h>
#define var 10
int main(){
#if var
printf("%d",var);
#else
printf("%d",var);
#endif
return 0;
}
Program to display System date using pre-defined Macro constant:
#include<stdio.h>

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
#ifdef __DATE__
printf("%s",__DATE__);
#else
printf("First define the __DATE__");
#endif
return 0;
}
Output: It will print current system date.
Explanation: __DATE__ is global identifier. It has already defined in the header file stdio.h and it
keeps the current system date.

Program to display System Time using pre-defined Macro


#include<stdio.h>
#define I 30
int main()
{
#ifndef __TIME__
printf("%d",I);
#else
printf("%s",__TIME__);
#endif
return 0;
}
Output: It will print current system time.
Explanation: __TIME__ is global identifier. It has been defined in the header file stdio.h.
Compiler doesn’t compile the c codes which are inside the any conditional preprocessor
directive if its condition is false. So we can write anything inside it.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.

You might also like