Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 75

DIT Notes of C Language

Notes of Computer Language

What is C- Programming Language?

C is a general-purpose computer programming language developed in 1972 by

Dennis Ritchie. Although C was designed for implementing system software, it is

also widely used for developing portable application software.

C is one of the most popular programming languages. It is machine-independent,

structured programming language which is used extensively in various applications.

C is a base for the programming. If you know 'C,' you can easily grasp the

knowledge of the other programming languages that uses the concept of 'C'.

Characteristics of C- Programming Language

'C' is a structured programming language in which program is divided into various

modules. Each module can be written separately and together it forms a single 'C'

program. This structure makes it easy for testing, maintaining and debugging

processes.

'C' contains 32 keywords, various data types and a set of powerful built-in functions

that make programming very efficient.

Another feature of 'C' programming is that it can extend itself. A 'C' program contains

various functions which are part of a library. We can add our features and functions
to the library. We can access and use these functions anytime we want in our

program. This feature makes it simple while working with complex programming.

Various compilers are available in the market that can be used for executing

programs written in this language.

It is a highly portable language which means programs written in 'C' language can

run on other machines. This feature is essential if we wish to use or execute the

code on another computer.

Elements of C-Language

C-Program is collection of different elements, which are the following:

Variables: These will how data is represented. It can range from something very

simple, such as the age of a person, to something very complex, such as a record of

university students holding their names, ages, addresses, what courses they have

taken, and the marks obtained.

Constant: The values, which are used in program and remain the same during

execution of program, are called constant values.

Loops: This will allow us to carry out execution of a group of commands a certain

number of times.

Conditionals: This will specify execution of a group of statements depending on

whether or not some condition is satisfied. These type of statement used different

operators for calculation and making decision.

Input/Output: This will allow interaction of the program with external entities. This

might be as simple as printing something out to the terminal screen, or capturing


some text the user types on the keyboard, or it can involve reading and/or writing to

files.

Subroutines and functions: This will allow you to put oft-used snippets of code into

one location, which can then be used over and over again.

What is Constants how we define Constants

A constant value is the one, which does not change during the execution of a

program. C supports several types of constants.

1. Integer Constants

2. Real Constants

3. Single Character Constants

4. String Constants

Defining Constants

In C/C++ program we can define constants in two ways as shown below:

1. Using #define preprocessor directive

2. Using a const keyword

1-Using #define preprocessor directive:

Preprocessor Directive are the lines included in program with the character# which

make them different from the normal code. We can use this to declare a constant as

shown below:

#define identifierName value

identifierName: It is the name given to constant.


value: This refers to any value assigned to identifierName.

Example:

#define val 10 

#define floatVal 4.5 

#define charVal 'G' 

2-using a const keyword:

Using const keyword to define constants is as simple as defining variables, the

difference is you will have to precede the definition with a const keyword.

Example:

For const int intVal = 10; 

Literals:

The values assigned to each constant variable are referred to as the literals.

Generally, terms, constants and literals are used interchangeably.

 For example

 “const int = 5;“

 Is a constant expression and the value 5 is referred to as constant integer literal.

Data type on C language

There are two basic data types use in c language:

1. Primary data types


2. Derived data types

Primary data types:

These are fundamental data types in C namely integer(int), floating point(float),

character(char) and void.

Derived data types:

Derived data types are nothing but primary data types but a little twisted or grouped

together like array, structure, union and pointer. These are discussed in details later.

Primary Data Types:

1) Integer Data type: -


An integer data type is used to store the whole number. There are 3 types of

integer’s namely decimal integer, octal integers and hexadecimal integer.

Decimal Integers: it consists of a set of digits 0 to 9 preceded by an optional + or -

sign. Spaces, commas and non-digit characters are not permitted between digits.

Example Decimal integer constants are

123 , -31 , 0 , 562321 , + 78

Some examples for invalid integer values are

15 750 , 20,000 , Rs. 1000

Octal Integers constant consists of any combination of digits from 0 through 7 with a

O at the beginning. Some examples of octal integers are

O26 , O , O347 , O676


Hexadecimal integer constant is preceded by OX or Ox, they may contain

alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal

digits. Example of valid hexadecimal integers are

OX2 , OX8C , Oxbcd , Ox

2) Floating Point Data Type:

Floating Point data type is used to store the fractional part (Real Number).

Example of real values are:

0.0026 , -0.97 , 435.29 , +487.0

Floating Point Data type consist on Float, Double and Long Double

3) Character Data Type :

It is used to store a Single Character.

Example for character constants are

'5' , 'x' , ';' , ' '

Void type

void type means no value. This is usually used to specify the type of functions which

returns nothing. We will get acquainted to this data type as we start learning more

advanced topics in C language, like functions, pointers etc.

[Escape Sequences] Back slash Character Constants


Backslash character constants are special characters used in output functions.

Although they contain two characters they represent only one character. Given

below is the table of escape sequence and their meanings.

Escape sequences are typically used to specify actions such as carriage returns and

tab movements on terminals and printers. They are also used to provide literal

representations of nonprinting characters and characters that usually have special

meanings, such as the double quotation mark ("). The following list has some the

ANSI escape sequences and what they represent.

Constant Meaning

'\a' Audible Alert (Bell)

'\b' Backspace

'\f' Form feed

'\n' New Line

'\r' Carriage Return

'\t' Horizontal tab

'\v' Vertical Tab

'\'' Single Quote

'\"' Double Quote


'\?' Question Mark

'\\' Back Slash

'\0' Null

Variables in C Programming Language

A variable is a value that can change any time. In computer programming we say

those variables are those memory locations, which are used to store the constant

value. The programmer should carefully choose a variable name so that its use is

reflected in a useful way in the entire program. Variable names are case sensitive.

Example of variable names are

Sun , number , Salary , Emp_name

average1

Any variable declared in a program should confirm to the following Rules:

1. They must always begin with a letter, although some systems permit

underscore as the first character.

2. The length of a variable must not be more than 8 characters.

3. White space is not allowed and


4. A variable should not be a Keyword

5. It should not contain any special characters.

Examples of Invalid Variable names are

123 , (area) , 6th , %abc

Basic Data types of variables:

There are four basic types of variable in C; they are: char, int, double and float.

Type name Meaning

char The most basic unit addressable by the machine; typically a single octet(one

byte). This is an integral type.

int The most natural size of integer for the machine; typically a whole 16, 32 or 64-

bit(2, 4, or 8 bytes respectively) addressable word.

float A single-precision floating point value.

double A double-precision floating point value.

Declaration of Variables

You are required to declare your variables before you use them. You do this by

providing a list of variables near the beginning of the program. That way, the

compiler knows what the variables are called and what type of variables they are
(what values they can contain). Officially, this process is known as declaring your

variables.

For example:

int count;

char key;

char lastname[30];

Types of Declaration of variable (Classification of Variable)

Local Variable: -

When we declare a variable in body of the function this is called local variable. These

types of variable are used only in this function in which these variables are declare.

Global Variables: -

Local variables are declared within the body of a function, and can only be used

within that function. Alternatively, a variable can be declared globally so it is available

to all functions. Modern programming practice recommends against the excessive

use of global variables. They can lead to poor program structure, and tend to clog up

the available name space.

A global variable declaration looks normal, but is located outside any of the

program's functions. This is usually done at the beginning of the program file.

External Variables: -
Where a global variable is declared in one file, but used by functions from another,

then the variable is called an external variable in these functions.

Global and external variables can be of any legal type. They can be initialized, but

the initialization takes place when the program starts up, before entry to the main

function.

Static Variables

Another class of local variable is the static type. Static can only be accessed from

the function in which it was declared, like a local variable. The static variable is not

destroyed on exit from the function; instead its value is preserved, and becomes

available again when the function is next called. Static variables are declared as

local variables, but the declaration is preceded by the word static.

Static int counter;

Static variables can be initialized as normal; the initialization is performed once only,

when the program starts up.

Keyword / Reserve Word

These are the word, which have special meaning for compiler. These meaning are

predefined to compiler. There are 38 keywords, which are used in C-Language.

auto double int struct

break else long switch

case enum register typedef


char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Operators

Operator are special symbol that perform some special function like that addition,

multiplication etc. You should be familiar with operators such as +, -, /. 

Following are some Operator that is used in C-Language.

1) Arithmetic operators

These are operator which are used to perform Mathematical calculations.

The symbols of the arithmetic operators are:

+ Addition

- Suntraction

* Multiplication

/ Division
% (Find Reminder from Integer Division)

*, / And % will be performed before + or - in any expression. Brackets can be used to

force a different order of evaluation to this. Where division is performed between two

integers, the result will be an integer, with remainder discarded. Modulo reduction is

only meaningful between integers. If a program is ever required to divide a number

by zero, this will cause an error, usually causing the program to crash.

Examples of arithmetic operators are

x+y

x-y

-x + y

(a * b) + c

2) Relational Operators: -

Relational operator is required to compare the relationship between operands

(Constant/variable/expression) and bring out a decision. C supports the following

relational operators.

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equal to

! = Not equal to
It is required to compare the marks of 2 students, salary of 2 persons; we can

compare them using relational operators.

A simple relational expression contains only one relational operator and takes the

following form.

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or

combination of them.

Given below is a list of examples of relational expressions and evaluated values.

6.5 <= 25 TRUE

-65 > 0 FALSE

10 < 7 + 5 TRUE

3) Logical (Operator) Connectors

They are frequently used to combine relational Expression, for example

x < 20 && x >= 10

These are following:

&& AND

|| OR

! NOT

In C these logical connectives employ a technique known as lazy evaluation. They

evaluate their left hand operand, and then only evaluate the right hand one if this is

required.
These operator return the following result by using different combination:

True && True = True

True && False = False

False && True = False

True || True =True

True || False =True

False || True =True

If we use && operator then both side return must True and both side must be

checked.

But if we use || (OR) Operator then only one side return True Result the Expression

Return True. In this case if left side return true then there is no Need to check the

Right Expression.

4) Assignment Operator: -

The assignment operator use in assignment statement. In assignment statement we

assign the value to variable directly or indirectly.

X=10 ;

In this example we assign the value 10 to x directly.

x = (m * n) + c;

In this example first of all expression is evaluated and then result of the expression

save in variable x.

5) Increment or Decrement Operator: -


The increment and decrement operators are one of the unary operators, which are

very useful in C language. They are extensively used in for and while loops.

 The syntax of the operators is given below

1. ++ variable name

2. variable name++

3. – –variable name

4. variable name– –

The increment operator ++ adds the value 1 to the current value of operand and the

decrement operator – – subtracts the value 1 from the current value of operand. +

+variable name and variable name++ mean the same thing when they form

statements independently, they behave differently when they are used in expression

on the right hand side of an assignment statement.

Consider the following

m = 5;

y = ++m; (prefix)

In this case the value of y and m would be 6

Suppose if we rewrite the above statement as

m = 5;

y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to

the operand and then the result is assigned to the variable on the left. On the other
hand, a postfix operator first assigns the value to the variable on the left and then

increments the operand.

6) Conditional or Ternary Operator: -

The conditional operator consists of 2 symbols the question mark (?) and the colon

(:).

The syntax for a ternary operator is as follows

exp1 ? exp2 : exp3

The ternary operator works as follows

exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value

becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value

becomes the value of the expression. Note that only one of the expression is

evaluated.

For example

a = 10;

b = 15;

x = (a > b) ? a : b

Here x will be assigned to the value of b. The condition follows that the expression is

false therefore b is assigned to x.

Expression :-

Operators and values are combined to form expressions. The values produced by

these expressions can be stored in variables, or used as a part of even larger

expressions.
We say that collection of operand and operator is called expression. If expression

use Arithmetic operator then expression is called Arithmetic expression, if expression

use logical operator then this is called logical expression. And if expression is used

relational operator then this is called relational expression.

X +5 (Arithmetic Operator)

X > Y (Relational expression)

X > Y && X < N (logical expression)

Structure of C Program

A Very Simple C-Program


This program, which will print out the message:

main()

printf("This is a C program\n");

 Though the program is very simple few points are worthy of note.

 Every C Program consists on one or more then on function.

 Every C program must contain a function called main. This is the start point of

the program.

 main() declares the start of the function, while the two curly brackets show the

start and finish of the function.


 Curly brackets in C are used to group statements together as in a function, or

in the body of a loop. Such a grouping is known as a compound statement or

a block.

 èEvery function contains some statements and every statement end with

semicolon (;).

 printf("This is a C program\n");

 Prints the words on the screen. The text to be printed is enclosed in double

quotes. The \n at the end of the text tells the program to print a new line as

part of the output.

 Most C programs are in lower case letters. You will usually find upper case

letters used in preprocessor definitions or inside quotes as parts of character

strings.

 C is case sensitive, that is, it recognizes a lower case letter and it's upper

case equivalent as being different.

 Steps Involve in Writing A C-Program

 Open the Turbo-C IDE (Integrated Development Editor)

 Crate a New file by selecting option New from File Menu

(Press ALT+F for opening File Menu and then select New Option)

 Now write the code (statements) of C-Program

 After writing Complete Program Save The File with Save option from File

Menu.

(Press ALT+F for opening File Menu and then select Save Option)


Compiling C- Program:

After writing C-Program first of all compile C-Program and create Object File. For this

purpose select Compile Option from Compile Menu.

 (Press ALT+C for opening Compile Menu and then select Compile Option)

 If any bugs (error) occur then correct these errors by Editing Option.

Executing C-Program

 When program Successfully compile and all the bugs are removed then

execute this program.

 For This purpose we have two ways:

 First way is by making Executable File by Selecting Make EXE

File Option from Compile Menu. After this is Executable file is Save on Your

Drive now you can Run this file.

 Second way is we directly execute the program from Run Menu by

Select Run Option or Pressing Ctrl + F9 Key. In this way Executable File is

automatically created, saved and also Execute.

 What is CODE File, Object File and Executable File In “ C “?

 In C-Language when we write a c program then after writing we save the file

this is called Code file and save with extension “. C “.

 After this when we compile the File then our code is transferred in machine

language and an other file (called Object file) is created. This file is

translation of our code to machine language and separately store with

extension “. OBJ “.
 In the end when we want to execute our file first of all we make executable

file. This file also separately store with extension “. EXE “.

Preprocessor Directive

Preprocessor Directive are the lines included in program with the character# which

make them different from the normal code.

processor directives are execute before compile actual program. with the help of

Preprocessor Directive we can inlcude the header files in our program or define

macor in our program.

Some of the Preprocessor Directive are:

#include<filename>

#define

#undefine

For example :

when we use getch() function then we must include <conio.h> file.

#include<conio.h>

Input / Output Statements

Formatted Input/Output

printf() and scanf() functions are inbuilt library functions in C programming language.

'Printf and Scanf function are used for formatted INPUT and OUTPUT. We have to
include “stdio.h” file as shown in below C program to make use of these printf() and

scanf() in C language.

Printf Function:

Printf allows formatted out put of data. In C programming language, printf() function

is used to print the “character, string, float, integer, octal and hexadecimal values”

onto the output screen. Its arguments are:

1. It has some constant value for example “String Constant”.

2. It has some control string, which controls what gets printed.

3. Control string followed by a list of values to be substituted for entries in the

control string.

Syntax:

Printf(“Control string / string constant ", List of argument)

Scanf Function: -

scanf allows formatted reading of data from the keyboard In C programming

language, scanf() function is used to read character, string, numeric data from

keyboard .

1. It has some control string, which controls what gets printed.

2. Control string followed by &variable name into which the typed response will

be placed.
Syntax:

Scanf("control string ",&variable 1 ,&variablc2,,,,,,)

gets( ) function:

The gets function is used to read a single line (until new line is encountered). When

all input is finished (when enter key is pressed) a NULL character is append at the

end of the string, which shows end of the string input.

Syntax:

gets (variable 1, variable2...) Where variable is any string type variable

puts () Function:

This function is used to print the string values on screen. When output of string is

over, then a new line is inserted automatically.

Syntax:

puts(variable name or string constant)

 getch () Function:

Getch stand for "Get character ". This function is used to get the single character

From the user during the execution of program. When we input the character then its

not display on the screen and control is transfer to next statement with out pressing

enter key.

Syntax:
getch () Function:

getche () Function:

This function also gets the character form the user at time of execution. When we

use getch then entered character not display on the screen but with getch character

display on the screen and pressing of enter key is required.

Syntax:

getche () Function:

For example

X= getche();

When user enter the character then this character store in x (where x is a character

variable).

Format specifiers

Format specifiers are the sequence passed as the formatting string argument in

printf( ) and scanf( ) function.

These are the special character that represent the type of out put and in put of

argument in formatted input output functions (printf and scanf statements).

Following are the some Format specifiers.

%d Integer

%f Float
%e Exponent

%g General

%c Character

%s Siring

%u Unsigned

%1 Long

%o Octal

%x Hexa

Transfer OF Control

Control Structure:

C is procedure-oriented language. In C program control is transfer form one

statement to other statement in that order in which these statement are written. But

some time we change this control according to our own need. For this purpose we

use transfer of control statements. Two types of transfer of control are used in C-

Language:

1. Conditional transfer of control


2. Unconditional transfer of control

Conditional transfer of control:

In this type of control a condition is given. If the condition is true than control is

transfer to specified statement. For this purpose we use Decision making statement

(IF and else statement or switch statement).

IF Statement

if statement is decision making statement or decision control statement in this

statement we give a condition after using “ IF “ key word. If the condition is “True “

then a statement or set of statements in the body of “ IF “ structure are executed

and if the condition is "False” then nothing will be do and control is transfer to next

statement according to sequences.

“ We say that if statement allows you to execute specific parts of a program if certain

conditions are met (if condition is true) “.

If structure contain three main parts. The first is the keyword “ if “. The second is

an expression enclosed in parentheses (Condition). The third is the block

of code (which is written in parentheses) that you want to run if the condition met to

given condition.

Syntax:

If (condition) Body of If Structure


{

statement 1;

statement 2;

 }

IF-Else Statement

If-Else statement is decision making statement or decision control statement in this

statement we use two Keyword “ IF “ and “ ELSE “ we give a condition after using “

IF “ key word. If the condition is “True “ then a statement or set of statements in

the body of “ IF “ structure are executed and if the condition is "False” then

statement or set of statement in the body of Else will be executed.

“ We say that if statement allows you to execute specific parts of a program if certain

conditions are met (if condition is true) “.

Syntax:

If (Condition)

statement 1;

statement 2;

{
else

statement 1;

statement 2;

Note: - If the statement block is only one statement, the braces are not necessary.

Example: - Scan a number from user and display message that number that enter

is 

+ve or -ve.

main()

int n;

printf(“Enter a number \n”);

scanf(“%d” , &n ) ;

if(n>=0)

printf("number is +ve") ;

else

prinlf( “Number is –ve ") ;

getch( );

}
In above example user enter a number. This number is stored in N (variable) then

condition is checked that number is greater then zero is less zero. If the number is

grater then zero its means that condition is true then message appear that "Number

is + ve " and if condition is false then message appear that "number is -ve".

NESTED IF

If an IF statement is tart in the body of other IF statement then this is called nested

if statement.

it is used when we have multiple conditions to check and when any if condition

contains another if statement then that is called ‘nested if’.

Syntax:

If (condition expression)

Block of statements

Else if (another condition expression)

Another block of statements

Else

Yet another block of statements


}

In simple word when we have multiple choices or multiple conditions then we use

nested if-structure. For this purpose we put an other if statement in the body of first if

statement.

Example
main( )

int n ;

printf( "Enter a number" ) ;

scanf (“ %d ” , &n ) ;

if(n== 1)

printf( “You Enter One” ) ;

else

if(n==2)

printf( “You Enter Two” ) ;

else

if(n==3)

printf( “You Enter Three” ) ;

else

printf( “ You enter other the one , two or three " ) ;


}

getch( );

in above example we see that if we enter 1(one) form keyboard then message

appear that "You enter One" other wise condition is again tested end the result is

prepared .

The switch Statement

This is another form of the multi way decision. It is well structured, but can only be

used, in certain cases where;

Only one variable is tested, all branches must depend on the value of that variable.

The variable must be an integral type. (Int. long, short or char).

Each possible value of the variable can control a single branch.

A final, catch all, default branch may optionally be used to trap all unspecified cases.

Switch statement work similar as nested if statement works.

In this example user enter a character and this program decides whether you enter

a, b, c or other then these character.

min( )

 Char x ;

Printf( “Enter a character ") ;

scanf(" %c ", &x);


switch (x)

case ' a ' :

Printf( " you enter A " );

Break ;

case ' b ' :

Printf( " you enter B " );

Break ;

case ' c ' :

Printf( " you enter C " );

break;

default :

printf ( " You enter other then a , b , c") ;

getch( ) ;

Each interesting case is listed with a corresponding action. The break statement

prevents any further statements from being executed by leaving the switch. Since

case 3 and case 4 have no following break, they continue on allowing the same

action for several values of number.


Loops

When we want to execute a statement or group of statement repeatedly then we use

Loops. In simple word when we do some work again and again for specified period

of time in the same way then we use loops.

For example if we want to print message "hello C" 100 times then there are two

ways to perform this type of task.

First we use printf statement 100 time to print this message on the screen.

Second we write single statement in the body of the loop which print this message

100 time.

So we observed that second one method is simple and easy and less time

consuming.

In C language we have choice of three types of loop, for , while and do while .

These loop are classified in two types

 Count Control Loop

 Event control Loop

Count Control Loop:

Each time the body of the loop is executed is called iteration. When the number of

repetition (Iterations) is well known before the processing than we use count control

loop. For example For Loop is an example of Count Control Loop.

Event control Loop:


When we not enough knowledge about the total iterations of the execution of loop

then we use event control loop. Event control loop repeated until some thing

happens with in the loop.

If you are making a angle food cake and the recipe reads “Beat the Mixture 300

strokes” its means you are executing count control loop. And if recipe reads “ Beat

the Mixture until the Color of Mixture change in brown color “ its means you are

executing event count loop.

I am sure you well under stand these two structures. Now we discussed Three Loop

 For loop

 While Loop

 Do While Loop

FOR LOOP

For loop is Count Control loop. The for loop works well, where the number of

iterations of the loop is known before the loop is entered. The head of the loop

consists of three parts separated by semicolons.

The initial value: - This is usually the initialization of the loop variable and its initial

Value this variable is called Loop Counter.

Condition: -The second part is a test; the loop is terminated when this returns false.

Step: - The third is a statement to be run every time the loop body is completed. This

is usually an increment of the loop counter.


Syntax of for loop:

for (initial Counter ; test condition ; increment)

statement 1;

statement 2;

statement 3;

Note: - If the statement block is only one statement, the braces are not necessary.

Example:

Following example give clear idea of using loop.

main( )

int i ;

for(i=1 ; I<=100 ; i++) ;

printf( “ %d” , i) ;

getch();

This Program print 1 to 100 digit on screen so we see that only one statement

executed and 1 to 100 number print on the screen because of header of this

statement is for loop which repeatedly execute the statement below which print the

number.
While Loop: -

The while loop keeps repeating an action until an associated test returns false. This

is useful where the programmer does not know in advance how many times the loop

will be traversed.

The while construct consists of a block of code and a condition. The condition is

evaluated, and if the condition is true, the code within the block is executed. This

repeats until the condition becomes false. Because while loops check the condition

before the block is executed, the control structure is often also known as a pre-test

loop.

Syntax:

While (condition)

statement 1 ;

statement 2 ;

statement 3 ;

Note: - If the statement block is only one statement, the braces are not necessary.

Example:

Following example give clear idea of using loop.

main()

{
int x = 1 ;

while (x < =100)

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

x++;

getch( );

This program also displays 1 to 100 digits on screen. But there is no counter as in for

loop. In this while loop x++ increment in the value of x one time and transfer the

control to while loop and check if x<=100 then again execute the printf statement and

then increase the x. this loop is terminated when x increases the value of 100.

Do While Loop:

The do while construct consists of a block of code and a condition. First, the code

within the block is executed, and then the condition is evaluated. If the condition is

true the code within the block is executed again. This repeats until the condition

becomes false. Because do while loops check the condition after the block is

executed, the control structure is often also known as a post-test loop. Contrast with

the while loop, which tests the condition before the code within the block is executed.

The do while loops is similar to while loop, but the test occurs after the loop body is

executed. This ensures that the loop body is run at least once.

Syntax: -
Do

statement 1 ;

statement 2 ;

statement 3 ;

Note: - If the statement block is only one statement, the braces are not necessary.

Example: -

Following example give clear idea of using loop.

Main()

int x = 11 ;

do

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

} while (x <= 10) ;

getch( );

}
We see as the value of x is greater then 10 in the start but printf statement executed

one time and then condition is test which identify that x > 10 so return False and loop

execution is terminated and control is transfer to next statement.

Continue Statement:

In some programming situation we want to take the control to the beginning of the

loop by passing the statement inside the loop. Which have not yet been executed.

For this purpose we use continue statement. When keyword continue is occurred

then control transfer to the beginning of the loop with out executing the statements

after the continue keyword in the body of the loop.

For example if we want to print all the number form 1 to 100 but those number are

not printed which are divisible by two. The C program for this purpose is as follow.

main()

int n ;

for(n=1 ; n<=100 ; n++)

if(n%2==0)

continue ;

printf( " %d ", n) ;

}
getch( ) ;

Break Statement:

When we want to jump out form the loop with out waiting to get back to test condition

then we use Break statement.

Following program is best example to under stand the break statement.

main ( )

int i ;

clrscr( );

for (I =0 ; I<=100 ; I++)

if (i==50 )

break ;

printf(“ %d” , I) ;

getch() ;

}
We see that in this program we use for loop to display the number 1 to 100 . but

using break statement before the printf statement stopped the loop when counter

reached to 50 and loop is terminated.

Nested Loop:

The placing of one loop inside the body of another loop is called nesting. When you

"nest" two loops, the outer loop takes control of the number of complete repetitions

of the inner loop. While all types of loops may be nested, the most commonly nested

loops are for loops.

For example:

main ( )

int i , j ;

clrscr( ) ;

for(i=1 ; i<=3 ; i++)

for(j=1 ; j<=3 ; j++)

printf(“Hello c \n “);

getch( ) ;

In this above program inner loop is executed 3 times for every iteration of outer loop

so total iteration are 9. Its means that printf statement repeated 9 time and “ Hello C”

is printed on the screen 9 times.


Array

Array is collection of variable, which are same in nature and store in contagious

memory location. In simple word we say that array is collection of similar data

element, which are, store in continues memory location with a single name.

We take an example to understand array. If we want to store the marks of 100

student in memory then we have two way.

First we declare 100 variables and store the marks.

Second is we declare a single subscripted variable which store the marks of 100

Student.

Of course second one is best way for-storing these types of values.

Subscripted variable:

it is the variable, which represent the individual element of array. It is use to access

and manipulate the data element of array.

Individual array elements are identified by an integer index (subscripted value). In C

the index begins at zero and is always written inside square brackets.

There are two-type array used in C-Language

 One Dimensional Array

 Two Dimensional Array

0ne Dimensional Array (Linear array)


A linear array is also called one-dimensional array. The entire element stored in

shape of vector means in one row or one column. The elements of the array stored

respectively in successive memory locations. In linear array each element of an

array is referred by one subscript.

Declaration of Array

Array is declared as we declare simple variable in the beginning with declaration

statement.

Syntax: Data type array name [size of array] [=values]

Data type is any valid C data types like integer, character etc.

Array name is any valid variable name.

Size is total length of array.

Values are optional we specify the value of each element of array at time of

declaration of array.

For example
int num[3]={2,5,7];

2 , 5 and 7 are given 3 subscripted variable such that

num[0]=2

num[1]=5

num[2]=7

Example of array
main()
{

int st[5] ;

printf(“ Enter the marks of 5 student \n") ;

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

scanf( "%d " , &st[ i ]) ;

clrscr( ) ;

printf( “ Your entered List is " ) ;

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

printf( “ %d “, st[ i ] ) ;

getch ( ) ;

Above program gets the marks of five students and then after getting marks clear the

screen and then print list of all the marks that you entered.

Tow Dimensional Array:

When data are store in more then one row or more then one column then this type of

data structure is called Two-dimensional array. In math we use matrix, in word

processing we use table and in programming we represent these two as Two-

Dimensional array.

Data elements are store or access in two-dimensional array with the help of two-

subscripted variable.
 

Declaration of array:

Tow Dimensional Array is also declared as we declare simple variable in the

beginning with declaration statement.

Syntax:

Data type array name[R][C] [=values]

Where R is total number of rows

C is total number of column

And R * C will give the total length of array.

For example

Int num [3] [3]

This declaration reserves 3 *3 =9 memory location in computer memory.

 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2

Programming Example:

 main ( )

int number [3] [3] , I , j ;

clrscr() ;

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

for( j=0 ; j < 3 ; j++)


scanf( " \n %d ", &number[ I ][ j ] ) ;

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

printf(" \n " );

for(j=0 ; j < 3 ; j++)

printf( “%d “ , number[ i ] [ j ]);

getch( ) ;

This program gets the number for matrix and then print in special form of matrix.

Like that

0,0 0,1 0,2

1,0 1,1 1,2

2,0 2,1 2,2

String Processing
Character Array (String )

When characters store in array (in Consecutive memory location) then it is called

string.

A string is a sequence of characters. Any sequence or set of characters defined

within double quotation symbols is a string constant. In “ c “ it is required to do some

meaningful operations on strings they are:


 Reading string displaying strings

 Combining or concatenating strings

 Copying one string to another.

 Comparing string & checking whether they are equal

 Extraction of a portion of a string

The last character of the character array is NULL character. when we enter a string

then each and every character take place in the array and when we press enter key

then a NULL character will place in the end of the string which tell that this is end of

the array.

For example:

Char name[ ]={ “T “, "O", "Q" , "E", "E", "R", "\0"}

Where "\0" is NULL Character.

Null Character play important role in string because this is only way which tell that

where the string is end.

Then the string name is initializing to “ Toqeer “. This is perfectly valid but C offers a

special way to initialize strings.

The above string can be initialized char name[ ]=”Toqeer”; The characters of the

string are enclosed within a part of double quotes. The compiler takes care of storing

the ASCII codes of characters of the string in the memory and also stores the null

terminator in the end.

On the other hand when we print the string value then we use %s format specifier

and there is no need for specify the index value of array.

Printf( "%s " , name)


Example:

#include<iostream.h>

#include<stdio.h>

#include<conio.h>

void main()

char name[10];

clrscr();

scanf("%s",&name);

cout<<name;

getch();

#include<iostream.h>

you can also use gets( ) and puts ( ) function for string processing

main()

char month[15];

printf (“Enter the string”);

gets (month);

puts(“The string entered is “,month);


puts(month);

getch( );

Two Dimensional Character Array

As we now that character array actually represents the string values. So when we

declare any string variable this variable already a one dimensional character array.

And when we want to store more then when string values we declare two-

dimensional character array.

In two-dimensional array subscript is play very important role.

When we declare

Char name[25][3];

Where first subscript value 25 means that every value in this character array have

maximum 25 character and 2nd subscript 3 tell that only three string values store in

this array.

For example :

char I , name[25][5];

clrscr( ) ;

printf ( "Enter five name \n ");

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

gets(name[ i ]);
for(i=0 ; i<=4 ; i++)

puts(name[ i ] );

getch( ) ;

In this example when we get name then we don't mention the first subscripted

Variable as we use gets (name [ i ] where [ i ] represent name [0], name [1], .name

[3], name[4] means that name at first location name, 2nd location name, 3rd location

name, 4th location name and 5th location name.

What is Function in C Language?

A function in C language is a block of code that performs a specific task. It has a

name and it is re-usable i.e. it can be executed from as many different parts in a C

Program as required. It also optionally returns a value to the calling program.

In simple word we suppose you have a task, which is always performed exactly in

the same way. Like monthly service of the motorbike. When you want it to be done,

you go to the service station and say "its time of service do it now". You don't need to

give instructions, because mechanic knows his job.

In the same way when we have some kind of work, which performs always in same

way like that factorial of the number then we only, tell the number a function return

the factorial.

Function in a C program has some properties discussed below.


 Every function has a unique name. This name is used to call function from

“main()” function or for any where. A function can be called from within

another function.

 A function is independent and it can perform its task without intervention from

or interfering with other parts of the program.

 A function performs a specific task.

 A function returns a value to the calling program.

The C function has three different parts.

1. Function declaration

2. Calling function

3. Function Definition

1) Function declaration: -

Function declaration is also called prototype. This is one line statement and always

written before the declaration of main( ) function. Its consist on name, type of the

function and arguments.

 Where type represent the data type returned by the function.

 Name is any valid names that represent the function.

 Specify the type parameters, which are provided to function. If more then one

parameters are used then commas separate them.


 

Where void means this function does not return any value and no values is passed

to this function.

Int sum (int x, int y);

Hare int means that this function returns integer value. And two integer values

passed to this function.

2) Calling Function: -

We can call function any where form any function. For this purpose we use calling

statement.

Syntax:

Variable name = function name ( argument ) ;

èWhere variable name is optional if function return any value then we give variable

name that store the returning value.

èArguments are those variables, which represent the values, which passing to

function.

3) Function Definition: -

Function Definition is actually the function, a task that is performed when we call this

function. Function definition is self-alone single program always written as we write

main ( ) function. Function Definition is written any where after the main function.

For Example

In following program we pass a number to function that calculate the factorial and

print the answer.


For example:

Advantages of using functions:

There are many advantages in using functions in a program they are:

 The length of the source program can be reduced by using functions at

appropriate places.

 A function may be used later by many other programs this means that a c

programmer can use function written by others, instead of starting over from

scratch.
 A function can be used to keep away from rewriting the same block of codes

which we are going use two or more locations in a program.

 Debugging is easier.

 It is easier to understand the logic involved in the program.

 Testing is easier.

 Recursive call is possible.

 Irrelevant details in the user point of view are hidden in functions.

 Functions are helpful in generalizing the program.

Recursion:

When a function call its self in its body then this process is called recursion and this

function is called Recursive function, sometime it is also called Circular definition.

Following program give description about recursive function. N this program we

calculate the factorial with the help of recursive function.


Passing Argument to function

There are two type of passing argument to function:

Pass By Value:

We take an example to understand this mechanism.

main ( )

int b = 10;

square (b);

void check (int n)

//body of function

printf ( “ %d” , n * n ) ;

In this function, ‘n’ is a parameter and ‘b’ (which is the value to be passed) is the

argument. In this case the value of ‘b’ (the argument) is copied in ‘n’ (the parameter).

Hence the parameter is actually a copy of the argument. The function will operate

only on the copy and not on the original argument. This method is known as PASS

BY VALUE.

Call by Reference:
When we pass address to a function the parameters receiving the address should be

pointers. The process of calling a function by using pointers to pass the address of

the variable is known as call by reference. The function which is called by reference

can change the values of the variable used in the call.

main ( )

int n = 10;

square (&n);

void square (int *x)

printf ( “ %d” , (*x) * (*x) );

As you can see the result will be that the value of a is 100. The idea is simple: the

argument passed is the address of the variable n. The parameter of ‘square’ function

is a pointer pointing to type integer. The address of n is assigned to this pointer. You

can analyze it as follows: &n is passed to int *x, therefore it is the same as:

Int * x = &n ;

This means that ‘x’ is a pointer to an integer and has the address of the variable n.

Within the function we have:

*x = (*x) * (*x) ;
* (star symbol ) when used before a pointer will give the value stored at that

particular address.

Type OF Function:

We have mentioned earlier that one of the strengths of C language is that C

functions are easy to define and use.

C functions can be classified into two categories, namely:

 Library functions

 User-defined functions

Main ( ) is an example of user defined function. printf and scanf belong to the

category of library functions.

The main distinction between user-defined and library function is that the former

are not required to be written by user while the latter have to be developed by the

user at the time of writing a program. However the user defined function can become

a part of the C program library.

These are also called built in function. When we use these types of functions then

often we include some headers files. Such that when we use sqrt ( ) function which

calculate the square root of the number then we include the math.h header file.

C program uses both built in function and function (which is also called user defined)

built in function means the declaration and the compiler already knows definition of a

function.

User defined function) means user is going to declare and define that function in the

program.function name is also user defined.


Simply, the library functions are standard functions within C-Language library

(already exist), but User defined function are functions that created by the user.

For example:

# include <math.h>

Some Built In Function


String Function:

Before using following function we #include <string.h>

Strlen ( ) Function: -

Description

The strlen function computes the length of the string s.Example 1:

Syntax :

Strlen(String constant / string variable)

Example:

printf("%d",strlen("Toqeer"));

Return 6

Strcpy ( ) Function: -

Description

The strcpy functions copy the source string to destination (including the terminating '\

0' character.)
Syntax:-

Strcpy(source string, String Variable)

Example:

char name1[10];

char name2[10];

scanf("%s",name1);

strcpy(name2,name1);

printf("\n Your name is %s",name2);

Strncpy ( ) Function: -

Description

The strncpy functions copy the given number of character from source string to

destination.

 Syntax:-
Strncpy(source string, String Variable, n[number of the character

to be copied)

Example:

int main()

char name1[10];

char name2[10];
scanf("%s",name1);

strncpy(name2,name1,2);

name2[2] = '\0'; /* Add the required NULL to terminate the copied string */

printf("\n Your name is %s",name2);

 return 0;

Strcat ( ) Function: -

Description

Strcat function append the one string to other string.

 Syntax:-

Strcat(S1 , s2 )

Example:

int main()

char str1[ ] = "This is ", str2[ ] = "learninghints.com";

//concatenates str1 and str2 and resultant string is stored in str1.

strcat(str1,str2);

puts(str1);

}
The Output is “This is learninghints.com”

Strncat ( ) Function: -

Description

Strcat function append the specify number of the character from on e string to other.

Example:

If s1=”Toqeer” and s2 =”Shah khan”

int main ( )

char str1[ ] = "This is ", str2[ ] = "learninghints.com";

 //concatenates str1 and str2 and resultant string is stored in str1.

 strcat(str1,str2);

 puts(str1);

srrcmp ( ) Function: -

Description

strcmp compare two string if they match with each other its return zero (0). If s1 > s2

its return +v2 number else return –ve number.

Syntax:

Strcmp(s1, s2)
Exapmle:

int main()

char str1[ ] = "This is ", str2[ ] = "learninghints.com";

cout<<strcmp(str1,str2);

Numeric Function

Include Library: stdlib.h

ABS( ) Function:

This function return the absolute value of the given signed value.

Syntax:

ABS(numeric constant/ numeric variable/ expression)

 Example:

 Int n = -8

Printf("%d" , abs(n)); èThe result of this statement is 8.

Sin( ) Function:

Sin () function return the sin value of any given value.

Syntax:

sin(number constant / number variable)

cos( ) Function:
cos ( ) function return the cos value of any given value.

Syntax:

cos(number constant / number variable)

This function returns the Tangent value of any given value. Min() Functien:-

min ( ) Function:

This function returns the minimum value from the given list.

 Syntax:

 Min(value1, value2, ...................)

For example:

cout<<min(1,2) ;

Return 1

max() function:

This function returns the maximum value from the given list.

Syntax:

 max(value1, value2, ...................)

For example:

cout<<min(1,2) ;

Return 1

pow() Function:
This function is used to calculate the power of the given value.

Syntax:

Row ( X , N)

Where X is base and N is power.

For example:

#include<bits/stdc++.h>

cout<<pow(4,2); 

Return 16

Sqrt ( ) Function:

This function calculate the square root of the given value.

Syntax:

Sqrt ( numeric value)

Example:

#include<bits/stdc++.h>

cout<<sqrt(4); 

rand function : -

rand will generate a random number between 0 and 'RAND_MAX' (at least 32767).

Syntax:

 rand( ) ;
Example:

printf(" %d \n", rand());

srand ( ) Function:

Srand will seed the random number generator to prevent random numbers from

being the same every time the program is executed and to allow more pseudo-

random number.

Example :

Following program generate 10 Random Number from 0 to 100

srand(time(0));

for(int i = 0; i<5; i++)

printf(" %d \n",rand());

hex( ) Function: -

Convert an integer number (of any size) to a hexadecimal string. The result is a valid

Python expression

Example:

int n = 5895;

std::cout << std::hex << n << '\n';

round( ) Function: -
Return the floating point value x rounded to n digits after the decimal point. If n is

omitted, it defaults to zero. The result is a floating point number.

Syntax:

Round ( x [ , n ] )

int main()

float x = 13.87;

int result;

result = round(x);

cout << "round(" << x << ") = " << result << endl;

return 0;

Character Function

Isdiqit ( ) Function:

This function determine the nature of the given character, whether the given

character is digit or not. If the given character is digit then its return any +ve number

otherwise its return 0.

Syntax:

Isdigit ( character constant / character variable)

int main()
{

char c;

c='5';

printf("Result when numeric character is passed: %d", isdigit(c));

return 0;

Issupper ( ) Function:

isupper() function in C programming checks whether the given character is upper

case or not. isupper() function is defined in ctype.h header file.

Syntax:

isupper (character constant or character variable)

int main()

char ch='X';

 if (isupper(ch))

printf("\nEntered character is uppercase character");

else

printf("\nEntered character is not uppercase character");

return 0;

}
Isspace( ) Function:

This function is used to check if the arguement contains any whitespace characters.

There are many types of whitespace characters in c++ such as:

 ‘’- “Space”

‘\t’ – Horizontal tab

Syntax:

lsspace(character constant or character variable)

int main()

char ch = ' ';

if (isspace(ch))

 printf("\nEntered character is space");

else

 printf("\nEntered character is not space");

Output :

Entered character is space

isalpha( ) Function:
This function determine, whether the given character is alphabet or not. If the given

character is alphabet then its return 1 otherwise 0.

Syntax:

isalpha ( character constant or character variable)

int main()

char ch='a';

if (isalpha(ch))

 printf("\nEntered character is Alphabatic");

else

 printf("\nEntered character is not Alphabatic");

return 0;

Structures in C

Structure is a user-defined data type in C language which allows us to combine data

of different types together. A simple variable can store a single value. And an array

stores the more then one value of similar data item in consecutive memory locations.

But if we want to store the more then one dissimilar data element in array this is not

possible.

For example if we want to store the information about book, which contain name of

the book (String value), Price of The book (float value) and page of the book (integer
value). This is not possible in array. C provides us an other solution to solve this

problem is called structure.

Declaration of Structure in C Program

Structure may be declared local to function in very start of the function. struct

keyword is used to define a structure. struct defines a new data type which is a

collection of primary and derived data types.

Syntax of declaration of structure:

Struct Structure- Name

Varaible Name Data type ;

Varaible Name Data type ;

};

After this we can define object variable of this structure:

Struct Structure-Name Object Variable-Name

Following program clear the concept of structure.

main ( )

struct book;

char name[50] ;

int page ;
int price ;

};

struct book b;

b.name=”Visual Basic”;

b.page=100;

b.price=150;

printf(“Book name=%s” , b.name);

printf(“Total pages= %d \n”, b.page) ;

printf(“Price of the book =%d”, b.price);

getch();

Structure Array

When we want to store the more then one element of structure data type then we

use structure array. For this purpose we use same method of declaration of structure

only change made in object variable declaration.

In simple structure we declare single object variable but in case array we declare

array of object variable.

Following example is clear picture of our above story.

Following program clear the concept of structure.

#include <iostream>

#include <conio.h>
#include <stdio.h>

struct Student

char name[50];

int page;

int price;

};

int main()

struct Student b[3];

int i;

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

printf("enter the Name of The book \n");

scanf("%s",b[i].name);

printf("Enter the pages \n") ;

scanf("%d", &b[i] .page);

printf("Price of the book \n");

scanf("%d" , &b[i].price);

}
for(i=0; i<=2 ;i++)

printf("Book name=%s ,",b[i].name);

printf("Total pages= %d ,", b[i].page) ;

printf("Price of the book =%d \n", b[i].price);

return 0;

POINTERS

Pointer is a way of accessing a value, which is stored in memory with out referring to

the variable name directly. Pointer refers the address of the variable.

Pointer variable:

In c a pointer variable that points to or references a memory location in which data is

stored. Each memory cell in the computer has an address that can be used to

access that location so a pointer variable points to a memory location we can access

and change the contents of this memory location via the pointer.

For example:

int *K ;

Where K is pointer variable, which store the address of any other variable. When we

declare variable then three type of information about that variable take place.
 Reserve space in memory to hold the integer.

 Associate a name with this memory.

 Store the value at this location.

For example:

Pointer declaration:

A pointer is a variable that contains the memory location of another variable. The

syntax is as shown below. You start by specifying the type of data stored in the

location identified by the pointer. The asterisk tells the compiler that you are creating

a pointer variable. Finally you give the name of the variable.

type * variable name

Example:

int * ptr ;

float *string ;

Address operator:
Once we declare a pointer variable we must point it to something we can do this by

assigning to the pointer the address of the variable you want to point as in the

following example:

Ptr = & n ;

This places the address where n is stores into the variable ptr. If n is stored in

memory 10101 address then the variable ptr has the value 10101.

if we want to print the value of n then we use following statement.

Printf(" % d " , n ) ;

It will display 10 on screen.

But if we give instruction in such way that print the value at address 10101 then

result will be same. 10 will display on the screen.

For example

Printf(" %d ", &ptr);

If we want to display only the address of n then we use following statement

Printf ( “ % u” , ptr)

where ptr is a pointer variable which store the address of N.

You might also like