Professional Documents
Culture Documents
2nd Sem c Material(2019)
2nd Sem c Material(2019)
2nd Sem c Material(2019)
programming in c
Y Jagadeesh
Department of Computer Science
924 66 666 46
Kakinada
Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables – Pointer Expressions and
Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to Functions using Pointer – Pointer and
Arrays – Passing Array to Function – Difference between Array Name and Pointer – Pointers and Strings – Array of
pointers – Pointer and 2D Arrays – Function Pointers – Array 0f Function Pointer – Pointers to Pointers – Memory
Allocation in C Programs – Dynamic Memory Allocation – Drawbacks of Pointers
Structure, Union, and Enumerated Data Types:
Introduction – Nested Structures – Arrays of Structures – Structures and Functions – Self referential Structures –
Union – Arrays of Unions Variables – Unions inside Structures – Enumerated Data Types
UNIT V
Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data from Files – Detecting the
End-of-file – Error Handling during File Operations – Accepting Command Line Arguments – Functions for Selecting
a Record Randomly - Remove() – Renaming a File – Creating a Temporary File
6. Write a C program to find both the largest and smallest number in a list of integers.
CONTENTS
Chapter Page
S.No. Unit.No Topic
No. No.
1 Introduction to Algorithms and Programming Languages
2 Algorithm
3 Key features of Algorithms
4 Some more Algorithms
5 Flow Charts
1
6 Pseudo code
7 Programming Languages
8 Generation of Programming Languages
9 Structured Programming Language
Design and Implementation of Correct, Efficient and Maintainable
10.
Programs.
11 Introduction to C:
12 1 Introduction
13 Structure of C Program
14 Writing the first C Program
15 File used in C Program – Compiling and Executing C Programs
16 Using Comments Identifiers
17 2 Keywords
18 Basic Data Types in C - Operators in C
19 Variables
20 Constants
21 I/O Statements in C
22 Operators in C
23 Programming Examples – Type Conversion and Type Casting
ALGORITHM:
Step 1: START
Step 1: START
FLOWCHART:
FLOWCHART SYMBOLS:
Before drawing flowcharts you need to understand the different symbols used in Flowcharts. There are
many more symbols to make flowchart more meaningful. Below are standard flowchart symbols and thir meaning.
Draw a Flowchart to accept any two number and print addition of given two numbers:
START
DECLARE
A, B, C AS
INTEGERS
WRITE '
ENTER
ANY TWO
NUMBERS '
READ A, B
C<- A + B
STOP
DEFINING PSEUDOCODE:
Pseudocode is a simple way of writing programming code in English. Pseudocode is not actual programming
language. It uses short phrases to write code for programs before you actually create it in a specific language. Once
you know what the program is about and how it will function, then you can use pseudocode to create statements to
achieve the required results for your program
Pseudocode is a compact and informal high-level description of a program using the conventions of a
programming language, but intended more for humans.
Examples of Pseudocode:
Pseudocode to create a program to add 2 numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
PROGRAMMING LANGUAGES:
Computer programming is almost always done by means of Programming Language.There exists more than
2500 programming languages in the world. Some of them are known by only their developers
1. Very efficient
2. Require less storage space
Disadvantages:
1. Machine dependent
2. Programming is difficult
Second Generation: Assembly Language
Assembly language is a low-level programming language that allows a computer user to write a program
using abbreviations or more easily remembered words instead of numbers, A programmer can write instructions in
assembly language more quickly than in machine language, In these languages, each numeric instruction is
assigned a short name (called a mnemonic) that is easier to remember than a number.
Advantages:
A high level or procedural language resembles some human language such as English. For example, COBOL,
which is used for business applications A procedural language allow users to write in a familiar notation, rather than
numbers or abbreviations, Also, unlike machine and assembly languages, most of procedural languages are not
machinedependent- i.e., they can be used on more than one kind of computer. Few examples, are FORTRAN,
COBOL, BASIC and Pascal.
For a procedural language we need language translator to translate it into machine language. Depending on
the procedural language we may use either of the following types of translators compiler or an interpreter
COMPILER:
corresponding object code of the low-level language. This translation process is called compilation. The entire high-
level program is converted into the executable machine code file. Compiled languages include COBOL, FORTRAN, C,
C++, etc.
1. Scans the entire program first and translates it into machine code.
2. Converts the entire program to machine code
3. Slow for debugging (removal of mistakes from a program).
4. Execution time is less.
INTERPRETER:
The interpreter is a translation program that converts each high-level program statement into the
corresponding machine code. This translation process is carried out just before the program statement is executed.
Instead of the entire program, one statement at a time is translated and executed immediately. The commonly
used interpreted language is BASIC and PERL.
1. Translates the program line by line.
2. Each time the program is executed; every line is checked for syntax error and then converted to
equivalent machine code.
3. Good for fast debugging.
Advantages of Third Generation: High-Level or Procedural Languages:
1. These are easy to learn.
2. Easier to maintain.
3. They are not machine dependent.
4. Programs are portable.
Fourth Generation: Problem Oriented Languages
Fourth generation languages, in contrast, tell the computer what to do. Very high-level or problem-oriented
languages, also called fourth-generation languages (4 GLs), are much more user-oriented and allow users to
develop programs with fewer commands compared with procedural languages, although they require more
computing power. These languages are known as problem-oriented because they are designed to solve specific
problems, whereas procedural languages are more general-purpose languages.
Three types of problem-oriented languages are report generators, query languages, and application
generators.
Fifth Generation: Natural Languages:
Natural languages are of two types. The first are ordinary human languages: English, Spanish etc. The
second are programming languages that use human language to provide people a more natural connection with
computers.
BASIC: (Beginner's All-purpose Symbolic Instruction Code):
BASIC used to be the most popular microcomputer language and is considered the easiest programming
language to learn. Although it is available in compiler form, the interpreter form is more popular with first-time and
casual users. This is because it is interactive, meaning that user and computer can communicate with each other
during the writing and executing (running) of the program.
Advantage: The primary advantage of BASIC is its ease of use.
Disadvantages: Its processing speed is slow.
COBOL: (Common Business-Oriented Language):
1. It is machine independent.
3. Its English-like statements are easy to understand, even for a nonprogrammer.
4. It can handle many files, records, and fields.
5. It easily handles input/output operations.
Disadvantages:
1. Because it is so readable, it is wordy. Thus, even simple programs are lengthy, and programmer productivity is
slowed.
2. It cannot handle mathematical processing as well as FORTRAN
FORTRAN:
FORTRAN is the language of mathematics and the first high-level language. It was developed in 1954 by
IBM; FORTRAN (for FORmula TRANslator) was the first high-level language. Originally designed to express
mathematical formulas, it is still the most widely used language for mathematical, scientific, and engineering
problems. FORTRAN has both advantages and disadvantages:
Advantages:
1 FORTRAN does not handle input and output operations to storage devices as efficiently as some
other higher-level languages.
2 It has only a limited ability to express and process non-numeric data.
3 It is not as easy to read and understand as some other high-level languages.
PASCAL:
Pascal is the simple language. Named after the 17th-century French mathematician Blaise Pascal, Pascal is
an alternative to BASIC as a language for teaching purposes and is relatively easy to learn. A difference form BASIC
is that Pascal uses structured programming. A compiled language, Pascal offers these advantages and
disadvantages:
Advantages:
1. Pascal has limited input/output programming capabilities, which limits its business applications.
C++ :
C++ is an Object Oriented Programming (OOP) language. In C++-the plus signs stand for "more than C"-
which combines the traditional C programming language with object-oriented capability. C++ was created by Bjame
Stroustrup. Three important concepts of OOP are: Encapsulation, Inheritance, Polymorphism
1. It is portable.
2. Once the programmer has written a block of program code, it can be reused in number of
program.
STRUCTURED PROGRAMMING LANGUAGE:
Structured programming takes a top-down approach that breaks programs into modular forms. T he main
objectives of structured programming are
a. Efficiency
b. Readability
c. Clarity of programs
d. Easy modification
e. Reduced testing problems.
The goto statement should be avoided so far as possible. The three basic building blocks are given below
1. Sequential flow Control Structure:
It consists of a single statement or a sequence of statements with a single entry and single exit as shown in
Figure
It consists of a condition ( simple or compound ) and sequence structure which is executed condition
based as shown below
It consists of a condition (simple or compound ) and two branches out of which one is to be followed
depending on the condition being true or false as shown below:-
INTRODUCTION TO THE DESIGN AND IMPLEMENTATION OF CORRECT, EFFICIENT AND MAINTAINABLE PROGRAMS:
The design and development of a correct, efficient, and maintainable program depends on the approach
followed by the programmer. A programmer should follow standard methodologies throughout the life cycle of
program development. The entire program development process is divided into a number of phases, with each
As the name suggests, the first phase of program development involves analyzing the problem in order to
ascertain the objectives that the program is supposed to meet. All the identified requirements are documented so
as to avoid any doubts or uncertainties pertaining to the functionality of the program.
2. Designing Phase:
This phase involves making the plan of action before actually starting the development work. The plan is
made on the basis of the program specifications identified in the previous phase. Different programs require
different designing patterns depending on the program specifications.
3. Development Phase:
This phase involves writing the instructions or code for the program on the basis of the design document
created in the previous phase. The choice of the programming language in which the program will be developed is
made on the basis of the type of program.
4. Implementation and Testing:
In this stage, the developed program is implemented in its target environment and its key parameters are
closely observed in order to ensure that the program runs correctly. Apart from ensuring the correct functioning of
the program this phase primarily focuses on identifying the hidden bugs in the program.
It is of three type: programmer effort, execution time and memory space utilization. The high level
languages are used for programmer efficiency but, a program written in machine language or assembly language is
quite compact and takes less machine time, and memory space. So depending on the requirement a compromise
between programmer effort and execution time can be made.
2. Flexibility:
A program that can serve many purposes is called a flexible program. For example, CAD (computer aided
design) software are used for different purposes such as : Engineering drafting, printed circuit board layout and
design architectural design. CAD can also be used in execution time can be made.
3. Reliability:
It is the ability of a program to work its intended function accurately even if there are temporary or
permanent changes in the computer system. Programs having such ability are known as reliable.
4. Portability:
It is desirable that a program written on a certain type of computer should run on different type of
computer systems. A program is called portable if it can be transferred from one system to anther with ease.
5. Robustness:
A program is called robust if in provides meaningful results for all inputs. If correct data is supplied at run
time, it will provide the correct result. In case the entered data is incorrect, the robust program given an
appropriate message with no run time errors.
A program that can be easily understood even by a novice is called user friendly. This characteristic makes
the program easy to modify if the need arises.
7. Self documenting Code:
The source code which uses suitable names for the for identifiers is called self-documenting code. A cryptic
name for identifiers makes the program complex and difficult to debug later on (even the programmer may forget
the purpose of the identifiers). So, a good program must have self-documenting code.
INTRODUCTION:
HISTORY OF C LANGUAGE
C Programming Language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in U.S.A. Dennis Ritchie is known as the founder of c language. It
was developed to overcome the problems of previous languages such as B, BCPL etc. Initially, C language was
developed to be used in UNIX Operating System. It inherits many features of previous languages such as B and
FEATURES OF C LANGUAGE:
C is the widely used language. It provides a lot of features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1. Simple:
C is a simple language in the sense that it provides Structured Approach (to break the problem into
C Programs can be executed in many machines with little bit or no change. But it is not platform-
independent.
3. Mid-level Prorgramming language:
C is also used to do low level programming. It is used to develop system applications such as Kernel, Driver
etc. It also supports the feature of High Level Language. That is why it is known as Mid-Level Language.
C is a structured programming language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify.
5. Rich Library:
It supports the feature of Dynamic Memory Allocation. In C language, we can free the allocated memory at
any time by calling the free() function.
7. Speed:
C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can
use pointers for memory, Structures, functions, array etc.
9. Recursion
In c, we can call the function within the function. It provides code reusability for every function.
10. Extensible
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h
file before going to actual compilation.
2. Functions:
The next line int main( ) is the main function where the program execution begins.
3. Variables:
A Variable is a name of memory location. It is used to store data. Its value can be changed and it can be
reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Ex1: int a; Ex2: float b; Ex3: char c; Ex4: char n[10]; Ex5: int a,b,c;
4. Statements & Expressions:
The body of the function contains valid C statements and expressions. These statements are solve the given
task.
5. Comments:
Comments /*...*/ will be ignored by the compiler and it has been put to add additional comments in the
program. So such lines are called comments in the program.
To save the source code in a file, and how to compile and run it. Following are the simple steps −
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you have saved the file.
4. open hello.c and press Ctrl F9 to compile your code.
5. If there are no errors in your code, the command prompt will take you to the next line and would
generate hello.bak and hello.exe executable file.
6. Now, type hello.exe to execute your program.
7. You will see the output "HELLOW, WELCOME TO C WORLD" printed on the screen.
COMMENTS IN C:
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in C language.
1. Single Line Comments 2. Multi Line Comments
1. Single Line Comments:
Single line comments are represented by double slash \\. An example of single line comment in C.
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr(); //printing information
printf("Hello C");
getch(); } Output: Hello C
2. Multi Line Comments:
Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code but it can't
be nested. The Syntax is
A source character is a character that represents itself when used. In C language, Source Character Set
consists of following catagerious of characters.
S.No. Category Characters
1. Alphabets A to Z and UnderScore ( _)
2. Digits 0 to 9
3. Special Symbols ~, !, #, $, %, ^, &, *, @, /, etc.,
4. Punctuations ., ,, ‘, ”, :, :, (, ), [, ], {, }, etc.,
An escape sequence in C language is a sequence of characters that doesn't represent itself when used
inside string literal or character. It is composed of two or more characters starting with backslash \. For example: \
n represents new line.
WORDS IN C LANGUAGE:
A word is nothing but group of characters. In C Language words are classified into two types.
Key words are defined by the scientists. A Key Word is fixed and predefined meaning to the compiler. A keyword is
a reserved word. You cannot use it as a variable name, constant name etc. There are only 32 reserved words (keywords) in C
language. A list of 32 keywords in c language is given below:
These words are defined by the User or programmer. The Variable names, Data Names, Constant names,
Etc., are user defined words.
Ex1 : int a,b,c; Ex2: float jack, rose;
In the above statements int, float are Key Words and a, b, c, jack and rose are user defined words.
VARIABLES or IDENTIFIERS IN C:
A Variable or Identifier is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified. The
syntax to declare a variable or Identifier:
Syntax:
DataType Variable_nameor variables_list;
Where the Data types can be int (integer), char (character), float (real) etc
Types of Variables in C:
There are many types of variables in c:
1. local variable 2. global variable 3. static variable
4. automatic variable 5. external variable 6. register variable
1. Local Variable:
A variable that is declared inside the function or block is called local variable.
A variable that is declared outside the function or block is called global variable. Any function can change
the value of the global variable. It is available to all the functions. It must be declared at the start of the block.
3. Static Variable:
A variable that is declared with static keyword is called static variable. It retains its value between multiple
function calls.
void function1()
{
int x=10; //local variable
static int y=10; //static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, local variable will print the same value for each function call e.g,
11,11,11 and so on. But static variable will print the incremented value in each function call e.g. 11,12,13 and so on.
4. Automatic Variable:
All variables in C that is declared inside the block, are automatic variables by default. By we can explicitly
declare automatic variable using auto keyword.
void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
5. External Variable:
We can share a variable in multiple C source files by using external variable. To declare a external variable,
you need to use extern keyword.
myfile.h
extern int x=10; //external variable (also global)
Example:
#include "myfile.h"
The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster
access than other variables. It is recommended to use register variable only for quick access such as in counter.
Note: We can not get the address of register variable
Syntax:
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x
or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
Examples of integer literals:
85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */
30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form. While representing decimal form, you
must include the decimal point, the exponent, or both; and while representing exponential form, you must include
the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples
of floating-point literals
3.14159 /* Legal */ 314159E-5L /* Legal */
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A
character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\
u02C0').
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters. You can break a long line into
multiple lines using string literals and separating them using white spaces.
Examples: of string literals.
“ YRL COLLEGE “ “ JAGADEESH ” “ A9*ABC “
Defining Constants:
There are two simple ways in C to define constants
1. Using #define preprocessor.
2. Using const keyword.
1. #define Preprocessor:
You can use const prefix to declare constants with a specific type as follows
Syntax:
I O STATEMENTS IN C
C OPERATORS:
An operator is simply a symbol that is used to perform operations. There can be many types of operations
like Arithmetic, Relational, Logical and Bitwise Operators etc. The following types of operators are performs different
types of operations in C language.
1. Arithmetic Operators 2. Relational Operators 3. Logical Operators
4. Bitwise Operators 5. Ternary or Conditional Operators 6. Assignment Operator
7. Shift Operators 8. Misc Operator
1. ARITHMETIC OPERATORS:
Arithmetic operators performs basic arithmetic operations like Addition, Subtraction, Multiplication,
Division and Modulus division etc., Assume variable a holds 10 and variable b holds 20, then:
These Operators are used to compare two or more Operands or Variables and then produce either True or
False. These Operators are used to build Relational Or Boolean Expressions. Assume variable a holds 10 and
variable b holds 20, then:
S.NO. OPERATOR DESCRIPTION EXAMPLE
Checks if the values of two operands are equal or not, if yes then
1. == (a == b) is not true.
condition becomes true.
Checks if the values of two operands are equal or not, if values are not
2. != (a != b) is true.
equal then condition becomes true.
Checks if the value of left operand is greater than the value of right
3. > (a > b) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand,
4. < (a < b) is true.
if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
5. >= (a >= b) is not true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of
6. <= (a <= b) is true.
right operand, if yes then condition becomes true.
3. LOGICAL OPERATORS:
C Language supports the following logical operators – Logical Operators are used to combine two or more
Relational expressions in to a Logical expression. These Logical expressions produce either True or False. Assume
variable A holds 10 and B holds 20, then –
S.NO OPERATOR AND DESCRIPTION
1 && (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B) is true.
2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A || B) is true.
! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will
3
make it false. Ex: !(A && B) is false.
4. BITWISE OPERATORS:
Bitwise Operators are used to perform operations on Bits and Bytes, these operations are called Boolean
Operations. C Language supports the following Bitwise Operators −Assume variable A holds 2 and B holds 3, then –
S.No Operator and Description
1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.
2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.
4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.
<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
5 operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4.
>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by
6
the right operand. Ex: (A >> 1) is 1.
>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are
7
always zero. Ex: (A >>> 1) is 1.
5. ASSIGNMENT OPERATORS:
conditional operator ? : which can be used to replace if...else statements. It has the following general form
Syntax:
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition is true then
const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable otherwise
const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B; Example2: R=(X==Y) ? (X+Y) : (X-Y); Example3: N=(A>B) ? 100 : 200;
C Language supports Decision Making and Branching Statements which are used to perform different
actions based on different conditions. C Language supports the following forms.
If statements:
The if statement in C language is used to perform operation on the basis of condition. These statements can
perform operations either condition is true or false. There are many ways to use if statement in C language:
1. Simple if statement 2. if...else statement 3. if...else if... statement.(Nested if )
4. Conditional or Terinory Operator 5. switch-case and default statement
1. Simple if statement:
The simple if statement in C language is used to execute the code if condition is true. The syntax of if
statement is given below:
Syntax:
if(Test-Condition)
{
Single Statement; or Group of Statements; //code to be executed
}
Flowchart:
Example:
#include<stdio.h>
main()
{ int n; clrscr();
printf("enter any number:"); scanf("%d",&n);
if(n%2==0) {
printf("%d is even number",n); } getch(); }
2. if-else Statement:
The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-
else statement is given below:
if(Test-Condition)
{
Single Statement; or Group of Statements; // code to be executed if condition is true
}
else
{
Single Statement; or Group of Statements; // code to be executed if condition is false
}
Flowchart:
Example:
#include<stdio.h>
main()
{
int n; clrscr();
printf("enter any number:"); scanf("%d",&n);
if(n%2==0)
printf("%d is even number",n);
else
printf("%d is odd number",n);
getch(); }
3. Nested if ( if else-if ladder ) Statement:
The Nested if ( if else-if ladder ) is used to execute one code from multiple conditions. The syntax of Nested
if ( if else-if ladder )statement is given below:
Syntax:
if(Test-condition1)
{
Statement or Statements block //code to be executed if condition1 is true
}
else
if(condition2)
{
Statement or Statements block //code to be executed if condition2 is true
}
else
if(condition3)
{
Statement or Statements block //code to be executed if condition3 is true
}
---
---
else
{
Statement or Statements block //code to be executed if all the conditions are false
}
Example:
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter a, b and c values:");
scanf(" %d %d %d ",&a,&b,&c);
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition is true then
const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable otherwise
const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B;
Example2: R=(X==Y) ? (X+Y) : (X-Y);
Example3: N=(A>B) ? 100 : 200;
5. switch-case-default Statement:
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("enter any character:");
scanf("%c", &ch);
switch(ch)
{
case ‘v’ : printf(“ Violet “); break;
case ‘i’ : printf(“ Indigo “); break;
case ‘b’ : printf(“ Blue “); break;
case ‘g’ : printf(“ Green “); break;
case ‘y’ : printf(“ Yellow “); break;
case ‘o’ : printf(“ Orange “); break;
case ‘r’ : printf(“ Red “); break;
default : printf(“ Enter right choice”);
}
getch();
}
Flowchart:
The most basic loop in C language is the while loop. The purpose of a while loop is to execute a statement
or statement block repeatedly as lon g as an expression or Test-condition is true. Once the expression becomes false,
the loop terminates. It iterates the code until condition is false.
The while loop checks the Tes condition at the beginning of the loop. This means that this loop will always
be executed if the condition is True. So, it is called Entry Controlled Loop.
Syntax:
Exp1;
while (Test-condition)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
}
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is Increment or
Decrement expressions. Exp1 and Exp2 are optional.
Example:
#include<stdio.h>
void main()
{
int i,n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
i=1;
while(i<=n)
{
printf(“%d \n “, i);
i++;
}
getch();
}
Syntax:
Exp1;
#include<stdio.h>
void main()
{
int i,n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
i=1;
do
{
printf(“%d \n “, i);
i++;
} while(i<=n);
getch();
}
Example:
#include<stdio.h>
void main()
{
int i, n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
printf(“%d \n “, i);
}
getch();
}
}
4. Nested Loops:
In C language, Loop inside the loop is called Nested loops. We can write nested loops by using while(), do-
while() and for() structures. The syntax of Nested loop is
Syntax:
The syntax of for Nested loops using for() loop as follows
for (Initialization Statements; Test Condition1; Iteration Statements)
{
for (Initialization Statements; Test Condition2; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the Inner loop code to be executed
}
Statement or Statements;
----------
---------- //body of the Outer loop code to be executed
}
The following program demonstrate the working of nested loops (or) Generation of Prime Numbers
Example:
#include<stdio.h>
void main()
{
int i, j, n, c;
clrscr();
printf("Enter Upto How Many Prime Numbers Do You Wnt To Print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
c=0; for(j=2;j<i;j++)
{
if( i % j == 0) c++;
}
if ( c == 0) printf(“%d \n “, i);
} getch(); }
Example:
#include<stdio.h>
continue statement:
The continue statement in C language is used to continue the execution of loop (while, do while and for).
It is used with if condition within the loop. In case of inner loops, it continues the control of inner loop only.
Syntax:
The if statement and continue Statement can be write in while loop, do while loop, for loop statements.
Example:
#include<stdio.h>
void main()
{
int i, n; clrscr();
printf("Enter upto how many numbers do you wnt to print:"); scanf("%d", &n);
for( i=1; i<=n; i++)
{
if (i==10)
continue;
printf(“%d \n “, i);
}
getch();
}
}
#include<stdio.h>
main()
{
int age; clrscr();
Jack:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n"); scanf("%d", &age);
if(age<18)
goto Jack;
else
printf("You are eligible to vote!\n");
getch();
}
ARRAYS
Array:
Array in C language is a collection or group of elements (data). All the elements of c array
Advantage of C Arrays:
3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage of C Arrays:
1. Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList.
2. All the elements of c array are homogeneous (similar).
Types of Arrays:
We can declare Single Dimensional Arrays in C language in the following way. The general format
Syntax: data_type array_name[array_size];
Example: int N[5];
We can declare Single Dimensional Arrays in C language in the following way. The general format is
In such case, there is no requirement to define size. So it can also be written as the following code.
int N[]={20,30,40,50,60};
Here, int is the data type, N is array name 4 is the row size and 3 is the column size.
getch();
}
Output:
} //end of function
#include<stdio.h>
#include<conio.h>
FUNCTIONS IN C
Advantage of functions:
There are many advantages of functions.
1. Code Reusability:
By creating functions in C, we can call it many times. So we don't need to write the same code again and
again.
2. Code optimization:
1. Library Functions:
These functions which are declared in the C header files such as scanf(),printf(), gets(), puts(), ceil(),
floor() etc.
2. User-defined functions:
These functions which are created by the C programmer, so that we can use it many times. It reduces
complexity of a big program and optimizes the code. These functions are again classified into three types
a. Function with no arguments
b. Function with arguments
c. Function with arguments and return value
a. Function with no arguments:
These functions have no parameters or arguments and to solve a specific task. The general format for
declaration of function with no arguments is
Syntax:
<prototype> <name of the function>( ) // function declaration or definition
{
--------;
--------; Body of the function
--------;
}
The general format for calling of function with no arguments is
Syntax:
main()
{
--------;
--------; Body of the mainfunction
--------;
<name of the function>( ); // function calling
}
Example:
#include<stdio.h>
main( )
A function may have 0 or more parameters or arguments. These functions can have any type of
parameters such as int, float, char etc. The parameters are also known as formal arguments. The general format of
Declaration of a function with arguments or parameters is
Syntax: // function Declaration or Definition
<return_type or proto type><function_name>(data_type1 parameter1, data_type2 parameter2, ...)
{
--------;
--------; Body of the function
}
The general format for calling of function with arguments is
Syntax:
main()
{
--------;
--------; Body of the main function
<name of the function>( parameter1, parameter2, …..); // function calling
}
Example:
#include<stdio.h>
main( )
{
int a=10,b=20;
clrscr();
add(a,b); // function calling
getch();
}
To return any value from the function, We need to use any data type such as int, float,char etc. The return
type depends on the value to be returned from the function. A function may or may not return a value from the
function. If a function don't have to return any value use void for the return type. The general format of Declaration
of a function with arguments or parameters and return value is
Syntax:
<return_type or proto type> <function_name>(data_type1 parameter1, data_type2 parameter2, ...)
{
Example1:
void hello()
{
printf("hello c");
}
Example2: A function that has 1 parameter:
int cube(int n)
{
return n*n*n;
}
Calling a function in C:
A function returns any value, we need to call function to get the value returned from the function. The
syntax of calling a function in c is given below:
Syntax:
variable=function_name(argument1, argument2,...);
1. variable: The variable is not mandatory. If function return type is void, we must not provide the variable because
3. arguments: We need to provide arguments while calling the C function. It is also known as actual arguments.
Passing parameters:
There are two ways to pass value or data to function in C language. They are Call by value and call by
reference in C. Original value is not modified in call by value but it is modified in call by reference.
Call by reference in C:
In call by reference, original value is modified because we pass reference (address). Here, address of the
value is passed in the function, so actual and formal arguments share the same address space. Hence, value
changed inside the function, is reflected inside as well as outside the function. The following program demonstrate
this concept
#include <stdio.h>
main()
{
1 A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not reflected Changes made inside the function is reflected outside
2
on other functions the function also
Actual and formal arguments will be created in Actual and formal arguments will be created in same
3
different memory location memory location
Recursive functions:
A function calls itself certain number of times. A function which calls itself is called a recursive function, the
call is recursive call and the process of function implementation is recursion . A function it self calling that function is
called Recursive function. The general format of Recursive function is
Syntax:
Name of the Recursive function()
{
Body of the function;
reursionfunction(); //calling self function
}
Example of recursive function:
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}
#include<stdio.h>
void main()
Types of Recursion:
A function is recursive if it makes a call to itself directly or indirectly. If a function f() calls itself within from
its own body, it is called recursive. Secondly, if a function f() calls another function g() that ultimately calls back to
f(), then it can also be considered a recursive function. Following are ypes of recursions
1. Linear Recursion 2. Binary Recursion 3. Tail Recursion 4. Mutual Recursion
5. Nested Recursion
1. Linear Recursion:
This recursion is the most commonly used. In this recursion a function call itself in a simple manner and by
termination condition it terminates. This process called 'Winding' and when it returns to caller that is called 'Un-
Winding'.Termination condition also known as Base condition.
2. Binary Recursion:
Binary Recursion is a process where function is called twice at a time inplace of once at a time. Mostly it's
using in data structure like operations for tree as traversal, finding height,merging,etc.
3. Tail Recursion:
In this method, recursive function is called at the last. So it's more efficient than linear recursion method.
Means we can say termination point will come(100%) only we have to put that condition.
4. Mutual Recursion:
Functions calling each other. Let's say FunA calling FunB and FunB calling FunA recursively. This is not
actually not recursive but it's doing same as recursive. So we can say Programming languages which are not
supporting recursive calls, mutual recursion can be applied there to fulfill the requirement of recursion.
5. Nested Recursion:
It's very different than all recursions. All recursion can be converted to iterative (loop) except nested
recursion. We can understand this recursion by example of Ackermann function.
1. In recursion, function calls itself until the base condition is reached. On other hand iteration means
repetition of process until the condition fails. For example, looping Structures like for, while, etc. in
C programs.
The auto keyword is applied to all local variables automatically. It is the default storage class that is why it
is known as automatic variable. The following examples shows the working of auto storage class.
Example:
#include <stdio.h>
void main()
{
int a=10;
auto int b=10; //same like above
printf("%d %d",a,b);
}
Output: 10 10
2. register:
The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster
access than other variables. The use of register variable only for quick access such as in counter.
Example: register int counter=0;
3. static:
The static variable is initialized only once and exists till the end of the program. It retains its value between
multiple functions call. The static variable has the default value 0 which is provided by compiler. The following
examples shows the working of static storage class.
Example:
#include <stdio.h>
void main()
{
jack();
jack();
jack(); }
void jack()
{
static int i=0; //static variable
int j=0; //local variable
i++; j++; printf("i= %d and j= %d\n", i, j); }
Output: i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4. extern:
The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or
function.
Example: extern int counter=0;
C STRINGS
String:
String in C language is an array of characters that is terminated by \0 (null character). There are two ways
Array index starts from 0, so it will be represented as in the figure given below.
0 1 2 3 4 5 6 7 8 9
j a g a d e e s h \0
While declaring string, size is optional, We can write the above code as given below:
char ch[]={'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 'h', '\0'};
The following program to read and write strings using gets() and puts() functions.
#include<stdio.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
There are many important Character functions defined in "ctype.h" library that are useful for testing and
mapping characters.
Conversion Functions:
C language supports two conversion functions that accepts and returns an "int".
S.NO. FUNCTION & DESCRIPTION
1 tolower(character): This function converts uppercase letters to lowercase.
2 toupper(character): This function converts lowercase letters to uppercase.
C Mathematical Functions:
The commonly used functions math functions of math.h header file are given below.
S.NO. FUNCTION DESCRIPTION
rounds up the given number. It returns the integer value which is greater than or
1 ceil(number)
equal to given number.
rounds down the given number. It returns the integer value which is less than or
2 floor(number)
equal to given number.
3 sqrt(number) returns the square root of given number.
pow ( base,
4 returns the power of given number.
exponent)
5 abs(number) returns the absolute value of given number.
6 log(number) Returns the natural logirthm of given number
7 sin(degres) Returns sin value
8 cos(degres) Returns cosine value
C – Miscellaneous functions:
C POINTERS
Pointer:
A Pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, we must declare a pointer before using it to store any variable address
NULL Pointers:
A pointer that is assigned NULL is called a null pointer. This is done at the time of variable declaration. The
NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program
#include <stdio.h>
main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
Output:
The value of ptr is 0
if a pointer contains the null(zero) value, it is assumed to point to nothing. To check for a null pointer,We
can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Generic Pointer:
When a variable is declared as being a pointer to type void it is known as a generic pointer. Since We
cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced.
Generic Pointer is very useful when we want a pointer to point to data of different types at different times.
The following program describes the use of void pointer or Generic Pointer:
int main()
{
int i;
char c;
void *the_data;
i = 6;
c = 'a';
the_data = &i;
printf("the_data points to the integer value %d\n", *(int*) the_data);
the_data = &c;
printf("the_data now points to the character %c\n", *(char*) the_data);
return 0;
}
Passing Arguments to Functions using Pointers:
If we want to pass arguments(Single dimensional array) to a function, We have to declare a formal
parameter in one of following three ways and all three declaration methods produce similar results because each
tells the compiler that an integer pointer is going to be received. Similarly, We can pass multi-dimensional arrays as
formal parameters.
Way-1:
Formal parameters as a pointer
Syntax:
void myFunction(int *parameter)
{
…..
…..
}
Way-2:
Formal parameters as a sized array
Syntax:
void myFunction(int parameter[10])
{
…..
…..
}
Way-3:
Formal parameters as an unsized array −
Syntax:
void myFunction(int parameter[])
{
…..
…..
}
Example:
double getAverage(int arr[], int size)
{
int i;
float avg;
float sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
3. Pointer is dynamic in nature. The memory 3. They are static in nature. Once memory is allocated , it
allocation can be resized or freed later. cannot be resized or freed dynamically.
4. The assembly code of Pointer is different
4. The assembly code of Array is different than Pointer.
than Array
The malloc() function allocates single block of requested memory. It doesn't initialize memory at execution
time, so it has garbage value initially. It returns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)malloc(byte-size);
2. calloc():
The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It
returns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)calloc(number, byte-size);
If memory is not sufficient for malloc() or calloc(), we can reallocate the memory by realloc() function. In
short, it changes the memory size.
Syntax: ptr=realloc(ptr, new-size);
4. free():
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Syntax: free(ptr);
STRUCTURE IN C
Structure in c language is a user defined datatype that allows we to hold different type of elements. Each
element of a structure is called a member. It is widely used to store student information, employee information,
product information, book information etc.
Defining structure:
The struct keyword is used to define structure. The syntax to define structure in c is
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
struct book
{
int p;
float c;
char n[10;
};
Here, struct is the keyword, book is the tag name of structure; p, c and n are the members or fields of the
structure.
Declaring structure variable:
We can declare variable for the structure, so that we can access the member of structure easily. There are
two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring variable at the time of defining structure.
1 way:
st
Let's see the example to declare structure variable by struct keyword. It should be declared within the main
function. struct employee
{
int id;
Array of Structures in C:
There can be array of structures in C programming to store many information of different data types. The
array of structures is also known as collection of structures. This program shows the structure with array that stores
information of 3 students and prints it.
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
for(i=0;i<2;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
Nested Structure in C:
Nested Structure can have another structure as a member. There are two ways to define nested structure in
c language:
1. By separate structure
2. By Embedded structure
1. Separate structure:
We can create 2 structures, but dependent structure should be used inside the main structure as a member.
Let's see the code of nested structure.
struct Date
{
int d;
int m;
int y;
};
struct Employee
{
int id;
char n[20];
struct Date doj;
} emp1;
In the above example, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
2. Embedded structure:
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure:
We can access the member of nested structure by Outer Structure. Nested_ Structure.member as given
below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
Example:
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
main( )
{
e1.id=101; //storing employee information
strcpy(e1.name,"Jagadeesh"); //copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id); //printing first employee information
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,1.doj.yyyy); return 0;
}
Output:
employee id : 101
employee name : Jagadeesh
employee date of joining (dd/mm/yyyy) : 10/11/2014
C UNION
C Union:
In C, like structure, Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory
of largest member.
Enumerated data type variables can only assume values which have been previously declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
enum month m;
m = feb;
In the above declaration, month is declared as an enumerated data type. It consists of a set of values, jan
to dec. Numerically, jan is given the value 1, feb the value 2, and so on. The variable m is declared to be of the
same type as month, then is assigned the value associated with feb. m cannot be assigned any values outside those
specified in the initialization list for the declaration of month.
#include <stdio.h>
main()
{
char *pwest = "west";
*pnorth = "north";
*peast="east",;
*psouth = "south";
enum location { east=1, west=2, south=3, north=4};
enum location direction;
direction = east;
if( direction == east )
{
printf("Cannot go %s\n", peast);
}
getch();
}
The variables defined in the enumerated variable location should be assigned initial values.
FILE HANDLING IN C
File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.
Advantage of File:
It will contain the data even after program exit. Normally we use variable or array to store data, but data is
lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage
medium.
File Handling Functions:
There are many functions in C library to open, read, write, search and close file. A list of file functions
are given below:
S.No. FUNCTION DESCRIPTION
1 fopen() opens new or existing file
2 fprintf() write data into file
3 fscanf() reads data from file
4 fputc() writes a character into file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
MODE DESCRIPTION
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
The fopen() function is used to open a file. The syntax of fopen() function is
Syntax: FILE *fopen( const char * filename, const char * mode );
Example: fptr = fopen("emp.txt", "w+");
2. Closing File: fclose():
The fclose() function is used to close a file. The syntax of fclose() function is
The following File Handling functions are used to read data from files.
a. fscanf() b. fgetc() c. fgets()
a. fscanf() function:
The fscanf() function is used to read data from files. It sends formatted input from a stream.
Syntax: int fscanf(FILE *stream, const char *format [, argument, ...]);
Example: fscanf(fptr, "Id= %d\n", id);
b. fgetc() function:
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns
EOF at the end of file.
Syntax: int fgetc(FILE *stream);
Example: c=fgetc(fp);
c. fgets() function:
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax: char* fgets(char *s, int n, FILE *stream);
Example: printf("%s",fgets(text,200,fp));
4. Writing Files:
The following File Handling functions are used to write data into files.
a. fprintf() b. fputc() c. fputs()
a. fprintf() function:
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax: int fputc(int c, FILE *stream);
Example: fputc(ch, fp);
c. fputs() function:
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax: int fputs(const char *s, FILE *stream);
Example: fputs("hello c programming",fp);
5. fseek() function:
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at
desired location.
Syntax: int fseek(FILE *stream, long int offset, int whence);
Example: fseek( fp, 7, SEEK_SET );
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and SEEK_END.
6. rewind() function:
The rewind() function sets the file pointer at the beginning of the stream. It is useful if we have to use
stream many times.
Syntax: void rewind(FILE *stream);
Example: rewind(fp);
7. ftell() function:
The ftell() function returns the current file position of the specified stream. We can use ftell() function to get
the total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file
pointer at the end of file.
Syntax: long int ftell(FILE *stream);
Example: length = ftell(fp);