0% found this document useful (0 votes)
2 views

C - Introduction-Tokens

The document provides a comprehensive overview of the C programming language, including its history, features, and basic structure. It covers essential concepts such as data types, variables, constants, and operators, along with examples of C programs and their development steps. Additionally, it explains the significance of tokens, identifiers, and formatting output in C.

Uploaded by

nagas2820
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C - Introduction-Tokens

The document provides a comprehensive overview of the C programming language, including its history, features, and basic structure. It covers essential concepts such as data types, variables, constants, and operators, along with examples of C programs and their development steps. Additionally, it explains the significance of tokens, identifiers, and formatting output in C.

Uploaded by

nagas2820
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 92

C PROGRAMMING LANGUAGE

======================

INTRODUCTION:
----------------------
1.C Programming Language is used to develop programs or software's.

2.C Programming Language was most popular general purpose programming language.

3.We can develop system software�s and Application software�s by using C


programming language.

4.Most of the features of C were derived from its previous languages like B and
BCPL.

Brief History of C:
1.C was developed by DENNIS RITCHIE in 1972 at Bell labs of AT & T [American
Telephone and Telegraphs] in USA.

2.C was mainly invented to create �UNIX� operating system(OS).

3.C Language was well suited to develop all types of softwares (System softwares &
Application softwares).Hence it was called as general purpose programming language.

Features of C Language: [Characteristics]


-----------------------------
1.C is structured programming language.

2.C is highly portable programming language.

3.C has a rich set of operators.

4.C has several predefined functions (standard library).

5.C has only 32 keywords.

6.C supports all data conversions and mixed mode operators.

7.Dynamic memory storage allocation is possible with C.

8.C was simple and multi purpose programming language.

9.The programs written in C are efficient and fast.

10.Extensive verities of data types such as Arrays, Strings, pointers, structures,


Unions etc., available in C.

Important Points:
---------------------
1.C is a case sensitive programming language. C statements are entered in lower
case letters only.

ex; SWITCH switch

2.Every C statement must be terminated by a semicolon (;) except preprocessor


statements and function definition.
3.Any C program that contains one or more functions, but one main( ) function is
mandatory.

BASIC STRUCTURE OF C PROGRAM:


--------------------------------------------
We must follow syntax (structure, i.e set of rules) while writing a c-program.
A c-program structure is divided into following sections;

1. [Documentation Section]

2. Pre-Processor section Or Link Section.

3. [Global declaration section]

4. Main( ) section
{
[Local declaration section]

Statements
}

5. [Sub programming section]


{
[Local declaration section]

Statements
}
Note:Sections in square brackets are optional.

C-Comments:
------------------
C-comments are used to prepare documentation section, and also prepare guide lines
to the beginer.
The commented lines in the program, are skipped by the compiler while execution.

1.Single-line comment:
//....................

2.Multi-line comments:
/*...............
...................
..................
*/

Example Program;[Basic structure of C-program Demostration]


-------------------------
//This is example C-program to display 'Hello world'

[OR]
/*
This is example C-program to display Hello world
Output:'Hello World'
Author:Cyber World //Documentation Section
Date:20-Oct-2023
*/
#include<stdio.h>
#include<stdlib.h> //Link Section
#define PI 3.14

float pi=3.14;
int max=100; //Global declaration Section

void main( ) //Main Section


{
printf("Hello World");
}

void message( ) //sub program section


{
printf("Thank you");
}

C-Program Development steps:


--------------------------------------
There are so many C & CPP compilers like TurboC++, DevCpp, CodeBlocks, gcc-
compiler, VisualCode, ... etc.
First Download Dev-Cpp compiler from "https://www.embarcadero.com/free-tools/dev-
cpp" at free of cost.
Load/Install cpp compiler [Embercadero Dev-Cpp] on to your computer.

1.Create C-program
Open Dev-C++ editor ; File->New->Sourse file (Ctrl+N)

2.Write & Save C-program; Type or write program.


After completion of writing, then Save as the program;
File->Save As ->A Save As window opend, then write filename with dot C
extention.
[ex; sample.c] then click on Save

3.Compile the program; To check syntax errors (compile time errors)


Goto->Execute Tab -> Compile (F9)

Note1:The process of rectifying errors in the program is called as


'Debugging'.

Note2:If Errors are 0(zero) and Warning are 0(zero), then go to


Execution/Run.

4.Execute/Run the program


Goto->Execute -> Execute/Run (F10)

printf( ) AND scanf( ):


==============
printf( ) & scanf( ) are pre-defined functions and these are available with
<stdio.h>.
So we must include <stdio.h> at link section in the program before use these
functions.
printf( � �): -
--------------
It is a pre-defined function and is used to print/display data(message) on the
console screen (i/o window).
Syntax:
int printf (�control sting�,[arg-1,arg-2,��..arg-n]);

The printf statement is used to print messages, the values contain in the variable
on the screen.
Example: printf("WELCOME");

scanf():-
----------
It is a pre-defined function, which is used to read data (inputing data) from
standard input device (keyboard) through console window.
Syntax:-
int scanf(�format(s)�,address-1,address-2,....,address-n);

Example:-
int n;
scanf("%d",&n); // Here '&n' is memory Address of n

C - TOKENS
----------------

The smallest individual units or elements in a C-program statement,are called as


tokens.

[software -> set of programs -> set of statements -> set of tokens.]

C has the following tokens�

1. C-Keywords
2. C-Data types
3. Identifiers ---> names of variables,arrays,functions,pointers,structures etc.
4. Constants
5. Character set
6. Escape sequence characters
7. Operators

C-KEYWORDS
-----------------
A c-keyword is a reserved word,which is used for specific purpose in the program
development.
Don't use these keywords for other purpose in the program development.
A c-keyword is a English word/phrase.
All keywords are must be in lower case letters (small alphabet).
Every keyword, that has internal code, hence it is key to code.

C language has 32 keywords only.Those are as follows;

auto break case char const continue default do


double else enum extern float far for goto

if int long register return short signed sizeof

static struct switch typedef union unsigned void while

C - DATA TYPES
--------------------
DatatType, defines what type of data to be store by a variable in the C-program.

A 'datatype' defines type of data to be store/display/read by the variables /


arrays / structures in the c-program.

(1)Basic/Primitive/Built-in data types: These datatypes are availble with C


language/Compiler.

32-bit based
Data type Format specifier Memory size Storage range
------------ --------------- ---------------- -----------------

unsigned char %c 1 byte 0 to 255 [ASCII code]


char %c 1 byte -128 to 127 [ASCII Code]

int %d 2 bytes -32768 to 32767


unsigned int %u 2 bytes 0 to 65535
long int or long %ld 4 bytes -2147483648 to 2147483647
unsigned long %lu 4 bytes 0 to 4294967295

float %f 4 bytes 3.4*(10-38) to 3.4*(10+38)


double or long float %lf 8 bytes 1.7*(10-308) to
1.7*(10+308)
long double %Lf 10 bytes 3.4*(10-4932) to 1.1*(10+4932)

==================================================================================
[ASCII : American Standard code for Information Interchange]

char[ ] or string %s ---- -----


Hexa Decimal base %x
Octal base %o
Memory Address %p or %u

(2)User Defined Data Types:


The user defined data types enable a program to invent or create own data types and
define what values it can taken on.

1. enum (enumerated data type)


2. typedef (type definition)

(3)Derived Data Types:


The derived data types are created from the basic integers, characters and floating
values.
The examples of derived data types are arrays, strings, pointer, structures,
unions, etc.,

IDENTIFIERS
------------------
An identifier is a programmer defined/choice of name given to the program
elements,such name is called as Identifier.
The program elements, such as variables,arrays,
pointers ,functions,structures,unions.

But the programmer must follow all Identifier rules while giving own naming to
variables or arrays or pointers or structures ...... etc.

Identifier Rules:
--------------------
1.It must not be a C- keyword.

2.It does not allows space character.

3.It doesn't allow special characters except underscore( _ ).

4.It starts with either underscore or Alphabet character but not digits.

5.It allow digits as a part of identifier from second character onwards.

6.It has max.of 32 chacters only and minimum one character.

7.Underscore may use to combine two parts of identifier.

ex;
name, Name, NAME, _name, my_name, var1, Int, AK47 => Valid identifiers

12name, my name, @name, int, for , Ak@47 => Invalid identifiers

VARIABLES: [ vary + able ]


=================
It is a storage (computer memory) container, used to store only one value at a
time.
A quantity which may vary during the execution of a program is known as variable.So
the content of variable may change at any point of line in the program.
A variable name is a memory storage location reference name.
Variable naming is completely programmer choice but follows identifier rules.

Declaration of a variable: -
-------------------------------
A variable is declared by basic datatype and name of variable.

syntax:

<basic-datatype> identifier/variable-name;
(or)
<basic-datatype> identifier-1, identifier-2,���identifier-n;

Examples:
int n; 4-Bytes //n only stores an integer value.
char ch; 1-Byte //ch only stores one character value.
float f; 4-Bytes // f only stores one float value.
int a,b,c;

n=100;
ch='M'; //variables assignment by values
f=56.7435;

Initialization of variable: -
-------------------------------
At the time of declaring a variable we can store some data into that variable is
known as variable initialization.

syntax:
<datatype> identifier/variable-name = value;

Examples: - int n=10;


char ch=�s�;
float ft=10.1023;
int a=10,b=20,c=30;
int a=100,b,c=150;

Example: -
int n=100;
1.printf(�%d�,n); output:100
2.printf(�value of n=%d�,n); output: value of n=100

Note:In C language all declarations will be done before the first execution
statment of the program.

Ex1;Example C-program to declare & initialization of variables


#include<stdio.h>
void main()
{
char ch; //variable declaration
int data=100;
float price=345.567; //variable initialization
ch='M'; //variable assignment
/*printf("%d",data);
printf("%c",ch);
printf("%f",price);*/
printf(" %d %c %f",data,ch,price);
}

Ex2;To read and display data values(char,int,float)


#include<stdio.h>
void main()
{
char ch;
int data;
float ft;
/*
printf("Enter a character ");
scanf("%c",&ch);
printf("Enter a number ");
scanf("%d",&data);
printf("Enter a float value ");
scanf("%f",&ft);
*/
printf("Enter char, int float values ");
scanf("%c%d%f",&ch,&data,&ft);
printf(" %c %d %f",ch,data,ft);
}

CONSTANTS
---------------
Constant in 'C' refers to fixed value that doesn�t change during the execution of a
program.
C supports the following constants.

1)Integer constantans ->12, 345, 678, -123, 0, -3467, 3000,.....

2)Real/float Constants --> 1.234, 67.890, 34.123, 0.000123, -67.234, .......

3)Character constants - - > 'B' , 'A' , 'q' , ..... must be enclosed with
in single quotes.

4)String constants ----> "cyber" , "QWERT" , "bza" , "Welcome" .....


enclosed within double quotes.

Constants are mostly used to initialize variables.

C-laguage also provides another two types of constants as follows;

1.Symbolic Constants: -
------------------------------
It is a pre-processor statement in link section and is used to define symbolic
constants.

Syntax: -
<#define> <identifier/Symbol> <value>

Ex:
#define MAX 100
#define PI 3.14

2.Constant variable:
---------------------------
'const' keyword is also used to constant a variable.

ex;
const float g=9.8; // g is constant for entire program.
g=3.24; //It gives error message, read only variable 'g'

C-CHARACTER SET:
============
C- language supports 256 characters and each character is represented by ASCII
(American Standard Code for Information Interchange) code. It ranges from 0 to 255.
It includes following list of characters;
1.Alphabet Upper case & Lower case [A-Z & a-z]
2.Digits (Numbers: 0 to 9 )
3.Special characters ( ! @ # $ % ^ & * ( ) � � ; : > < ? .
spacecharacter ..��.. )
4.Symbols (sigma,pi,gamma,alpha,delta,.....)
5.Some ASCII codes are reserved for future use.

ASCII Code Equivalent Character


-------------- -------------------------
0
1
.
.
32 space character (space bar)
.
.
48 0
49 1
.
.
65 A
66 B
.
.
.
97 a
98 b
.
.
.
.
255

Escape sequence characters:


-------------------------------------
These characters are used within printf(" ") statement to format the output.

\n = new line
\t = Horizontal tab (default 8 spaces)
\v = Vertical tab (default 1 line)
\b = Back space
\r = Carriage return
\a = Alert (Beep sound)

Ex;
#include<stdio.h>
void main()
{
printf("hello\nwelcome\tto\ncomputer\tclasses\a");
}

FORMATTING THE OUTPUT:


----------------------------------
int:
int n=100;
printf(�%d�,n); o/p:100
printf(�\n%5d�,n); o/p:_ _100(spaces before output)
printf(�\n%-5d�,n); o/p:100_ _(spaces after)
int n=5;
printf(�\n%.2d�,n); o/p:05

char:
char ch=�h�;
printf(�\n\n%c�,ch); o/p:h
printf(�\n%4c�,ch); o/p:_ _ _h(before 3 spaces)
printf(�\n%-5c�,ch); o/p:h_ _ _ _(after 4 spaces)

float:
float ft=45.1352;
printf(�\n\n%f�,ft); o/p:45.135200
printf(�\n%12f�,ft); o/p:_ _ _45.135200
printf(�\n%-12f�,ft); o/p:45.135200_ _ _
printf(�\n%.2f�,ft); o/p:45.13
printf(�\n%7.2f�,ft); o/p:_ _45.13

String:
char st[10]=�welcome�;
printf(�\n\n%s�,st); o/p:welcome
printf(�\n%9s�,st); o/p:_ _welcome
printf(�\n%.3s�,st); o/p:wel

NOTE:one underscore(_) equal to one space character.

OPERATORS
==========
"An operator is a symbol or a special character, used to perform an operation"

Unary operator:
This operator requires only one variable to perform an operation.
ex; -- ++ ~ >> << !

Binary operator:
This operator requires two variables to perform an operation.
ex; + - < > == & |

C supports following types of operators ,as follows ;

1.Arithmetic operators
2.Relational operators
3.Logical operators
4.Assignment operator (=)
5.Increment operator (Unary ++ )
6.Decrement operator (Unary --)
7.sizeof() operator
8.comma operator (,)
9.conditional operator (Ternary Operator)
10.Bitwise operators

1.Arithmetic operators:
-------------------------------
-> All arithmetic operators are binary type operators, i.e An arithmetic operator
that requires two values or two variable to perform an operation.
An Arithmetic operator applied on numerical values (integers , float values)

Operator Description
----------- --------------
+ Addition

- Subtraction

* Multiplication

/ Division ==>The output is Quotient

% Modulo Division ==>The output is Remainder

-------------------------------------------------------------------------

Priority(Precedence) of Arithmetic Operators:Mostly it follows 'BODMAS' rule

Priority Operators Associativity


........... ............... ...................
1. ( ) Left to Right
2. of Left to Right
3. / * % Left to Right
4. + - Left to Right
5. = Right to Left

Ex;
k=a+b/c
k=(a+b)/c
k=a*b+c/d+e
k=a*(b+c)/(d+e)

Example Program:
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nSUM =%d",c);
printf("\nSUB =%d",(a-b));
printf("\nMUL =%d",(a*b));
printf("\nDIV =%d",(a/b));
printf("\nMOD =%d",(a%b));
}

practice programs:
---------------------
1.Write a C-program to display area and circumference of a circle by reading Radius
of circle.
area=pi*r*r
circumference=2*pi*r;

#include<stdio.h>
#define PI 3.14
const float K=2.0;
void main()
{
float r,a,c;
printf("Enter radius of circle: ");
scanf("%f",&r);
a=PI*r*r;
c=K*PI*r;
printf("\nArea=%f",a);
printf("\nCircumference=%f",c);
}

2.Write a C-program to display area and perimeter of a rectangle by reading length


& breadth
area=length*breadth
perimeter=2.0*(length+breadth)

#include<stdio.h>
void main()
{
float l,b,a,p;
printf("Enter length & breadth of a rectangle\n");
scanf("%f%f",&l,&b);
a=l*b;
p=2.0*(l+b);
printf("\nArea\t=%.2f",a);
printf("\nPerimeter=%.2f",p);
}

3.Write a C-program,to display Employee Gross & Net salary,by reading Basic salary
of an employee;
consider the following criteria;
Assume,
hra=30% of basic
da=27% of basic
ta=15% of basic
pf=12% of basic
esi=5% of basic

gross salary=basic+hra+da+ta
net salary = gross salary-(pf+esi)

#include<stdio.h>
void main()
{
float basic,hra,da,ta,esi,pf,gross,net;
printf("Enter Basic salary of an employee:");
scanf("%f",&basic);
hra=(30.0/100.0)*basic;
da=(27.0/100.0)*basic;
ta=(15.0/100.0)*basic;
pf=(12.0/100.0)*basic;
esi=(5.0/100.0)*basic;

gross=basic+hra+da+ta;
net=gross-(pf+esi);
printf("\n\nBasic salary\t:%.2f",basic);
printf("\nGross salary\t:%.2f",gross);
printf("\nNet salary\t:%.2f",net);
}

4.Write a program to display Simple Interest & Net amount to repayment,by reading
Principal(P) amount,Rate of Interest(R) in % , Time(T) in years.
SI=(P*R*T)/100.0
Net=P+SI

#include<stdio.h>
void main()
{
float SI,P,R,T,NET;
printf("Enter Principal Amount, Rate of Interest in percentage, and Time in years\
n");
scanf("%f%f%f",&P,&R,&T);
SI=(P*R*T)/100.0;
NET=P+SI;
printf("\nPrincipal Amount :%.2f",P);
printf("\nSimple Interest :%.2f for %.2f years",SI,T);
printf("\nNet Amount to Pay:%.2f",NET);
}

5.Write a program to display % of profit by reading cost price(CP) and selling


price(SP) of a product.

% of profit, K=((SP-CP)/CP)*100.0

6.Write a C-program to display result of the following Arithmetic Expression;

k=(a+b)/(c*b)

2.Relational operators: [Comparision operators]


-------------------------------
These operators are binary type, used to find the relationship [true(1)/false(0)]
between two operands/variables.
A relational operator used to test only one condition at a time.

Operator Description
-------- -----------
< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to


== Equal to

!= Not Equal to

ex;
int a=10, b=45;
(a>b) ---> relational expression , returns false i.e '0'

int a=45,b=10;
(a>b) ---> relational expression , returns true i.e '1'

(a==b) --> False(0)

(a!=b) --> True (1)

Example:
-----------
#include<stdio.h>
void main()
{
int a,b;
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
printf("a=%d\tb=%d\n",a,b);
printf("\n(a>b)\t:%d",(a>b));
printf("\n(a<b)\t:%d",(a<b));
printf("\n(a>=b)\t:%d",(a>=b));
printf("\n(a<=b)\t:%d",(a<=b));
printf("\n(a==b)\t:%d",(a==b));
printf("\n(a!=b)\t:%d",(a!=b));
}

3.Logical operators:
--------------------------
A logical operator is used to test multiple relational expressions or conditions.

Operator Description
----------- ---------------

&& Logical 'AND'

|| Logical 'OR'

! Logical 'NOT'

Note:Logical AND(&&), Logical OR(||) are binary type operators, where Logical
Not(!) is unary operator.
Logical operators, work based on Truth Table;
Truth Table:
A B A&&B A||B !A
--- --- ------- ----- -----
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Ex:
int a=10,b=30,c=5;

(a>b) && (c<a) ==> 0


0 1

(a>b) || (c<a) ==> 1


0 1

(b<a) => 0

!(b<a) => 1
0

Example program:
----------------
#include<stdio.h>
void main()
{
int a=20,b=10,c=5;
printf("\n%d",(a>b && c>b));
printf("\n%d",(a>b || c>b));
printf("\n%d",(a<b));
printf("\n%d",!(a<b));
}

4.Assignment operator: [ = ]
------------------------------
It is nothing but equal to (=) symbol.
It is used to assign or copy rightmost value to leftmost variable.
Its associativity always right to left.
ex;
int a=10;
a=12*34;
c=(a+b)*20;
d=a;
Note : Assignment perator also used to initialize variables.

Ex;C-program to swap given two numbers


#include<stdio.h>
void main()
{
int a=20,b=10,t;
printf("\nBefore Swap A=%d\tB=%d",a,b);
t=a;
a=b;
b=t;
printf("\nAfter Swap A=%d\tB=%d",a,b);
}

5.Increment Operator/Unary ++ operator:


------------------------------------------------------
It increments a variable by 1. It is a combination of two plus symbols (++).
1)Pre-Increment: [++variable]
"Operand/variable follows the operator (++)"

Ex1;
int a=10;
++a; => a=a+1 = 11
Ex2;
int a=10,c;

c=5*++a; First 'a' is incremented,then 'a' is used in expression

Now a=11 , c=55

2)Post-Increment: [variable++]
"Operaor (++) follows the Operand/variable "

Ex1;
int a=10;
a++; =>a=a+1 = 11
Ex2;
int a=10,c;

c=5*a++; First 'a' is used in expression, then 'a' is


incremented

Now c=50 , a=11

Example program: Increment [ ++ ]


----------------
#include<stdio.h>
void main()
{
int a=20,b=10,c;

printf("\na=%d",a); //a=20
++a; //Pre-Increment
printf("\na=%d",a); //a=21
c=10*++a;
printf("\nc=%d a=%d\n",c,a); //c=220 a=22

printf("\nb=%d",b); //b=10
b++; //Post-Increment
printf("\nb=%d",b); //b=11
c=10*b++;
printf("\nc=%d b=%d",c,b); //c=110 b=12
}

6.Decrement Operator/Unary -- operator:


------------------------------------------------------
It decrements a variable by 1. It is the combination of two hyphen symbols (--).

1)Pre-Decrement: [--variable]
"Operand/variable follows the operaor --"

Ex1;
int a=10;
--a; =>a=a-1 = 9
Ex2;
int a=10,c;

c=5*--a; First 'a' is decremented,then 'a' is used in


expression

Now a=9 c=45

2)Post-Decrement: [variable--]
"Operaor --, follows the Operand/variable "

Ex1;
int a=10;
a--; =>a=a-1=9
Ex2;
int a=10,c;

c=5*a--; First 'a' is used in expression, then 'a' is decremented

Now c=50 a=9

Example program: Decrement [ -- ]


------------------------
#include<stdio.h>

void main()
{
int a=20,b=10,c;

printf("\na=%d",a); //a=20
--a; //Pre-Decrement
printf("\na=%d",a); //a=19
c=10*--a;
printf("\nc=%d a=%d\n",c,a); //c=180 a=18

printf("\nb=%d",b); //b=10
b--; //Post-Decrement
printf("\nb=%d",b); //b=9
c=10*b--;
printf("\nc=%d b=%d",c,b); //c=90 b=8
}

7. sizeof( ) operator:
------------------------
It is a compiler operator,and is used to find the allocated memory size of
datatype / variable / array / pointer / structure interms of bytes.

This operator returns a number interms of bytes and It takes one argument, that may
be datatype or variable or array or pointer or structure.

syntax: sizeof(datatype/variable);

1-bit = To store either 1(True) or 0(False)


8-bits = 1 Byte
1024 Bytes = 1 KB (Kilo Bytes)
1024 KB = 1 MB (Mega Bytes)
1024 MB = 1 GB (Giga Bytes)
1024 GB = 1 TB (Tera Bytes)
1024 TB = 1 PB (Peta Bytes)

Example program:

#include<stdio.h>
void main()
{
char ch;
int n;
float ft;
printf("\nchar size\t:%d byte",sizeof(ch));
printf("\nint size\t:%d bytes",sizeof(n));
printf("\nfloat size\t:%d bytes",sizeof(ft));
printf("\ndouble size\t:%d bytes",sizeof(double));
}

8. Comma Operator [,]:


--------------------------
Comma operator is used to seperate relative expressions/ relative variables at
declaration & initialization.

Ex;
int a,b,c,d;

printf("Value of a=%d",a);

scanf("%d%d",&a,&b);

9. Conditional Operator :- (? : ) [ Ternary Operator ]


--------------------------------
It is a combination of two symbols, question mark(?) and colon(:).
This operator is used to test a condition.
It has three expressions,hence it is also called as Ternary Operator.

syntax:

(Test-condition)? true-statement : false-statement;


exp1 exp2 exp3

exp1:It is a testcondition,that may be relational or logical expression,it returns


1(True) or 0(False).
exp2:It is any executable statement.
exp3:It is any executable statement.

Ex1;
int a=10,b=50;

(a>b) ? printf("A is big") : printf("B is big);

Ex2;
int a=10,b=50,c;

c=(a>b) ? a : b;

printf("\n%d is Greatest",c);

Example program://Write a C-program to display greatest of given two numbers by


using ternary operator.
#include<stdio.h>
void main()
{
int a,b;
printf("\nEnter two numbers\n");
scanf("%d%d",&a,&b);
printf("\nA=%d B=%d\n",a,b);
//(a>b)? printf("\nA is Greatest") : printf("\nB is Greatest");
(a==b)?printf("\nBoth A & B are Equal"):(a>b)?printf("\nA is greatest"):printf("\nB
is greatest");
}

10. Bitwise Operators:


----------------------
These operators are used to perform an operation at bit level (binary/machine
level).
These operators are mostly used in Electronics Embbeded applications.

Operator Description
------------ -----------------
& Bitwise 'AND'

| Bitwise 'OR'

^ Bitwise Exclusive OR

~ Bitwise complement

<< Bitwise Left shift

>> Bitwise Right shift

------------------------------------------------------------------------------

Decimal Binary (4-bit)


---------- --------------
0 0 0 0 0
1 0 0 0 1
2 0 0 1 0
3 0 0 1 1

4 0 1 0 0
5 0 1 0 1
6 0 1 1 0
7 0 1 1 1
----------------------------------------
Ex;
int a=3,b=6;

a=3 => 0 0 1 1
b=6 => 0 1 1 0
------------------------
a&b => 0 0 1 0 =>2

a|b => 0 1 1 1 =>7

a^b => 0 1 0 1 =>5

a=3 => 0 0 1 1
~a => 1 1 0 0 => -ve value

a=3 => 0 0 1 1
a<<1=> 0 1 1 0 =>6

b=6 => 0 1 1 0
b>>1=> 0 0 1 1 =>3

Example program:
-------------------
#include<stdio.h>
void main()
{
int a,b;
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
printf("\na=%d\tb=%d\n",a,b);
printf("\na&b\t:%d",(a&b));
printf("\na|b\t:%d",(a|b));
printf("\na^b\t:%d",(a^b));
printf("\n~a\t:%d",(~a));
printf("\na<<1\t:%d",(a<<1));
printf("\nb>>1\t:%d",(b>>1));
}

-----------------------------------------------------------------------------------
----------------------------------

CONTROL STATEMENTS
====================
[Control Structures]
These statements are used to achieve a Non-Sequential flow of execution of a
program.
These are used to implement complexed solutions and used as building blocks.
These are categorized into following three ;

1.Conditional/Decision making Control Statements


[if, if-else, else-if, nested-if, switch]

2.Loop/Iterative/Repetitive Control Statements


[ for, while, do-while ]

3.Un-conditional Control Statements


[ break, continue, goto ]
---------------------------------------------------------------------------
'if' statement OR simple 'if' :
=======================
'if' is a C-keyword.
It has a Testcondition and 'if' block.
The if block that i.e represented by pair of curly braces { } and it contains one
or more executable statements.
The testcondition is may be relational or logical expression,that returns either
true(1) or false(0).
Whenever testcondition is true, the if block will be executed,otherwise not
executed.

syntax;
.....................
....................
................
if(TestCondition)
{
........
...... //statements to be executed
.......... //'if' block
........
}
..................
..................
.................

Ex;//'if' statement example program


#include<stdio.h>
void main()
{
int n=10;
if(n>0)
{
printf("Given number > 0");
}
printf("\n\nReached End of the program");
}

'if-else': [Two-way conditional statement]


======
'else' is a C-keyword.
There is an 'else' block, that follows 'if' block.
Whenever 'if' testcondition is false, then else block will be executed.
Both 'if' block and 'else' block together never executed.
'if' block alone can used in the program, but 'else' block can't be used.
'if-else' statement is used to test only one condition at a time.
Syntax;
---------------
---------
--------------
if(TestCondition)
{
........
...... //statements to be executed
.......... //'if' block [True block]
........
}
else
{
........
...... //statements to be executed
.......... //'else' block [False block]
........
}
..........................
...................
....................

//Ex1;To check the given number is EVEN or ODD


#include<stdio.h>
void main()
{
int n,i;
printf("\nEnter a number:");
scanf("%d",&n);
i=n%2;
if(i == 0)
{
printf("\nGiven number is EVEN");
}
else
{
printf("\nGiven number is ODD");
}
}

//Ex2;To check given number is +ve or -ve number


#include<stdio.h>
void main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>0)
{
printf("+Ve number is given");
}
else
{
printf("-Ve number is given");
}
}

//Ex3;To check Major & Minor status of given age of a person


#include<stdio.h>
void main()
{
int age;
printf("Enter your Age ");
scanf("%d",&age);
if(age>=18)
{
printf("You are Major");
}
else
{
printf("You are Minor");
}
}

//Ex4;To display greatest of given two disimilar numbers


#include<stdio.h>
void main()
{
int a,b;
printf("Enter two disimilar numbers\n");
scanf("%d%d",&a,&b);
printf("\nA=%d\tB=%d",a,b);
if(a>b)
{
printf("\nA is greatest");
}
else
{
printf("\nB is greatest");
}
}

Ex5; To display student result by reading each subject marks, each subject ,max.
100, cut-off 35.
#include<stdio.h>
void main()
{
int m,p,c,t;
printf("Enter 3 subject marks\n");
scanf("%d%d%d",&m,&p,&c);
if(m>=35 && p>=35 && c>=35)
{
printf("\nResult: PASS");
t=m+p+c;
printf("\nGain marks:%d out of 300",t);
}
else
{
printf("\nResult:FAIL");
}
}

Ex6;To check given character is Upper case OR Lower case character.


#include<stdio.h>
void main()
{
char ch;
printf("Enter An Alphabet character [A-Z or a-z]:");
scanf("%c",&ch);
if(ch>=65 && ch<=90)
{
printf("\nGiven Alphabet Character is Upper Case");
}
else
{
printf("\nGiven Alphabet Character is Lower Case");
}
}

Ex7;To check given character is VOWEL or CONSONANT


#include<stdio.h>
void main()
{
char ch;
printf("Enter An Alphabet character in Lower Case:");
scanf("%c",&ch);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
{
printf("\nGiven character is VOWEL");
}
else
{
printf("\nGiven character is CONSONANT");
}
}

'else-if' statement OR 'if-else-if' ladder: [Multi-way conditional statement]


--------------------------------------------------
It is used to test multiple conditions.
Every 'if' block that has 'else' block, i.e every test condition,has a block of
statements.
Which testcondition is true, that block of statements only to be executed.
If No one condition is true, then finally 'else' block of statements will be
executed.

syntax;

if(testcondition-1)
{
....
....
}
else if(testcondition-2)
{
....
....
}
else if(testcondition-3)09
{
....
....
}
.
.
.
.
else if(testcondition-N)
{
....
....
}
else
{
....
....
}

Ex1;To display week day for given week day value(1 to 7)


#include<stdio.h>
void main()
{
int w;
printf("Enter a week day value ");
scanf("%d",&w);
if(w==1)
{
printf("Sunday");
}
else if(w==2)
{
printf("Monday");
}
else if(w==3)
{
printf("Tuesday");
}
else if(w==4)
{
printf("Wednesday");
}
else if(w==5)
{
printf("Thursday");
}
else if(w==6)
{
printf("Friday");
}
else if(w==7)
{
printf("Saturday");
}
else
{
printf("Invalid week day value");
}
}

Ex2;To display season for given month value


#include<stdio.h>
void main()
{
int m;
printf("Enter a month value (1 to 12):");
scanf("%d",&m);
if(m>=3 && m<=6)
{
printf("Summer Season");
}
else if(m>=7 && m<=10)
{
printf("Rainy Season");
}
else if(m==1 || m==2 || m==11 || m==12)
{
printf("Winter Season");
}
else
{
printf("Invalid month value");
}
}

Ex3:To display age group of a person by rading age value;


#include<stdio.h>
void main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age<0)
{
printf("Invalid Age value");
}
else if(age>=0 && age<=5)
{
printf("Baby age group");
}
else if(age>=6 && age<=12)
{
printf("Child age group");
}
else if(age>=13 && age<=19)
{
printf("Teenage group");
}
else if(age>=20 && age<=40)
{
printf("Young age group");
}
else if(age>=41 && age<=60)
{
printf("Adult age group");
}
else
{
printf("Old age group");
}
}

Ex4; To perform and display specific arithmetic operation using 'else-if' statement
#include<stdio.h>
#include<process.h>
void main()
{
int ch,a,b;
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit");
printf("\n\nEnter your choice: ");
scanf("%d",&ch);
if(ch>=1 && ch<=4)
{
printf("\n\nEnter two numbers\n");
scanf("%d%d",&a,&b);
}
if(ch==1)
{
printf("\nsum=%d",a+b);
}
else if(ch==2)
{
printf("\nsub=%d",a-b);
}
else if(ch==3)
{
printf("\nmul=%d",a*b);
}
else if(ch==4)
{
printf("\ndiv=%d",a/b);
}
else if(ch==5)
{
exit(0);
}
else
{
printf("Invalid choice!");
}
}

Ex5; To display greatest of given two numbers


#include<stdio.h>
void main()
{
int a,b;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
printf("\nA=%d\tB=%d",a,b);
if(a==b)
{
printf("\nNo one is greatest, Both are equal");
}
else if(a>b)
{
printf("\nA is greatest");
}
else
{
printf("\nB is greatest");
}
}
Ex6; To display greatest of given three numbers, by using 'else if' ladder
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
printf("\nA=%d\tB=%d\tC=%d",a,b,c);
if(a==b && b==c)
{
printf("\nNo one is greatest, All are equal");
}
else if(a>b && a>c)
{
printf("\nA is greatest");
}
else if(b>a && b>c)
{
printf("\nB is greatest");
}
else if(c>a && c>b)
{
printf("\nC is greatest");
}
else if(a==b && b>c)
{
printf("\nBoth A & B are greatest");
}
else if(c==b && b>a)
{
printf("\nBoth C & B are greatest");
}
else if(a==c && c>b)
{
printf("\nBoth A & C are greatest");
}
}

Ex7: To display student Grade by reading marks, out of 100 [0 to 100]


#include<stdio.h>
#include<process.h> //OR #include<stdlib.h>
void main()
{
int m;
printf("Enter marks of the student,out of 100: ");
scanf("%d",&m);

if(m<0 || m>100)
{
printf("Invalid marks");
exit(0);
}
else if(m>90)
{
printf("\nA Grade");
}
else if(m>75 && m<=90)
{
printf("\nB Grade");
}
else if(m>60 && m<=75)
{
printf("\nC Grade");
}
else if(m>50 && m<=60)
{
printf("\nD Grade");
}
else if(m>=40 && m<=50)
{
printf("\nE Grade");
}
else
{
printf("\nF Grade");
}
}

Ex8; To display Net bill amount after discount on purchase


Bill Discount
--------- ------------
<=3000 No discount
3001 to 10000 10% of bill
10001 to 20000 20% of bill
20001 to 30000 30% of bill
30001 to 40000 40% of bill
Above 40000 50% of bill

#include<stdio.h>
void main()
{
float bill,discount,net;
printf("Enter total bill:");
scanf("%f",&bill);
if(bill<=3000.0)
{
discount=0.0;
}
else if(bill>3000.0 && bill<=10000.0)
{
discount=(10.0/100.0)*bill;
}
else if(bill>10000.0 && bill<=20000.0)
{
discount=(20.0/100.0)*bill;
}
else if(bill>20000.0 && bill<=30000.0)
{
discount=(30.0/100.0)*bill;
}
else if(bill>30000.0 && bill<=40000.0)
{
discount=(40.0/100.0)*bill;
}
else{
discount=(50.0/100.0)*bill;
}
net=bill-discount;
printf("\nBill Amount\t:%.2f",bill);
printf("\nDiscount\t:%.2f",discount);
printf("\nNet Bill to Pay\t:%.2f",net);
}

'Nested if' statement:


=================
A 'if' stmt/block defined/write within another 'if' block, is reffered as Nested
if.

systax1:
if(Test-condition) //Outer 'if' block
{
if(Test-condition) //Inner 'if' block
{
-----
----
}

syntax2:

if(Test-condition)
{
......................
...................
if(Test-condition)
{
-----
----
}
else
{
----
----
}
..................
................
..............
}
else
{
if(Test-condition)
{
-----
----
}
else
{
----
----
}

}
syntax3:

if(Test-condition)
{
if(Test-condition)
{
if(Test-condition)
{
-----
----
}
}
else if((Test-condition)
{
----
----
}
else
{

else
{
if(Test-condition)
{
-----
----
}
else if((Test-condition)
{
----
----
}
else
{

syntax4:

if(Test-condition)
{
if(Test-condition)
{
if(Test-condition)
{
-----
----
}
}
else if(Test-condition)
{
if(Test-condition)
{
-----
----
}
else
{
----
----
}
}
else
{
----
----
}

else
{
if(Test-condition)
{
-----
----
}
else if(Test-condition)
{
----
----
}
else
{
----
----
}

Ex1;To display greatest of given three disimilar numbers


#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter three disimilar numbers\n");
scanf("%d%d%d",&a,&b,&c);
printf("\nA=%d\tB=%d\tC=%d",a,b,c);

if(a==b && b==c)


{
printf("\nNo one is greatest, All are equal");
}
else if(a>b)
{
if(a>c)
{
printf("\nA is greatest");
}
else
{
printf("\nC is greatest");
}
}
else
{
if(b>c)
{
printf("\nB is greatest");
}
else
{
printf("\nC is greatest");
}
}
}

Ex2;To check the given year is leap year or not a leap year

Centuary Years:
100,200,300, ,........ 1100, .....1900, 2000, 2100,2200,.....3000,......
If a centuary year is divisible by both 4 and 400, then that year is called as Leap
Year.

Non-Centuary Years:
1-99,101-199,201-299,301-399,.....
If a non-centuary year is divisible by 4 only, then that year is called as Leap
Year.

#include<stdio.h>
void main()
{
int y;
printf("Enter a year value: ");
scanf("%d",&y);

if(y%4==0)
{
if(y%100==0)
{
if(y%400==0)
{
printf("\nIt is a Leap Year");
}
else
{
printf("\nIt is not a Leap Year");
}
}
else
{
printf("\nIt is a Leap Year");
}
}
else
{
printf("\nIt is not a Leap Year");
}
}

Ex3:To display student result and grade


#include<stdio.h>
void main()
{
int m,p,c,sum;
printf("Enter maths,physics & chemistry marks[Each max.100]\n");
scanf("%d%d%d",&m,&p,&c);

if(m>=35 && p>=35 && c>=35)


{
printf("\nResult:PASS");
sum=m+p+c;
printf("\nTotal marks:%d",sum);
if(sum>250)
{
printf("\nGrade: A");
}
else if(sum>200 && sum<=250)
{
printf("\nGrade: B");
}
else if(sum>150 && sum<=200)
{
printf("\nGrade: C");
}
else
{
printf("\nGrade: D");
}
}
else
{
printf("\nResult:FAIL");
}
}

'switch' statment: [Multi-way statement]


---------------------
'switch' is a keyword.

It has an 'argument/expression' and a switch 'block',the block that contains 'N'


no.of case blocks.

A case-block is defined by 'case' keyword & identified by case-value.

Each case block contains one or more executable stmts and is terminated by 'break'
keyword.

Which case-value matches with switch argument, that case block only will be
executed.

If No case-value matches with switch 'argument',then default case block will be


executed.

Default case block is optinal, not mandatory.

Note:switch argument datatype[char/int] and case-value datatype must be same.

syntax:
----------
switch(Argument/Expression)
{
case case-value1:
-----
-----
break;
case case-value2:
-----
-----
break;
case case-value3:
-----
-----
break;
.
.
case case-valueN:
-----
-----
break;
default:
------
------
}

Ex1; switch example program


#include<stdio.h>
void main()
{
int n;
printf("Enter a number ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
default:
printf("Invalid");
}
}

Ex2;To display a specific arithmetic operation, select from MENU of arithmetic


operation
#include<stdio.h>
#include<process.h>
void main()
{
int ch,a,b;
printf("MENU\n--------------");
printf("\n1.Addition\n2.Subtraction");
printf("\n3.Multiplication\n4.Division\n5.Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
if(ch>=1 && ch<=4)
{
printf("\nEnter two numbers\n");
scanf("%d%d",&a,&b);
}
switch(ch)
{
case 1:
printf("SUM=%d",(a+b));
break;
case 2:
printf("SUB=%d",(a-b));
break;
case 3:
printf("MUL=%d",(a*b));
break;
case 4:
printf("DIV=%d",(a/b));
break;
case 5:
exit(0);

default:
printf("Invalid choice");
}
}

Ex3; To display color code and case merging


#include<stdio.h>
void main()
{
char ch;
printf("\nEnter color code[r/g/b]: ");
scanf("%c",&ch);
switch(ch)
{
case 'R':
case 'r':
printf("RED");
break;

case 'G':
case 'g':
printf("GREEN");
break;

case 'B':
case 'b':
printf("BLUE");
break;

default:
printf("Invalid choice");
}
}

Ex4;To check the given character is Vowel or Consonant


#include<stdio.h>
void main()
{
char ch;
printf("\nEnter any Alphabet Character[A-Z or a-z]: ");
scanf("%c",&ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("\nGiven Character is VOWEL");
break;
default:
printf("\nGiven Character is CONSONANT");
}
}

Nested 'switch':
-----------------
Writing/Defining a switch block within case block of outer switch block.
It is mostly used to display sub menu of items.

Ex;To check given number is EVEN or ODD using nested switch


#include<stdio.h>
void main()
{
int n,rem;
printf("Enter a number: ");
scanf("%d",&n);

switch(n)
{
case 0:
printf("\nGiven number is zero");
break;
case 1:
printf("\nGiven number is ODD");
break;

default:
rem=n%2;

switch(rem)
{
case 0:
printf("\nGiven number is EVEN");
break;
default:
printf("\nGiven number is ODD");
}
}
}

LOOP CONTROL STATEMENTS: [for, while, do-while]


----------------------------------------
These are used to execute block of statements repeatedly until certain number of
times to achieve/perform a specific task.

'for' Loop Statement:


=================
'for' is a C-keyword, and it is a loop/iterative statement.
It is used to execute block of statements repeatedly until the given condition is
FALSE.
It is also called as Entry-Controlled OR Counter-Controlled Loop.

It has three expressions as follows;


1.Initialization - Used to initialize variables/counter variables
2.Test-Condition - It may be Relational/Logical Expression that returns
True(1)/False(0)
3.Updation - It is used to INC/DEC counter variable

Each expression is seperated by semicolon (;)

'for' statement has block represented by pair of curly braces { }, that contains
one or more executable statements.

Working:
First controller of an execution enter into 'initialization', then goto 'test-
condition', if it is true then for block will be executed, then goto 'updation',
then again goto 'test-condition' if it is true again, for block will be executed,
repeats this until test-condition is true, once test-condition is false, then
immediately controller of an execution skip the execution of 'for' block and
continue statement after for block.
Syntax;
.........
...........
........
for(initialization; Test-Condition; Updation)
{
.............
.............
............. //Executable statements (for block)
............
............
............
}
................................
...........................
............................

Ex1;To display first 'N' natural numbers & their summation


#include<stdio.h>
void main()
{
int n,i,sum=0;
printf("Enter a number ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("%d%c",i,32);
sum=sum+i;
}
printf("\nsum=%d",sum);
}

Ex2;To display table format for given table number


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

Ex3;To display factorials of a number, Ex; 5!=1*2*3*4*5=120


#include<stdio.h>
void main()
{
int n,i,fact=1;
printf("Enter a number ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("\nFactorials=%d",fact);
}

Ex4;To display all factors of given number, Ex; 12 => 1,2,3,4,6,12


#include<stdio.h>
void main()
{
int n,i,count=0;
printf("Enter a number ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
printf("%d%c",i,32);
count++;
}
}
printf("\n\nTotal factors:%d\n",count);
}

Ex5; To check given number is prime or not prime.


#include<stdio.h>
void main()
{
int n,i,count=0;
printf("Enter a number ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count=count+1;
}
}
if(count==2)
{
printf("\nGiven number is PRIME");
}
else
{
printf("\nGiven number is not PRIME");
}
}

Ex6; To display fibonacci series;


It starts with initial two terms, they are by default 0 & 1, the next term is
generated by sum of it's previous two terms.
Ex;

0 1 1 2 3 5 8 13 21 .....

t1 t2 t3
t1 t2 t3
t1 t2 t3

#include<stdio.h>
void main()
{
int i,n,t1,t2,t3;
printf("Enter Total no.of terms in Fibonacci series: ");
scanf("%d",&n);
t1=0;
t2=1;
printf("\nFibonacci series:\n\n");
printf("%d%c%d%c",t1,32,t2,32);
for(i=3;i<=n;i++)
{
t3=t1+t2;
printf("%d%c",t3,32);
t1=t2;
t2=t3;
}
}

Ex7;To display all ASCII codes and their equivalent Characters.


#include<stdio.h>
void main()
{
int i;
for(i=0;i<=255;i++)
{
printf("\n%d\t:%c",i,i);
}

'Nested for' statement:


===================
A 'for' statement/block is defined/write in another 'for' block is reffered as
'Nested for'.
It is mostly used to represent ROWs & COLUMNs.
Outer 'for, represents Rows & Inner 'for', represents Columns.
syntax;

for(init;Test;Updation) //outer 'for' [Rows]


{
.......
.......
for(init;Test;updation) //inner 'for' [columns]
{
.............
............. //statements
............
}
.......
.......
}

Ex1;display following pattern

1 2 3 4 5
1 * * * * *
2 * * * * *
i 3 * * * * *
4 * * * * *
5 * * * * *

#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Explanation
i=1 =>j=1, j=2, j=3, j=4, j=5
i=2 =>j=1, j=2, j=3, j=4, j=5
i=3 =>j=1, j=2, j=3, j=4, j=5
i=4 =>j=1, j=2, j=3, j=4, j=5
i=5 =>j=1, j=2, j=3, j=4, j=5

Ex2;display following pattern


j

1 2 3 4 5
1 *
2 * *
i 3 * * *
4 * * * *
5 * * * * *

#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Ex3;display following pattern


j

1 2 3 4 5
5 * * * * *
4 * * * *
i 3 * * *
2 * *
1 *
#include<stdio.h>
void main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Ex4;display following pattern

1 2 3 4 5
1 *
2 * *
i 3 * * *
4 * * * *
5 * * * * *

#include<stdio.h>
void main()
{
int i,j,n;
printf("\nEnter no.of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf("%c%c",32,32);
}
for(j=1;j<=i;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Ex5;display following pattern


j

1 2 3 4 5
1 * * * * *
2 * * * *
i 3 * * *
4 * *
5 *
#include<stdio.h>
void main()
{
int i,j,n;
printf("\nEnter no.of rows: ");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=1;j<=n-i;j++)
{
printf("%c%c",32,32);
}
for(j=1;j<=i;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Ex6;To display a Pyromid.


#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=5;++i)
{
for(j=1;j<=5-i;++j)
{
printf("%c%c",32,32);
}
for(j=1;j<=i;j++)
{
printf("*%c",32);
}
for(j=1;j<=i-1;j++)
{
printf("*%c",32);
}
printf("\n");
}
}

Ex7;To display all prime numbers upto given number


#include<stdio.h>
void main()
{
int i,j,n,cnt,count=0;
printf("Enter a number: ");
scanf("%d",&n);
printf("\nAll Prime numbers upto %d\n\n",n);
for(i=1;i<=n;i++)
{
cnt=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2){
printf("%d%c",i,32);
count++;
}
}
printf("\n\nTotal prime numbers: %d\n",count);
}

'while' Loop: [Entry-Controlled Loop]


========
'while' is a C-keyword.
It is also used to execute block of statements until given condition is FALSE.
It has a Test-Condition, that return True/False, and a block of statements.
It is recommended whenever we don't know exact fixed no.of repetitions.
syntax;
..........
...............
.........

while(Test-Condition) //Test-condition is Relational/Logical Expression


{
--------
-------
--------- statements to be executed;
------- It is 'while' block
}
.............
...............

Ex1;To display first 'N' natural numbers & their summation


#include<stdio.h>
void main()
{
int i=1,n,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
printf("\nNatural numbers:\n");
while(i<=n)
{
printf("%d%c",i,32);
sum+=i; // (OR) sum=sum+i;
i=i+1;
}
printf("\nsum of natural numbers: %d",sum);
}

Ex2;To display factorials of given number, 5! =1*5*4*3*2*1 = 120


#include<stdio.h>
void main()
{
unsigned long n,fact=1;
printf("Enter a number: ");
scanf("%lu",&n);
while(n>0)
{
fact=fact*n--;
}
printf("\nFactorials of given number: %lu",fact);
}

Ex3; To display fibonacci series

Fibonacci Series: Sequence of numbers with defined pattern.


--------------------
It is started with initial two terms(by default first term is 0 and second term is
1 ), next term is generated by sum of it's previous two terms.
ex;
0 1 1 2 3 5 8 .. ..
t1 t2 t3
t1 t2 t3

#include<stdio.h>
void main()
{
int n,t1,t2,t3,i;
printf("Enter no.of terms in Fibonacci series: ");
scanf("%d",&n);
t1=0;
t2=1;
printf("\nFibonacci Series:\n\n");
printf("%d%c%d%c",t1,32,t2,32);
i=3;
while(i<=n) //for(i=3;i<=n;i++)
{
t3=t1+t2;
printf("%d%c",t3,32);
t1=t2;
t2=t3;
i++;
}
}

Ex4; To display sum of digits of a given number, 123 => 3+2+1 = 6


#include<stdio.h>
void main()
{
int n,rem=0,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("\nsum of digits of given number: %d",sum);
}

Explanation;
n=123
sum=0
(123>0) => rem=3
sum=0+3=3
n=12

n=12
sum=3
(12>0) => rem=2
sum=3+2=5
n=1

n=1
sum=5
(1>0) => rem=1
sum=5+1=6
n=0

n=0
sum=6
(0>0) => False(0)

Ex5; To display Reverse of a given number, 123 => 321

#include<stdio.h>
void main()
{
int n,r=0,rev=0;
printf("Enter a number: ");
scanf("%d",&n);
while(n>0)
{
r=n%10;
rev=(rev*10)+r;
n=n/10;
}
printf("\nReverse of given number: %d",rev);
}

Ex6; To check given 3-digit number is an armstrong number or not

3-Digit ArmStrong number:


======================
"sum of cubes of digits of given 3-digit number is equal to same as given 3-digit
number"

Ex1;
123 => (1*1*1)+(2*2*2)+(3*3*3) = 1+8+27 =36
So, 123 != 36 , hence 123 is not an armstrong number

Ex2;
153 =>(1*1*1)+(5*5*5)+(3*3*3) = 1+125+27 =153
So, 153 = 153 , hence 153 is an armstrong number

#include<stdio.h>
void main()
{
int n,t,sum=0,rem=0;
printf("Enter a 3-digit number[100 to 999]: ");
scanf("%d",&n);
t=n;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(t==sum){
printf("\nGiven number is an Armstrong number");
}
else{
printf("\nGiven number is not an Armstrong number");
}
}

Nested 'while'
-----------
Define/write a 'while' block within another 'while' block.
It is mostly used to represent ROWs and COLUMNs.
syntax;
while(Testcondition) //outer while block[ROWs]
{

while(Testcondition) //inner while block [COLUMNs]


{
........
........
}

Ex1;To display following patten

1 2 3 4 5
1 * * * * *
2 * * * * *
i 3 * * * * *
4 * * * * *
5 * * * * *

#include<stdio.h>
void main()
{
int i,j;
i=1;
while(i<=5)
{
j=1;
while(j<=5)
{
printf("*%c",32);
j++;
}
printf("\n");
i++;
}
}

Ex2; To display following pattern


j

1 2 3 4 5
1 $ * * * *
2 * $ * * *
i 3 * * $ * *
4 * * * $ *
5 * * * * $

#include<stdio.h>
void main()
{
int i,j;
i=1;
while(i<=5)
{
j=1;
while(j<=5)
{
if(i==j){
printf("$%c",32);
}
else{
printf("*%c",32);
}
j++;
}
printf("\n");
i++;
}
}

Ex3; To display following pattern

1 2 3 4 5
1 $ * * * $
2 * $ * $ *
i 3 * * $ * *
4 * $ * $ *
5 $ * * * $

#include<stdio.h>
void main()
{
int i,j;
i=1;
while(i<=5)
{
j=1;
while(j<=5)
{
if(i==j || i+j==6){
printf("$%c",32);
}
else{
printf("*%c",32);
}
j++;
}
printf("\n");
i++;
}
}

Ex4;To display all 3-digit Armstrong numbers from 100 to 999


#include<stdio.h>
void main()
{
int i,n,rem,sum;
i=100;
while(i<=999)
{
n=i;
rem=0;
sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(i==sum)
{
printf("%d%c",i,32);
}
++i;
}
}

'do-while' Loop: [Exit-Controlled Loop]


--------------
It is also used to execute block of statements repetedly until the given condition
is FALSE.Apart this, 'do-while' guarantees one time execution of 'do' block,even
test condition is FALSE at first teration / repetetion.
'do' is a keyword.It has a block that contains one or more executable statements.
It is also called as Exit-Controlled Loop.Because the test condition checked at end
of the do-block.

syntax;
do
{
.....
..... Executable statements
.....

}while(Test-Condition);

In this, 'while' statement must terminated by semicolon(;).


Test-Condition is may be relational or logical expression that returns either
true(1) or false(0).

Ex1;
/*'do-while' example program
NOTE: 'do-while' guarantees one time execution of 'do' block, even test condition
is FALSE at first iteration/repetition.
*/
#include<stdio.h>
void main()
{
int n=8;
do
{
n++;
printf("\nn=%d",n);

}while(n>10);
}

Ex2;To display first N natural numbers


#include<stdio.h>
void main()
{
int n,i=0;
printf("Enter a number: ");
scanf("%d",&n);
printf("\nAll Natural numbers:\n");
do
{
i++;
printf("%d%c",i,32);

}while(i<n);
}

Ex3;To perform specific arithmetic operation


#include<stdio.h>
#include<process.h>
void main()
{
int ch,a,b;
do
{
printf("\n------MENU------");
printf("\n[1]. ADDITION ");
printf("\n[2]. SUBTRACTON ");
printf("\n[3]. MULTIPLACTION ");
printf("\n[4]. DIVION ");
printf("\n[5]. EXIT ");
printf("\nEnter your choice: ");
scanf("%d",&ch);

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


printf("\nEnter two numbers\n");
scanf("%d%d",&a,&b);
}
switch(ch)
{
case 1:printf("\n Sum of A and B is %d\n",a+b); break;
case 2:printf("\n Sub of A and B is %d\n",a-b); break;
case 3:printf("\n Mul of A and B is %d\n",a*b); break;
case 4:printf("\n Div of A and B is %d\n",a/b); break;
case 5:exit(0);

default:printf("\nInvalid choice!\n\n");
}

}while(1);
}

Ex4;To display following patten using nested do-while

1 2 3 4 5
1 * * * * *
2 * * * * *
i 3 * * * * *
4 * * * * *
5 * * * * *

#include <stdio.h>
void main()
{
int i,j;
i=1;
do
{
j=1;
do
{
printf("*%c",32);
j++;

}while(j<=5);

printf("\n");
i++;
}while(i<=5);
}

'break':
----------
It is a keyword.
It is used within switch block or any loop block, to break up/ discontinue
execution of block of statements.

Ex;
#include<stdio.h>
void main()
{
int n=1;
while(n<=10)
{
if(n==5)
{
break;
}
printf("%d\n",n);
n++;
}
printf("\n\nReached END of the program");
}

'continue':
-------------
It is a keyword.
It is used within loop blocks only, to continue next repetition/iteration of loop
block, i.e it skips execution of specific/a range of repetitions of loop block.
It carries the controller of an execution to the begining of the loop.

Ex;
#include<stdio.h>
void main()
{
int n=0;
while(n<10)
{
n++;
if(n==5 || n==7 || n==9)
{
continue;
}
printf("%d\n",n);
}
printf("\n\nReached END of the program");
}

'goto':
------
It is also a keyword, and is used to jumping the controller of an execution from
one point of line to another point of line in the program with help of label-name.
The label-name is identifier i.e programmer choice of name.

General form;

main()
{
.......
.......
goto Mypoint;
................
..............
................
Mypoint:
...............
..................
}

Ex;
#include<stdio.h>
void main()
{
int i=1,s=0;
LOOP:
printf("%d%c",i,32);
s=s+i;
i=i+1;
if(i<=100)
{
goto LOOP;
}
else
{
goto STOP;
}
STOP:
printf("\nsum=%d",s);
}

ARRAYS:
=======
An Array is a collection of data items/elements/values and all elements are belongs
to one datatype.
OR
An Array is a collection of homogeneous data items.

All Array elements shares a common name and each element is associated or
represented by an index value that starts with zero (0).
So we can access or update an array element by corresponding index only.

Types of Arrays:
--------------------
There are two types of Arrays, as follows;

1.Single Dimenssional Array [One Dimenssional Array OR 1-D Array]

2.Multi Dimenssional Array [Two Dimenssional Array OR 2-D Array]

1-D ARRAY:
---------------
In this type,each array element is represented by only one index value.
So we can access/update 1-D array element by corresponding index value. The index
is always start from 0(zero).
'for' statement is a convenient way to implement 1-D array.

1-D Array Declaration syntax; sqare brackets [ ], are used to represent an


array.
--------------------------

<datatype> <array-name>[size];

<datatype> :It may be any basic datatype but not 'void'

<array-name> :It is a programmer choice of name, but follows identifier rules.

[size] :It is a number, that represents no.of array elements to be


store.

Ex;

char ch[10]; 1*10 = 10 bytes, 10 characters to be store.

int a[5]; 4*5 = 20 bytes, 5 integers to be store.

float ft[6]; 4*6=24 bytes. 6 float values to be store

Note:We must mention the size of an array at declaraion.

int a[5];

a[0]=50; //Array assignment


a[1]=34;
a[2]=89;
a[3]=12;
a[4]=20;

1-D array Initialization syntax;


------------------------------------
Assign or set array elements at array declaration is reffered as array
initialization.

syntax;
<datatype> <array-name>[size]={val1,val2,....valN};

Ex;
0 1 2 3 4 => indices
int a[5]={10,20,30,40,50};

Highest Index = size - 1


= 5 - 1
= 4

Representation: 0 1 2 3 4 => array indices


[ 10 20 30 40 50 ]

Accessing;
<array-name>[index];

printf("%d",a[0]) =>10
printf("%d",a[1]) =>20
.
.
printf("%d",a[4]) =>50

Update;
a[1]=250;

Ex1;Write a program to declare & initialize 1-D Array

#include<stdio.h>
void main()
{
int a[5]; //1-D array declaration
int b[]={1,3,5,7,9}; //1-D array initialization
a[0]=10;
a[1]=20; //1-D array assigment
a[2]=30;
a[3]=40;
a[4]=50;

printf("\n%d",a[3]); //Accessing array elements


printf("\n%d",b[2]);

printf("\n%d",a[4]);
a[4]=123; //update/modify array element
printf("\n%d",a[4]);
}

Ex2;Write a program to read & display sum of array elemets using 'for' loop
#include<stdio.h>
void main()
{
int a[5],i,sum=0;
printf("Enter 5 integer values\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("\nGiven Array Elments are: ");
for(i=0;i<5;i++)
{
printf("%d%c",a[i],32);
sum=sum+a[i];
}
printf("\nSum of array elements: %d",sum);
}

Ex3:Write a program to display max. & min. values of given array.


#include<stdio.h>
void main()
{
int a[10]={34,20,56,10,78,23,44,20,78,15};
int max,min,i;
printf("Given Array: ");
for(i=0;i<10;i++)
{
printf("%d%c",a[i],32);
}
max=min=a[0];
for(i=0;i<10;i++)
{
if(max<a[i])
{
max=a[i];
}
if(min>a[i])
{
min=a[i];
}
}
printf("\nMaximum Element is %d",max);
printf("\nMinimum Element is %d",min);
}

Ex4:Write a program to sort (Acending) of given array.


#include<stdio.h>
void main()
{
int a[10]={34,20,56,10,78,23,44,12,47,15};
int i,j,t;
printf("Given Array: ");
for(i=0;i<10;i++)
{
printf("%d%c",a[i],32);
}
for(i=0;i<10;i++) //sorting logic (Bubble Sort)
{
for(j=i;j<10;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n\nSorted Given Array: ");
for(i=0;i<10;i++)
{
printf("%d%c",a[i],32);
}
}

Ex5:Write a C program to search a given element in the given 1-D array [Linear
Search]
#include<stdio.h>
void main()
{
int a[10]={34,20,56,10,78,23,44,12,47,15};
int i,key,flag=0;
printf("Given Array: ");
for(i=0;i<10;i++)
{
printf("%d%c",a[i],32);
}
printf("\n\nEnter an Element to be Search:");
scanf("%d",&key);
for(i=0;i<10;i++)
{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag==1)
{
printf("\nGiven Element found at %d position\n",(i+1));
}
else{
printf("\nGiven Element not found\n");
}
}

Ex6://To display Array elements in reverse indexing


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

2-D ARRAY:
---------------
In this type,each array element is represented by two index values.One is Row index
and another one is Column index.
Nested 'for' is used to implement 2-D array.
2-D Array is mostly used to represent Matrix and Matrix operations.

Declaration syntax;

<datatype> <array-name>[ROW-size][COL-size];

<datatype> :It may be any basic datatype but not 'void'

<array-name> :It is programmer choice of name, but follows identifier rules.


[ROW-size] :It is a number, that represents no.of rows.

[COL-size] :It is a number, that represents no.of columns.

Ex;

int a[3][4]; => 3*4=12 elements to be store

a[0][0]=7;
a[0][1]=9;
a[0][2]=3;
a[0][3]=2;

a[1][0]=17;
a[1][1]=19;
a[1][2]=13;
a[1][3]=12;

a[2][0]=70;
a[2][1]=90;
a[2][2]=30;
a[2][3]=20;

Initialization;

syntax;

<datatype> <array-name>[Row-size][Col-size]={val1,val2,....valN};

Ex;

int a[3][3]={10,20,30,40,50,60,70,80,90};

OR

int a[3][3]={ {10,20,30},{40,50,60},{70,80,90} };

Representation;

0 1 2

0 10 20 30
a[0][0] a[0][1] a[0][2]

1 40 50 60

2 70 80 90

We can Access or update, an element by two indices;

a[0][0] => 10 //accessing


a[1][1]=200; //updation

Ex1;To declare,initialize,access,update a 2-D Array


#include<stdio.h>
void main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9}; //initialization of 2-D array
int b[2][3]; //declaration of 2-D array
printf("\n%d",a[0][0]);
printf("\n%d",a[1][0]);
printf("\n%d",a[2][2]);
printf("\n%d",a[1][2]);
a[2][2]=123;
printf("\n%d",a[2][2]);
b[0][0]=10;
b[0][1]=20;
b[0][2]=30;
b[1][0]=40;
b[1][1]=50;
b[1][2]=60;
printf("\n%d",b[1][2]);
}

Ex2;To read and display sum of elements of a matrix


#include<stdio.h>
void main()
{
int r,c,i,j,s=0;
printf("Enter No.of Rows & No.of Columns of a Matrix:\n");
scanf("%d%d",&r,&c);
int a[r][c]; //declaration of 2-D array
printf("Enter %d integer matrix elements:\n",r*c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\nGiven matrix:\n\n");
for(i=0;i<3;++i)
{
for(j=0;j<3;j++)
{
printf("%d%c",a[i][j],32);
s=s+a[i][j];
}
printf("\n\n");
}
printf("\n\nsum=%d\n",s);
}

Ex3;To display Addition of two matrices


#include<stdio.h>
void main()
{
int a[2][2]={1,2,1,2}, b[2][2]={3,1,1,3};
int c[2][2];
int i,j;
printf("\nGiven Matrix-A\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d%c",a[i][j],32);
}
printf("\n\n");
}
printf("\nGiven Matrix-B\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d%c",b[i][j],32);
}
printf("\n\n");
}

for(i=0;i<2;i++) // Matrix Addition logic


{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nResult Matrix-C\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d%c",c[i][j],32);
}
printf("\n\n");
}
}

Ex4;To display Traspose of a given matrix

Matrix-A Transpose of A
0 1 2 0 1

0 1 2 3 <= Transpose => 1 4 0


1 4 5 6 2 5 1
3 6 2

#include<stdio.h>
void main()
{
int a[2][3]={1,2,3,4,5,6};
int t[3][2];
int i,j;
printf("\nGiven Matrix-A\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d%c",a[i][j],32);
}
printf("\n");
}

for(i=0;i<3;i++) // Transpose logic


{
for(j=0;j<2;j++)
{
t[i][j]=a[j][i];
}
}

printf("\nTranspose of given Matrix\n");


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

Matrix Multiplication:
------------------------------

Rule: Total no.of columns in first matrix must equal to Total no.of rows in second
matrix.

Matri-A Matrix-B
0 1 2 c1 0 1 c2
r1 r2
0 1 2 1 0 1 2
1 2 1 2 1 2 1
2 1 1

1*1+2*2+1*1 1*2+2*1+1*1

2*1+1*2+2*1 2*2+1*1+2*1

Matrix-C
6 5
6 7

#include<stdio.h>
void main()
{
int a[2][3]={1,2,1,2,1,2},b[3][2]={1,2,2,1,1,1},c[2][2],i,j,k,sum;
printf("Given Matrix-A:\n");
for(i=0;i<2;++i)
{
for(j=0;j<3;++j)
{
printf("%d%c",a[i][j],32);
}
printf("\n\n");
}

printf("Given Matrix-B:\n");
for(i=0;i<3;++i)
{
for(j=0;j<2;++j)
{
printf("%d%c",b[i][j],32);
}
printf("\n\n");
}

for(i=0;i<2;++i) //Matrices multiplication logic


{
for(j=0;j<2;++j)
{
sum=0;
for(k=0;k<3;++k)
{
sum=sum+(a[i][k]*b[k][j]);
}
c[i][j]=sum;
}
}
printf("\nResult Matrix:\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("%d%c",c[i][j],32);
}
printf("\n\n");
}
}

STRINGS
-----------
A string is a collection of characters.
OR
A string is a group of characters.
OR
A string is a sequence of characters.
OR
A string is an array of characters.

Note1:A String contains two or more characters.


Note2:A string is enclosed by double quotations marks;

Ex;
"hai"
"hello"
"welcome"
"123"
"Ak47"
"hi"
"12.345"

NOTE:
There is NO direct basic datatype of String in C-language to create strings, So we
create strings in C-language by using 'Character Array'.

Character ARRAY:
------------------------
Syntax;
char <ArrayName>[size];

We can create a String by the following two ways;

1.Using character constants [single quotations]

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

Note:'\0' is a NULL character that is used to represent End of the string.

2.Using string constant [Double Quotations]

Ex;
char s2[ ]="welcome";

Note:
We need not place a NULL (\0) character at end of the string, because Compiler
automatically Appends NULL character.

Ex1; Example program to create & display strings


#include<stdio.h>
void main()
{
char s1[]={'H','e','l','l','o','\0'};
char s2[]="welcome";
char s3[20];
printf("\nEnter a string3: ");
//scanf("%s",&s3);
gets(s3);
printf("\nString1 = %s",s1);
printf("\nString2 = %s",s2);
printf("\nString3 = %s\n\n",s3);
puts(s1);
puts(s2);
puts(s3);
}

Ex2;Write a program to display length of a string and also display reversed string
#include<stdio.h>
void main()
{
char str[100];
int i;
printf("Enter a String: ");
gets(str);
for(i=0;str[i]!='\0';i++);
printf("\nThe length of given String:%d characters",i);
printf("\nReversed string :");
for(i=i-1;i>=0;i--)
{
printf("%c",str[i]);
}
}

Ex3;To count Capitals,smalls,digits,spl.characters for given string


#include<stdio.h>
void main()
{
char s[100];
int i,c,sm,d,sp;
c=sm=d=sp=0;
printf("Enter a String:");
gets(s);
printf("\nGiven string:");
for(i=0;s[i]!='\0';i++)
{
printf("%c",s[i]);

if(s[i]>=48 && s[i]<=57)


{
d++;
}
else if(s[i]>=65 && s[i]<=90)
{
c++;
}
else if(s[i]>=97 && s[i]<=122)
{
sm++;
}
else
{
sp++;
}
}
printf("\nTotoal Capitals\t\t:%d",c);
printf("\nTotal small letters\t:%d",sm);
printf("\nToal digits\t\t:%d",d);
printf("\nTotal special characters\t:%d",sp);
}

Ex4;//To modify first & last character

#include<stdio.h>
void main()
{
char s[100];
int i;
printf("Enter a String:");
gets(s);
printf("\nGiven string:");
for(i=0;s[i]!='\0';i++)
{
printf("%c",s[i]);
if(i==0){
s[i]='M';
}
}
s[i-1]='M';
printf("\n\n%s",s);
}

String Library Functions OR Standard Library Functions:


============================================
A <string.h> header file provides many pre-defined string handling functions.
Before using any string library function, we must include <string.h> header file in
the program.

Some important String functions are as follows;

Function name Description


--------------- -------------
1. strlen(str) It retuns a number interms of no.of characters of str

2. strcpy(str1,str2) It copies source string(str2) into destination


string(str1)

3. strrev(str) It returns reversed string and original string also


reversed

4. strlwr(str) It returns a string of small letters of given string

5. strupr(str) It returns a string of capital letters of given string

6 strcat(str1,str2) It combines (concatenation) given two


strings(str1,str2) as a one string

7.strcmp(str1,str2) It compares given two strings with case sesitivity

8.strcmpi(str1,str2) It compares given two strings without case sesitivity

Ex1;

#include<stdio.h>
#include<string.h>
void main()
{
char str1[]="HeLLo";
char str2[]="WelCome";
char str3[10];
int len;
printf("\nString1: %s",str1);
len=strlen(str1);
printf("\nLength of string1:%d",len);
strcpy(str3,str1);
printf("\nString3: %s",str3);
strrev(str3);
printf("\nReverse of String3: %s",str3);
printf("\nString2 LowerCase: %s",strlwr(str2));
printf("\nString2 UpperCase: %s",strupr(str2));
printf("\nConcatenation of str3 & str2: %s",strcat(str3,str2));
}

Ex2;
#include<stdio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
int i;
printf("\nEnter string1: ");
gets(str1);
printf("\nEnter string2: ");
gets(str2);
i=strcmp(str1,str2); //i=strcmpi(str1,str2); it ignores case sensitivity
if(i==0)
{
printf("\nGiven strings are same");
}
else
{
printf("\nGiven strings are not same");
}
}

Ex3;//To check Log-in credentials


#include<stdio.h>
#include<string.h>
void main()
{
char pswd[10]="cyber",upswd[10];
printf("\nEnter Password: ");
gets(upswd);
if(strcmp(pswd,upswd)==0)
{
printf("\nLogin Success\n");
}
else{
printf("\nLogin Fail\n");
}
}

Ex4;
/*To check the given string is palindrome or not

MALAYALAM LIRIL MADAM MOM WOW TENET CIVIC LEVEL

RACECAR RADAR REDEVIDER REFER

*/
#include<string.h>
#include<stdio.h>
void main()
{
char str[100], temp[100];
printf("Enter a string: ");
gets(str);
strcpy(temp,str);
strrev(temp);
printf("\nReversed string: %s\n",temp);
if(strcmpi(str,temp)==0)
{
printf("\nGiven string is a Palindrome");
}
else
{
printf("\nGiven string is not a palindrome");
}
}

C - FUNCTIONS:
==========
A C-function is a self contained block of statements, used to perform a specific
task.
A function my re-use many times by calling it.Hence we can achieve modularity and
code re-usability.

Functions are of two types;


1.Pre-defined OR Built-In OR Standard Library Functions
2.User-defined Functions

Pre-defined Functions: [These are already defined and ready to use]


----------------------------
These are available with C-compiler by a specified header file.We just use a pre-
defined function in the program for required task to be perform.

<stdio.h> printf(), scanf(), getch(), putch(), gets(), puts(),..

<string.h> strlen(), strcmp(),strrev(),.....

<process.h> exit()

<math.h> sqrt(), abs(),......

User-defined Functions:
------------------------------
A programmer(user) may develop own functions to accomplish required
operation(service).
There are three steps to create user defined function.
Following is the syntax to create user-defined function;

1).Function Declaration;

syntax;
<return-datatype> <function-name>(parameters list, ..);

ex;
int sum(int,int);
void msg(void);

2).Function definition or implementation;

syntax;
<return-datatype> <function-name>(parameters list, ..)
{
.................
................ //function block
...............
return (value);
}

<return-datatype> :It may be any datatype (int,char,float double,.... and void),


that represents return data value.
If it is 'void' the function doesn't return any value.

<function-name> :It is programmer choice of name, that follows all identifier


rules.

parameters list :We may declare one or more variables of any datatype, seperated
by comma.

return :It is c-keyword and is used to return a value to the function


caller.

function block :It represents pair of curly braces, that block contains one or
more executable statements.

ex1;
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}

ex2;
void msg( )
{
printf("welcome");
}

3).Function calling

syntax;
<function-name>(Actual arguments);

ex;
int s=sum(10,30);

msg();

Example program:
--------------------
/*The following program describes how a user defined function to be created with
function declaration, function definition and function calling. */

#include<stdio.h>

int sum(int , int); //function declaration

int sum(int a, int b) //function definition or implementation


{ //Here a,b are formal arguments
int c;
c=a+b;
return c;
}

void main() //main() is calling function and sum( ) called function


{
int x=10,y=30;
int s;
s=sum(x,y); //function calling, here x,y are actual arguments
printf("%d",s);
}

Types of user defined functions:


====================
1.Function with arguments and with return value
2.Function with arguments and with NO return value
3.Function with NO arguments and with return value
4.Function with NO arguments and with NO return value

1.Function with arguments and with return value


==============================
Data exchanged between calling function & called function
ex;
#include<stdio.h>
int sum(int, int); //function declaration

int sum(int a, int b) //function definition & a,b are formal arguments
{
int c;
c=a+b;

return c;
}

void main() //main( ) is calling function & sum( ) is called function


{
int x=10, y=50;
int z;
z=sum(x,y); //function calling & x,y are actual arguments
printf("\nSUM=%d",z);
}

2.Function with arguments and with NO return value


=======================================
Data is transfered only from calling function to called function

ex;
#include<stdio.h>
void sum(int, int);

void sum(int a, int b)


{
int c;
c=a+b;
printf("\nSUM=%d",c);
}

void main()
{
int x=10, y=50;
sum(x,y);
}

3.Function with NO arguments and with return value


=================================
Data is transfered only from called function to calling function
ex;
#include<stdio.h>
int sum(void); //function declaration

void main()
{
int z;
z=sum( ); //function calling
printf("\nSUM=%d",z);
}

int sum( ) //function definition


{
int a=10, b=50, c;
c=a+b;
return c;
}

4.Function with NO arguments and with NO return value


========================================
NO Data is transfered between calling function and called function
ex;
#include<stdio.h>

void sum( ) //function definition


{
int x=10, y=50;
int z;
z=x+y;
printf("\nSUM=%d",z);
}

void main()
{
sum( ); //function calling
sum( );
sum( );
}

Ex1;Write a C-function to display factorials of given number using user defined


function

#include<stdio.h>
void fact(void);
void fact()
{
int n,f=1;
printf("\nEnter a number: ");
scanf("%d",&n);
while(n>0){
f=f*n--;
}
printf("\nFactorials:%d\n",f);
}
void main()
{
int i;
for(i=1;i<=5;i++)
{
fact();
}
}

practice programs;
1.Write a C-function to display sum of digits of given number
2.Write a C-function to check given number prime or not
3.Write a C-function to display fibonacci series
4.Write a C-function to check given string is palindrome or not
5.Write a C-funtion to sort given array of elements
6.Write C-funtions to implement a seperate user-defined function for each
arithmetic operation

Recurssive Function:
--------------------------
The process of self calling of a function is called as Recurssion.

A function, which has atleast one statement is a self calling statement, then it is
called as Recurssive Function.

By using Recurssion, we can achieve repetition i.e recurssive function block is


repeatedly executed and it is recommended to implement complexed , mathemetical
solutions.

Recurssive function repetitions (self calling statement)were controlled by a


conditional statements(if,else,else-if).

More memory is consumed while recurssive function execution.

syntax;
void main()
{
......
.....
fun( );
.......
.......
}
fun( ) //Recurssive function
{
.........
fun( ); //sefl calling statement
........
}

Ex1;Write a C-program to display first N natural numbers using Recurssive function

#include<stdio.h>

void disp(int);

void disp(int n)
{
if(n>1)
{
disp(n-1); //self calling
}
printf("%d%c",n,32);
}

void main()
{
int k;
printf("Enter a number: ");
scanf("%d",&k);
disp(k);
}

----------------------------------------------------------------------
Explanation;

n=5

void disp(5)
{
if(5>1)
{
disp(5-1);
}
printf("%d%c",n,32);
}

void disp(4)
{
if(4>1)
{
disp(4-1);
}
printf("%d%c",n,32);
}

void disp(3)
{
if(3>1)
{
disp(3-1);
}
printf("%d%c",n,32);
}

void disp(2)
{
if(2>1)
{
disp(2-1);
}
printf("%d%c",n,32);
}

void disp(1)
{
if(1>1)
{
//disp();
}
printf("%d%c",n,32);
}

O/p: 1 2 3 4 5
----------------------------------------------------------------

Ex2;Write a C- program to display factorials of a given number using Recurssive


function
#include<stdio.h>
int fact(int);
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

void main()
{
int k;
printf("Enter a number: ");
scanf("%d",&k);
printf("\nFactorials:%d",fact(k));
}

-------------------------------------------------
explanation;
n=5;

int fact(5)
{
if(5==0)
return 1;
else
return 5*fact(4);
}

int fact(4)
{
if(4==0)
return 1;
else
return 4*fact(3);
}

int fact(3)
{
if(3==0)
return 1;
else
return 3*fact(2);
}

int fact(2)
{
if(2==0)
return 1;
else
return 2*fact(1);
}

int fact(1)
{
if(1==0)
return 1;
else
return 1*fact(0);
}

int fact(0)
{
if(0==0)
return 1;

}
Pointers in C Language:
==================
A pointer is a special type of variable.
A pointer is used to store memory address of another variable of same datatype.
A variable memory address is identified by reference operator(&) with variable
name.
ex;
int a=10;
'&a' is representation of memory address of varaible 'a'.

Pointers, improves speed of the execution of the program.

Pointers doesn't provide data security.

Pointer Declaration:
-------------------------
It is similar to normal variable declaration,but a pointer is declared by prefixing
the pointer-name with star(*) symbol .
syntax;
<datatype> *<pointername>; //<pointername> is programmer choice of name
that follows all identifier rules.
ex;
char *ch; //character pointer, it stores address of another character
variable.

int *ptr; //integer pointer,it stores address of another integer variable.

float *ft; //float pointer,it stores address of another float variable.

Note:4 bytes or 8 bytes of memory is allocated to any datatype of pointer.

Pointer Initialization:
------------------------
It is good practice,to initialize a pointer with 'NULL' value if No proper value to
initialize a pointer.
ex;
char *ch=NULL;

int a=123;

int *p=&a;

*p => pointing 123 value


'p' contains memory address of 'a'.

printf("%d",*p); => 123


printf("%u",p); => address of 'a'

*p=541; //'a' value 123 is replaced by 541.

ex1;
//pointers example
#include<stdio.h>
void main()
{
int a=10;
int *p=&a;
printf("%d bytes\n",sizeof(p));
printf("\nAddress of a is %u",&a);
printf("\nAddress of p is %u",&p);
printf("\ncontent of p is %u",p);
printf("\na=%d",*p);
*p=255;
printf("\na=%d",a);
}

ex2;//perform all arithmatic operations by pointers


#include<stdio.h>
void main()
{
int a,b;
int *p=&a, *q=&b;
printf("Enter two numbers\n");
scanf("%d%d",p,q);
printf("\n%d",*p+*q);
printf("\n%d",*p-*q);
printf("\n%d",*p*(*q));
printf("\n%d",*p/(*q));
}

ex3;//Access all array elements by a pointer


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

ex4; // pointer array


#include<stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
int *p[5]; //pointer as an array
int i,sum=0;
for(i=0;i<5;i++)
{
p[i]=&a[i];
}
for(i=0;i<5;i++)
{
*p[i]=*p[i]+1;
printf("%d%c",*p[i],32);
sum=sum+*p[i];
}
printf("\n\nSum of array elements:%d",sum);
}

Parameters passing Techniques:


---------------------------------------
Arguments or Parameters are forwarded at the time of function calling or function
definition is called as parameters passing Technique.
There are two types of parameters passing techniques;
1.CALL BY VALUE
2.CALL BY REFERENCE(Addresses of variables)

1.CALL BY VALUE: example swapping of two numbers


-------------------
Calling a function by values/variables as an actual arguments at function calling.
In this, if formal aurguments are changed,that doesn't affect actual arguments.
ex;
#include<stdio.h>
void swap(int m, int n)
{
int t;
t=m;
m=n;
n=t;
}
void main()
{
int a=10,b=30;
printf("\nBefore swap,\ta=%d\tb=%d",a,b);
swap(a,b); //calling swap() function by values/variable
printf("\nAfter swap,\ta=%d\tb=%d",a,b);
}

2.CALL BY REFERENCE: example swapping of two numbers


------------------
Calling a function by addresses of variables as actual arguments at function
calling..
In this, if formal aurguments are changed,that affects actual arguments.
ex;
#include<stdio.h>
void swap(int *m, int *n) //pointers as argument to function
{
int t;
t=*m;
*m=*n;
*n=t;
}
void main()
{
int a=10,b=30;
printf("\nBefore swap,\ta=%d\tb=%d",a,b);
swap(&a,&b); //calling swap() function by references(addresses of variables)
printf("\nAfter swap,\ta=%d\tb=%d",a,b);
}

Double Pointer: [ Pointer to Pointer]


---------------------
It is also used to speedup execution of a program.
It always store address of another pointer of same datatype.

Its declaration as follows; (two star symbols (astriks) prefixed to pointername)


ex;
char **ch;
int **p;
float **ft;

Its Initialization;

int n=10;
int *p=&n;
int **dp=&p;

**dp => 10

EX1;
#include<stdio.h>
void main()
{
int n=10;
int *p=NULL;
int **dp=NULL;
printf("\nsize of single-pointer\t:%d bytes",sizeof(p));
printf("\nsize of double-pointer\t:%d bytes",sizeof(dp));
p=&n;
dp=&p;
printf("\n%d",**dp);
**dp=(**dp)*(**dp);
printf("\n%d",n);
}

Ex2; To perform all arithmetic operations using double pointer


#include<stdio.h>
void main()
{
int a,b,c;
int *p=&a,*q=&b;
int **dpa=&p,**dpb=&q;
printf("Enter two numbers\n");
scanf("%d%d",p,q);

c=**dpa+**dpb;
printf("\nsum=%d",c);

c=**dpa-**dpb;
printf("\nsub=%d",c);

c=**dpa*(**dpb);
printf("\nmul=%d",c);

c=**dpa/(**dpb);
printf("\ndiv=%d",c);
}

STRUCTURES:
==========
It is a collection of data elements of different data types or same data types.
[OR]
It is a collection of hetrogeneous data elements.

It is mostly used to create records of students or employess or products, ..etc.

syntax; structure definition

'struct' keyword is used to define a structure.

struct <structure-name> //<structure-name> is a programmer choice of


name
{
declaration-1; //members of structure
declaration-2;
.
.
.
declaration-N;
};

Note:A structure definition or block must be terminated by semicolon(;).

ex;
struct Student
{
int roll; => 4 bytes
char name[20]; => 20 bytes
float per; => 4 bytes
}; ----------------
28 bytes

Note: All structure members can initialize/access/update by structure variable with


dot(.) operator.

structure variable creation:


------------------------------
syntax;
struct <structure-name> <structure-variable-name>;
//<structure-variable-name> is programmer
choice of name
ex;
struct Student s1,s2,s3,......sn;

Note:
Each structure variable has memory is sum of memory is allocated of each member of
structure.
So,
s1 contains 28 bytes => s1.roll, s1.name, s1.per
s2 contains 28 bytes => s2.roll, s2.name, s2.per
s3 contains 28 bytes => s3.roll, s3.name, s3.per

So each member of a structure has a dedicated memory.

Ex0;
#include<stdio.h>
#include<string.h>
struct Student
{
int roll;
char name[20];
float per;

}s1={21,"mahesh",123.23},s2,s3;

struct Student s4={23,"suresh",675.90},s5,s6;

void main()
{
struct Student s7={12,"ramesh",567.5},s8,s9;
s2.roll=27;
strcpy(s2.name,"Donald");
s2.per=345.890;
printf("\n%d\t%s\t%f",s1.roll,s1.name,s1.per);
printf("\n\n%d\t%s\t%f",s2.roll,s2.name,s2.per);
}

Ex1;
#include<stdio.h>
#include<string.h>
struct emp //structure definition
{
int eno;
char ename[20];
float esal; //eno,ename,esal are members of structure 'emp'

}e1={101,"cyber",123.123},e2;

void main()
{
struct emp e3,e4={104,"hello",1212.123};

printf("\nSize of structure:%d bytes",sizeof(e1));

printf("\nENO=%d",e1.eno); //Accessing structure members


printf("\nENAME=%s",e1.ename);
printf("\nESAL=%f",e1.esal);
e2.eno=102;
strcpy(e2.ename,"cyber");
e2.esal=2312.453;

e1.esal=3452.123; //update member of a structure


printf("\nESAL=%f",e1.esal);
}

ex2;Array of structure example


#include<stdio.h>
struct emp
{
int eno;
char ename[20];
float esal; //eno,ename,esal are members of structure 'emp'

}e[100]; //e[100] is array of structure


void main()
{
int n,i;
printf("\nEnter no.of employees recods to be store:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter emp-%d eno,ename,esal\n",i+1);
scanf("%d%s%f",&e[i].eno,&e[i].ename,&e[i].esal);
}
printf("\n\nENO\tENAME\tESAL");
printf("\n----------------------");
for(i=0;i<n;i++)
{
printf("\n%d\t%s\t%f",e[i].eno,e[i].ename,e[i].esal);

}
}

ex3;structure variable is an argument to the function


#include<stdio.h>
struct student
{
int id;
char name[30];
float m1,m2,m3;
};

float disp(struct student t)


{
float s=0.0;
printf("\nId:%d",t.id);
printf("\nName:%s",t.name);
s=t.m1+t.m2+t.m3;
return s;
}

void main()
{
struct student s={101,"cyber",45.0,78.0,67.0};
float total;
total=disp(s);
printf("\nTotal marks:%.1f",total);
}

ex4;structure variable is returned from the function


#include<stdio.h>
struct student
{
int id;
char name[30];
float m1,m2,m3;
};
struct student read( )
{
struct student s={101,"cyber",45.0,78.0,67.0};
return s;
}
void main()
{
struct student stu;
float t;
stu=read();
t=stu.m1+stu.m2+stu.m3;
printf("\nID=%d",stu.id);
printf("\nNAME=%s",stu.name);
printf("\nTotal marks:%.1f",t);
}

ex5;Pointer to structure (structure variable become as pointer)


#include<stdio.h>
struct emp
{
int eno;
char ename[20];
float esal;

}s={101,"cyber",123.123};

void main()
{
struct emp *p=NULL; //pointer of structure emp
p=&s; //Assigns address of structure to pointer

//members of structure can access by pointer using arrow(->) operator

printf("\nENO\t:%d",p->eno);
printf("\nEName\t:%s",p->ename);
printf("\nESalary\t:%.2f",p->esal);
}

Nested structures [ structure with in structure ]:


----------------------------------------------------------------
Defining a structure definition within another structure block is reffered as
Nested Structure.

Ex1;
struct Student
{
int roll;
char name[20];

struct Add
{
char street[20];
char city[20];
char state[20];
}a;
}s;

Accessing;
s.roll
s.name
s.a.street
s.a.city
s.a.state

Ex2;
struct Add
{
char street[20];
char city[20];
char state[20];
};

struct Student
{
int roll;
char name[20];
struct Add a;
}s;

Accessing;
s.roll
s.name
s.a.street
s.a.city
s.a.state

Ex;
#include<stdio.h>
#include<string.h>
struct Student //outer structure
{
int roll;
char name[20];

struct Add // inner structure


{
char street[20];
char city[20];
char state[20];
}a;

}s={21,"Revanth"};

void main()
{
strcpy(s.a.street,"Prakash Nagar");
strcpy(s.a.city,"Rajahmundry");
strcpy(s.a.state,"Andhra Pradesh");

printf("Roll:%d",s.roll);
printf("\nName:%s",s.name);
printf("\nAddress:\n");
printf("%s\n%s\n%s",s.a.street,s.a.city,s.a.state);
}
UNION:
======
It is similar to Structure, but memory allocation is different.
A 'union' keyword is used to create Union derived datatype.

syntax;
union <union-name>
{
data decaration-1; //union members
data declaration-2;
.
.
data declaration-N;
};

ex;
union emp
{
int eno; => 4 bytes
char ename[20]; =>20 bytes
float esal; => 4 bytes
};

Note1:We can initialize/access/update members of union by union variable.

Note2:
Which member of 'union' has highest memory allocation, that memory is allocated to
'union' or union variable.
So a common memory shared by all union members one by one.
There is No dedicated memory for each member of union.

Union variable creation:


------------------------------
ex;
union emp e1,e2,e3;

e1 => 20 bytes allocated


e2 => 20 bytes allocated
e3 => 20 bytes allocated

e1.eno, e1.ename, e1.esal, all these are shares 20 bytes one by one.

e1.eno=34;
strcpy(e1.ename,"cyber");
e1.esal=123.12;

//union example program


#include<stdio.h>
#include<string.h>
union emp
{
int eno;
char ename[20];
float esal;
};
void main()
{
union emp e1;
printf("union memory, e1=%d bytes",sizeof(e1));
e1.eno=123;
strcpy(e1.ename,"cyber");
e1.esal=123.123;
printf("\nEno =%d",e1.eno);
printf("\nEname =%s",e1.ename);
printf("\nEsal =%f",e1.esal);
}

Structure Vs Union:
==============

STRUCTURE UNION
---------------- ------------
1.It is used to store records. 1.It is used to store records.

2.It has to allocate memory,sum of memory allocated to it's members.


2.It has to allocate memory,which union member has highest
memory allocation.
3.A structure members has a dedicated memory.
3.A union members shares a common memory one by one.

FILES
-------
Definition:-

A FILE is one which enable the user to read , write and store a group of a related
data .
(or)

A FILE is a collection of related data stored in a particular area On the


disk(HDD).

Basic file operations:

1) Naming/creating a file
2) Opening a file
3) Reading data from a file
4) Writing data into file
5) Closing a file

FILE:- It is a predefined structure and is used to declare a file pointer.


Using this pre-defined structure FILE pointer, we can perform all file
operations.

Declaration of file pointer:-

FILE *identifier;

ex:- FILE *fp;

Basic File handing functions: <stdio.h> or <stdlib.h>


-------------------------------------

[1].fopen():- It opens a file stream.It returns file pointer interms of memory


address.

syntax:-
FILE *fopen(const char *filename,const char *mode);

file name:- File that the function to be open in main memory at given mode, and
this function returns memory address where file opened in the memory, interms terms
of file object.

MODE:-

String Description
-------- ---------------
"r" : File opens in reading only, if file not exist, it rturns an error.

"w" : File opens in writing only, If a file by that name already exists, it
will be overwritten,
if file not exist a new file is created & write data.

"a" : Append; File opens for writing at end of file, or create for writing
if the file does not exist.

"r+" : Open an existing file for update (reading and writing)

"w+" : Create a new file for update (reading and writing).If a file by that
name already exists,it will be overwritten.

"a+" : Open for append; open for update at the end of the file, or create if
the file does not exist.

Ex;
FILE *fp;

fp=fopen("one.txt","w");

[2].fclose():- It closes a file stream

syn:- int fclose(FILE *stream);


ex;
fclose(fp);

[3].fcloseall():- It closes all opened file streams.


syn:- int fcloseall(void);
ex;
fcloseall();

[4].feof():-
It is a Macro that tests if end of file has been reached on a stream.
syn:- int feof(FILE *stream);
ex;
feof(fp);

[5].remove():-It is a Macro that removes or delete a file


Declaration: int remove(const char *filename);
ex;
remove(one.txt); //it returns zero(0) on successfull deletion

[6].rename():-It Renames a file


Declaration: int rename(const char *oldname, const char *newname);
ex;
rename(one.txt,two.txt); //it returns zero(0) on successfull renaming

fgetc() & fputc() : These are predefined functions.


[7]. fgetc() is used to read a single character from file (file pointer).
[8]. fputc() is used to write a single character to file (file pointer).

Ex1;// char by char writing into a file in WRITE mode

#include<stdio.h>
void main()
{
FILE *fp=NULL;
char ch;
fp=fopen("one.txt","w");
printf("\nEnter data ...input terminate by * \n");

do{
ch=getchar();
fputc(ch,fp);

}while(ch!='*');
fclose(fp);
}

Ex2//char by char writing into a file in APPEND mode


#include<stdio.h>
void main()
{
FILE *fp=NULL;
char ch;
fp=fopen("one.txt","a");
printf("\nEnter data ...input terminate by * \n");

do{
ch=getche();
fputc(ch,fp);

}while(ch!='*');
fclose(fp);
}

Ex3;//char by char Reading from a File in READ mode


#include <stdio.h>
#include <process.h>
void main()
{
char ch,fname[20];
FILE *fp;
int nc,ns,nd,nw,nsp;
nc=ns=nd=nsp=0;
nw=1;
printf("Enter File Name with dot extension: ");
scanf("%s",&fname);
fp=fopen(fname,"r");

if(fp==NULL)
{
printf("\nFile Not Found! Not exist");
exit(0);
}
do
{
ch=fgetc(fp);
printf("%c",ch);

if( ch>=65 && ch<=90 )


nc++;
else if( ch>=97 && ch<=122)
ns++;
else if( ch>=48 && ch<=57 )
nd++;
else if( ch==32 )
nw++;
else
nsp++;

}while(ch!=EOF); //End Of File

printf("\n Number of Capitals\t:%d",nc);


printf("\n Number of Smalls\t:%d",ns);
printf("\n Number of Digits\t:%d",nd);
printf("\n Number of Words\t:%d",nw);
printf("\n Number of Specials\t:%d",nsp);

fclose(fp);
}

Ex4;//Renaming existing file name


#include<stdio.h>
void main()
{
char old_fname[20],new_fname[20];
printf("Enter Old File Name ");
scanf("%s",&old_fname);
printf("Enter New File Name ");
scanf("%s",&new_fname);
if(rename(old_fname,new_fname)==0)
{
printf("\nFile Renamed success");
}
else
{
printf("\nFile Not Found ");
}
}

Ex5;// File Deletion


#include <stdio.h>
void main()
{
char fname[20];
printf("Enter File Name ");
scanf("%s",&fname);
if(remove(fname)==0)
{
printf("\nFile Deletion success ");
}
else
{
printf("\nFile Not Found ");
}
}

Static Memory Vs Dynamic Memory:


-------------------------------------------------

Static Memory Dynamic Memory


============ ===============
1.Memory is allocated at compile time 1.Memory is allocated at run time

2.Static memory is not increased at the time program execution.

2.Dynamic memory is increased at the time


program execution.

3.Static memory is allocated for Arrays. 3.Dynamic memory is allocated for Linked
List.

DYNAMIC MEMORY ALLOCATION


==========================
C language requires the no of elements in an array to be specified at
compile time.But we may not be able to do so always our initial judgement of
size,if it is wrong,it make cause failure of the program (or) wastage of the memory
space.In this situation we use Dynamic Memory allocation.

Definition:-The process of allocating memory at run time is known as Dynamic memory


allocation.

To perform Dynamic memory allocation, c-language has the following pre-defined


functions with <alloc.h> header file to be included.
1.malloc()
2.calloc()
3.realloc()
4.free()

1.Malloc():-
---------
It is a function which is used to allocating memory at run time.
Syntax:- void *malloc(size_t size);
size_t:- unsigned integer. this is used for memory object sizes.

Pointer variable=(type casting)malloc(memory size);

Example:-

int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)malloc(n*sizeof(int)); //for n locations

2.Calloc():-
------------
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);

NOTE:- Calloc allocates a block (n times*size)bytes and clears into 0.

Difference between malloc and calloc:


1.Malloc defaultly store garbage value where as calloc defaultly stores zero
2.In malloc only one argurment we will pass where as in calloc we will pass two
arguments

3.Realloc():-
--------------------
It reallocates Main memory.
Syntax:- void *realloc(void *block, size_t size);

4.free():-
------------
It deallocates the allocated memory.
Syntax:- void free(void *block);

Example program:
-----------------------
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *p,n,i,s=0;
printf("Enter no.of elements to be store:");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
printf("\nEnter %d integer elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
}

printf("\nGiven Elements: ");


for(i=0;i<n;i++)
{
printf("%d%c%c",*(p+i),32,32);
s=s+*(p+i);
}
printf("\nSum of given elements:%d\n",s);
free(p);
}

You might also like