C Concepts

157

description

Concepts of C Languages, Understanding C language with diagrams

Transcript of C Concepts

Page 2: C Concepts

IndexingChapter 1: C Introduction

Data type in C language Range of data Constants,Varaibles and keywords Identifiers Comments in C Operators Precedence and Associativity rules Assignment Operator Arithmethic Operator Relational Operator Equality Operators Logical Operators Conditional Operators Short Circuit evaluation of Conditional AND and OR operator Increment and decrement operator Pseudo Code, Algorithm and Flow chart

Chapter 2: Control Statements

Conditional Statements If If else Bullet Points Nested if else Ladder if else Switch statements Bullet Points break keywords Conditional Operator Bullet Points

Chapter 3 : Iterative Statements

The Loop While Loop For Loop Bullet Points Do While Loop Bullet Points Control transfer Statements

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 3: C Concepts

Break Continue

Data type revisited Integers ,Short and Long Integers, signed and unsigned Character : Unsigned and Signed

Chapter 4: Functions

What is function Why used function Function signature Input argument of function Return value in function function calling call by value compiter looks in call by value Call by reference Pointer Declaration of pointer variable Initialization of pointer variable Back to call by reference concept Function recursion How to write recurion program Bullet Points

Chapter 5: Arrays

What is Array Declaration of Array How to initialize an array

Direct Initialization Using loops

Accessing Array element values Using indexed values Using loops

Important Points Arrays and functions Pointer Arithmetic passing Array in function Two Dimensional Array Declaration of 2-D array Initialization of 2- D array

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 4: C Concepts

Strings Standard String library Functions strlen function and logic for creating own function strcmp function and logic for creating own function pointer to a constant and constant pointer strcpy function and logic for creating own function

Chapter 6: Structure

what is Structure structure declaration Bullet Points Memory Requirement to store structure variable Bullet Points Initializing structure variable

Initializer list Initialize variable Using input library function

Accessing Structure variable: Memory Allocation for structure Structure Array Structure Pointer

Chapter 7: File Handling

File operation functions in C Defining and Opening a File

fopen() function mode of file

Closing a File Reading and Writing character in file

getc() function putc() function fgetc() function fputc() function

Reading and Writings Strings in/from file

fgets() function fputs() function

Reading and Writing other data types in file

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 5: C Concepts

fprintf() function fscanf() function

file reading program file writing program

Chapter 8: Command line arguments and Dynamic Memory Allocation

program lists difference between

break and continue while and do while pointer and array structure and union malloc and calloc

Chapter 1 : C Introduction

Programming languages are language which computer can understands and programs are the series of instruction to perform some task.So before starts C language, it is very important to understand the concept of langauges.

There are different types of languages

Machine Language : Machine language is a sequence of numbers, for everything ,there is a number in machine language , for character there is a

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 6: C Concepts

number ,and for names which are combination of characters ,there is also a number and truly speaking ,computer understands only Machine Language.Machine Language is the only language which our processor can Understand.

Assembly Language : Assembly language is an abstraction for machine language. Writing code in the form of numbers is much more difficult as compare to remember some instruction for that number. So Assembly Language provides some instruction which is used to perform task, and there is Assemble, a tool ,which converts these instruction in Machine language ,so that Machine understands them.

Intermediate Language(Procedural Language) : These language provides much greater abstraction for Machine language. In procedural language ,we don’t require to memorize the instruction ,instead of instruction ,it provides rules for creating instruction.In Intermediate Language,there is a tool, called compiler ,which converts these grammer in Machine Language. C language comes under this category of language.

C is a language for small, fast programs.The C language is designed to create small, fast programs. It’s lower-level than most other languages; that means it creates code that’s a lot closer to what machines really understand.C language is developed by dennis Ritchie.

C is used where speed, space, and portability are important. Most operating systems are written in C. Most other computer languages are also written in C. And most game software is written in C.

Dennis Ritchie introduced three types of data initially, integer type data means numeric value that don’t have fractional part, floating value that have fractional part and character values which have single alphabet. All three are datatypes in c .

So , there are three types of datatype in c

1. Integer data type2. Float data type3. Character data type

All three types are already defined in c , so we called it primitive data types or primary data types. Data types which programmer creates for writing program are called secondary data types or user defined datatypes.

As shown in the diagram , there are six primary data types , out of which short,int and long are Integer data type and float and double are flaoting data types.char is for character data type.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 7: C Concepts

As data type is used to inform the compiler which type of value we are going to used , so there is some memory space is required to store such value, these memory space is different for each data type. Required memory space is dependent on the compiler ,means memory required to store a variable is compiler dependent , but for now , we see the memory spaces for the Turbo C compiler.

Range of Integer Values

Data Type

Width (bits)

Minimum value MIN_VALUE

Maximum value MAX_VALUE

short 16 -215 (-32768) 215-1 (+32767)

int 16 -215 (-32768) 215-1 (+32767)

long 32 -231 (-2147483648) 231-1 (+2147483647)

float 32 3.4*10e-38 3.4*10e38

double 64 1.7*10e-308 1.7*10e308

char 8 -27 (-128) 27-1 (+127)

Learning ranges for integer and character type is stupidity, better know how to derive it.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 8: C Concepts

Computer understands only Machine language,which is in 2’s number system means it have only two values : either 0 or 1. Combination of 0 and 1 is used to represent different things in Computer. Individual 0 0r 1 is called a bit. Combination of 4 bit is called nibble and 8 bit is called byte.Suppose if we have a 4 bit to represent a integer number and each bit can have value either 0 or 1 (only two state),then according to formula ,we have total possible values are 2power4 = 16 as shown in diagram.So using 4 bit ,we can represent number from 0 to 15 (total 16),Bit pattern for writing binary number for the decimal is

If we want to represent 10, then get the nearest smallest value from above diagram, 8 in our case before 8 is less than 10, and we know we require 2 more for 10 , so choose 2 also. So we choose 8 and 2 , mark it with 1 and rest all bits mark it with zero. As we have 4 bits so binary equivalent for 10 is 1010.

As int is 16 bit in turbo c , so total values that we can represent using 16 bit is 2pow16 = 65536,but as we know int can be negative also , so we divide this value by 2, so 65536/2=32768. So half values are used to represent negative values and half is used to represent positive values.

-32768 ---------------------1,0,1,---------- ------------- 32767 (0 added)

As 32768 is equivalent with 2power15, so we can also write this range as:

-215 (-32768) ------------------------------------------------215-1 (+32767)

So general formula is

-2numberofbits-1 -------------------------------------------------2numberofbits-1 -1 (+32767)

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 9: C Concepts

In a similar way, we can calculate the values for short, long and char also. As Float data types also have fractional part, so some bits are used to denote the fractional part. So above method is not for float values.

Constants, Variables and Keywords in c

A constant is an entity whose value is fixed, means value doesn’t change in the program whereas variables value can change in the program. We can define the variable by using data types.

int i;

it means i is a variable of type int, means in i we can store integer value and this value we can change multiple times throughout the program. Constants are fixed values.

Keywords are the reserved words whose definition (working) is already defined in c. There are 32 keywords which have reserved in the c library. Keywords cannot be used as variables. List of c keywords are as:

Identifiers

Identifiers are the names that are given to various program elements such as variables, symbolic constants and functions.

Identifier can be freely named, the following restrictions.

Alphanumeric characters ( a ~ z , A~Z , 0~9 ) and half underscore ( _ ) can only be used.

The first character of the first contain letters ( a ~ z , A~Z ) or half underscore ( _ ) can only be used.

Case is distinguishable. That is, word and WORD is recognized as a separate identifier.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 10: C Concepts

Reserved words are not allowed. However, part of an identifier reserved words can be included.

Maximum length of variable name is compiler dependent, but for latest turbo C compiler, it is 32 characters.

Here are the rules you need to know:

1. Identifier name must be a sequence of letter and digits, and must begin with a letter.

2. The underscore character (‘_’) is considered as letter.

3. Names shouldn't be a keyword (such as int , float, if ,break, for etc)

4. Both upper-case letter and lower-case letter characters are allowed. However, they're not interchangeable.

5. No identifier may be keyword.

6. No special characters, such as semicolon, period, blank space, slash or comma are permitted

7. Maximum length for a identifier is 32 words

Examples of legal and illegal identifiers follow, first some legal identifiers:

float _number;float a;int this_is_a_also_a_name;

The following are illegal (it's your job to recognize why):float :e;float for;float 9PI;float .3.14;float 7g;

Comments in C

A program can be documented by inserting comments at relevant places. These comments are ignored by the compiler. It is not considered as a coding part of a project.

C provides two types of comments

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 11: C Concepts

• Single Line comment

• Multi line comments or Block Comment

Single line comments

Single line Comments is used to comment a single line in a program. Single line comment syntax is

// this comments ends at the end of this line.

MultiLine Comments

Multiline comments can span several lines. Such a comments starts with /* and ends with */.

/* A comment

On several lines

*/

OPERATORS

Operators are the symbols which is used to perform some tasks on some values. So we can say operators are used to perform some operations in c language. C language provides different types of operators. There are 45 operators in C language. Values on which operators operates is called operands for the operator. Some operator requires two operands for operation, these types of operators are called binary operator.

Precedence and Associativity Rules for Operators

Precedence and Associativity rules are necessary for the deterministic evaluation of the expression. For example if we have the below expression

int a = 5+4*5;

it can be understand as (5+4) * 5 or 5 + (4*5). In both cases the value for the variable a is different, so to avoid such type of ambiguous result, C provides the Associativity and precedence (priority) rules on operators.

Precedence rules are used to determine which operator should be applied first if there are two operators with difference precedence. Operator with the highest precedence is applied first. Precedence for each operator is study during the explanation of operator in this chapter later.

Associativity rules are used to determine which operator should be applied first if there are two operators with the same precedence.

Left Associativity implies grouping from left to right.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 12: C Concepts

e.g. 1+2-3 if it applies left Associativity then it is considered as

((1+2)-3)

Right Associativity implies grouping from right to left.

e.g. 1+2-3 if it applies right Associativity then it is considered as

(1+(2-3))

Note : Both these rules are decided by compiler of language.

Simple Assignment Operator (=)

Assignment operators assign the right hand side value (expression) of = to the left hand side of variable. Assignment operator has the following syntax

<Variable>=<expression>

Note:

• Expression value is calculated first, and then the result of expression is assign to variable.

• Assignment operators = writes over the previous value of the destination variable

For Ex: suppose if we have int i=5;

In the next line ,Let we write i=5+4;

Then i becomes 9 , overwrites the 5.

• The destination variable and source expression must be type compatible.

For Ex :

int i=5; //fine

int j=5.5;//not fine because 5.5 is a float value, integer datatye is not able to take float values , so we need type casting.

• Precedence of Assignment operator is minimum in all operators except comma operator (,).

• Associativity of Assignment operator is right to left.

Ex : int i,j;

i=j=10; //(i=(j=10))

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 13: C Concepts

so Associtivity is right to left , so first 10 is assign to j , then j value is assign to i .

i=j=10; //Mutiple Assignment in same line.

Arithmetic operators

Arithmetic operators are used to constructs the mathematical expression as in algebra.

Ex: int a =5;

int b =10;

int c = a+b;

In above Example + operator is used to add two operand . if any one of two is of string type then it concatenates the two operands.

Arithmetic Operators

Binary * Multiplication / Division % Remainder

  + Addition - Subtraction    

Note:• All the arithmetic operators are binary operators. They require two

operands as shown in diagram. • All arithmetic operators have left to right Associativity.• Precedence of arithmetic operators are shown in operators diagram

above. Multiplication, division and Remainder (modulus) operator have higher precedence then addition and subtraction. Operators in the same row have equal precedence in above diagram.

• If there are different precedence operators in an expression, then we applied the precedence rules for avoiding undeterministic behavior .

• If there are same precedence operators in an expression , then we applied the associativity rules for avoiding underministic behaviour.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 14: C Concepts

Multiplication Operator: *

Multiplication operator * multiplies two numbers.

int sameSigns = -4 * -8; // result: 32double oppositeSigns = 4.0 * -8.0; // result: -32.0int zero = 0 * -0; // result: 0

Division Operator: /

The division operator / is overloaded. If its operands are integral, the operation results in integer division.

int i1 = 4 / 5; // result: 0int i2 = 8 / 8; // result: 1double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value 1.0.

Integer division always returns the quotient as an integer value, i.e. the result is truncated toward zero. Note that the division performed is integer division if the operands have integral values, even if the result will be stored in a floating-point type.

If any of the operands is a floating-point type, the operation performs floating-point division.

double d2 = 4.0 / 8; // result: 0.5double d3 = 8 / 8.0; // result: 1.0double d4 = 12.0F / 8; // result: 1.5F

double result1 = 12.0 / 4.0 * 3.0; // ((12.0 / 4.0) * 3.0) which is 9double result2 = 12.0 * 3.0 / 4.0; // ((12.0 * 3.0) / 4.0) which is 9

Remainder Operator: %

In mathematics, when we divide a number (the dividend) by a another number (the divisor), the result can be expressed in terms of a quotient and a remainder. For example, dividing 7 by 5, the quotient is 1 and the

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 15: C Concepts

remainder is 2. The remainder operator % returns the remainder of the division performed on the operands.

int quotient = 7 / 5; // Integer division operation: 1int remainder = 7 % 5; // Integer remainder operation: 2

Relational operators

a < b a less than b?

a <= b a less than or equal to b?

a > b a greater than b?

a >= b a greater than or equal to b?

• Relational operators are used to compare(relate) the two operands, All the relational operators returns integer value in C.

• Relational operators are binary operators means they require two operands. And there operands are numeric expressions.

• Relational operators are non associative.

• Relational operators have precedence lower than the arithmetic operators but higher than assignment operator.

True in C means 1 and false in C means 0.

Equality Operator(==)

Equality Operators

a == b a and b are equal? That is, have the same primitive value? (Equality)

a != b a and b are not equal? That is, do not have the same primitive value? (Inequality)

The equality operator == and the inequality operator != can be used to compare primitive data values.

Note:

1. Equality operators have precedence less than the relational operators but greater than the assignment operator.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 16: C Concepts

2. Associativity for equality operators are left to right.

Ex:

double hours = 45.5;

boolean overtime = hours >= 35.0; // true.boolean order = 'A' < 'a'; // true. It compares the integer value for A and a . A = 65 and a=97 , so condition is true.

Boolean Logical Operators: !, ^, &, |

Boolean logical operators include the unary operator ! (logical complement) and the binary operators & (logical AND), | (logical inclusive OR), and ^ (logical exclusive OR, a.k.a. logical XOR). Boolean logical operators can be applied to int operands, returning a int value. The operators &, |, and ^ can also be applied to integral operands to perform bitwise logical operations

Boolean Logical Operators

Logical complement

!x Returns the complement of the truth-value of x.

Logical AND x & y true if both operands are true; otherwise, false.

Logical OR x | y true if either or both operands are true; otherwise, false.

Logical XOR x ^ y true if and only if one operand is true; otherwise, false.

Truth-values for Boolean Logical Operators

x Y !x x & y x | y x ^ y

0 0 1 0 0 0

0 1 1 0 1 1

1 0 0 0 1 1

1 1 0 1 1 0

Note:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 17: C Concepts

• Boolean logical operators have precedence less then arithmetic and relational operator but greater then assignment and Conditional AND and OR operator.

• In evaluation of boolean expressions involving boolean logical AND, XOR, and OR operators, both the operands are evaluated. The order of operand evaluation is always from left to right.

Conditional Operators: &&, ||

Conditional operators && and || are similar to their counterpart logical operators & and |, except that their evaluation is short-circuited. Given that x and y represent values of Boolean expressions, the conditional operators are defined in below table. In the table, the operators are listed in decreasing precedence order.

Conditional Operators

Conditional AND x && y true if both operands are true; otherwise, false.

Conditional OR x || y true if either or both operands are true; otherwise, false.

Unlike their logical counterparts & and |, which can also be applied to integral operands for bitwise operations, the conditional operators && and || can only be applied to boolean operands. Their evaluation results in a boolean value. Truth-values for conditional operators are shown in Table. Not surprisingly, they have the same truth-values as their counterpart logical operators.

Truth-values for Conditional Operators

X y x && y x || y

0 0 0 0

0 1 0 1

1 0 0 1

1 1 1 1

Short-circuit Evaluation

In evaluation of boolean expressions involving conditional AND and OR, the left-hand operand is evaluated before the right one, and the evaluation is short-circuited (i.e., if the result of the boolean expression can be

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 18: C Concepts

determined from the left-hand operand, the right-hand operand is not evaluated). In other words, the right-hand operand is evaluated conditionally.

The binary conditional operators have precedence lower than either arithmetic, relational, or logical operators, but higher than assignment operators. The following examples illustrate usage of conditional operators:

boolean b1 = 4 == 2 && 1 < 4; // false, short-circuit evaluated as // (b1 = ((4 == 2) && (1 < 4)))boolean b2 = !b1 || 2.5 > 8; // true, short-circuit evaluated as // (b2 = ((!b1) || (2.5 > 8)))boolean b3 = !(b1 && b2); // trueboolean b4 = b1 || !b3 && b2; // false, short-circuit evaluated as // (b4 = (b1 || ((!b3) && b2)))

Increment(++) and decrement(--) operators

Increment operators and decrement operators are used to increment and decrement the value by 1.Increment and decrement operators comes in two flavours: postfix and prefix.

Postfix increment operator: post increment operator have the below syntax

i++ uses the current value of i as the value of expression first , then it is incremented by 1.Below diagram explains the post Increment operator.

Pre Increment operator : pre increment operator have the below syntax

++i add 1 to i first , then uses the new value of i as the value for the expression .

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 19: C Concepts

Same story is applicable for the postdecrement and predecrement except it decrements the value by 1.

Representation styles:

Pseudocode

Most software programs are developed using a programming language, like C, C++ or Java. These languages have a specific syntax that must be adhered to when writing program's source code. Pseudocode, on the other hand, is not a programming language, but simply an informal way of describing a program. It does not require strict syntax, but instead serves as a general representation of a program's functions.Since each programming language uses a unique syntax structure, understanding the code of multiple languages can be difficult. Pseudocode remedies this problem by using conventional syntax and basic english phrases that are universally understood. For example, a line of C code may read if (i < 10) { i++; }This could be written in pseudocode as:if i is less than 10, increment i by 1.

By describing a program in pseudocode, programmers of all types of languages can understand the function of a program.Pseudocode is an informal language, so it is mainly used for creating an outline or a rough draft of a program. Because it is not an actual programming language, pseudocode cannot be compiled into an executable program. Therefore, pseudocode must be converted into a specific programming language if it is to become an usable application.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 20: C Concepts

Examples:

1.. If student's grade is greater than or equal to 60

Print "passed"else

Print "failed"

2. Set total to zero

Set grade counter to one

While grade counter is less than or equal to ten

Input the next gradeAdd the grade into the total

Set the class average to the total divided by ten

Print the class average.

3.

Initialize total to zero

Initialize counter to zero

Input the first grade

while the user has not as yet entered the sentinel

add this grade into the running totaladd one to the grade counterinput the next grade (possibly the sentinel)

if the counter is not equal to zero

set the average to the total divided by the counterprint the average

else

print 'no grades were entered'

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 21: C Concepts

Algorithm :

An algorithm is a clearly specified set of simple instructions to be followed tosolve a problem. Once an algorithm is given for a problem and decided (somehow) to be correct, an important step is to determine how much in the way of resources, such as time or space, the algorithm will require. An algorithm that solves a problem but requires a year is hardly of any use. Likewise, an algorithm that requires a gigabyte of main memory is not (currently) useful. So Algorithm is generally measured according to the time and space parameter.

Flow Chart :A flow chart is a graphical or symbolic representation of a process or algorithm. Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction.

Common Flowchart Symbols

Different flow chart symbols have different meanings. The most common flow chart symbols are:

Terminator: An oval flow chart shape indicating the start or end of the process.

Process: A rectangular flow chart shape indicating a normal process flow step.

Decision: A diamond flow chart shape indication a branch in the process flow.

Connector: A small, labeled, circular flow chart shape used to indicate a jump in the process flow. (Shown as the circle with the letter “A”, below.)

Data: A parallelogram that indicates data input or output (I/O) for a process.

Document: Used to indicate a document or report (see image in sample flow chart below).

A simple flow chart showing the symbols described above can be seen below:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 22: C Concepts

Programming experience

1. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

2. WAP in which principal, rate and time values are passed by user and we have to calculate the simple interest on these values:

Formula : interest= (principal* rate*time )/100;

3. If the marks obtained by a student in five different subjects are input through the keyboard, find out the total marks and percentage marks

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 23: C Concepts

obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

4. If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a program to find the cost price of one item.

5. If a five-digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23402.

6. Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

7. If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint: Use the modulus operator ‘%’)

8. Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

Formula to convert Celsius to Fahrenheit

Tf = (9/5)*Tc+32; Tc = temperature in degrees Celsius, Tf = temperature in degrees Fahrenheit

Formula to convert Fahrenheit to Celsius

Tc = (5/9)*(Tf-32); Tc = temperature in degrees CelsiusTf = temperature in degrees Fahrenheit

Chapter 2: Control Statements

Sometimes there are alternate ways for journey and we have to pick one to proceed with the journey .As shown in diagram , We as a programmer have to decide which way we must choose to get the right solution of the problem .This will depend upon some condition .

For Example : if today is Sunday , lets go for a party .

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 24: C Concepts

Above statement comprises a condition with it . Party is dependent on the day , so there is a condition involve with the statement.

In programming , scenario like this is called conditional scenario .C provides us an efficient mechansims to tackle such scenarios.

1. IF Statement 2. IF Else statements3. Nested IF Else Statement4. IF else ladder5. Switch Statements6. Conditional Operator

Note: 3 and 4 are different ways for if else statements.

If statements are very general statements which are used when we want to do something extra which is dependent on the condition .

As shown in the diagram , if condition is true that are part of if statement then we execute the conditional code ,then continue with the rest of program , and if condition is false then we can skip the conditional code and continue with the rest of program.

Syntax of if

if(condition){// conditional code}//rest of program

If there is only a single statement in if , then we can avoid curly braces.But if conditional code contains more then one statement , then we have to put curly braces for if body. If we forgot , then compiler assumes that the statement followed by if statement is inside if , rest others statement are outside of if statement.There is no statement terminator in if statement ,if we put it ,then compiler will assume that the conditional code for if contains only a ; .

For Example:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 25: C Concepts

#include<stdio.h>void main(){int a=10;if(a>1); // semicolon after if statementprintf(“%d”,a); // printf is consider out of if conditional code}// only statement which is part of if is ;.

If there is two alternatives that is dependent on one condition , then using if is not better choice , so c provides us an alternate which is used to choose between two alternatives . Condition is the part of if statement , else statement don’t have any condition . if condition is true, then statements which is part of if (Statement 1 shown in diagram), executes and else statements skips(statement 2 in diagram) and continue with the code which is mentioned after else body . If condition is false , then if body skips (statement 1), else body executes (statement 2) and continue with the rest of code after else.

So if-else syntax is like this :

Programming Journey

Problem :Suppose we want to check even or odd for the entered number by user .

Solution :

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 26: C Concepts

So using if else we can solve any problem where there are two alternatives and decision is dependent on some condition . Try out : Enter two values and find out which is max between those.

Exercise : 1. Find the max between two integer values using if else2. Write a program which checks the even or odd number, take a number

from user using scanf function.

1. Condition is always with the if statement , if we mention in else , it is compile time error.

2. else statement without if is not possible , there should be if statement for the else but vice versa is not true , means if can come without else.

3. At a time only one alternative will execute , it is not possible to execute statements for both if and else

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 27: C Concepts

4. In condition , we can used Logical operators for more than one condition.

5. Statement between if and else are not allowed.else should come after the if body statements.

6. In reality , there is also an expression instead of condition in if syntax , if the expression returns non zero , then it is consider true and if it is zero , then it is consider false.

7. If expression returns non zero , then if statements executes , and if expression returns zero , then else statements executes .

8. If there is only a single statement in if and else body , then we can avoid curly braces . (preferred : use curly braces for all )

Nested If Else statements

Sometimes there are conditions when we want another if –else inside if or else ,Such type of statements are nested if else statement . if else inside if or/and else is called nested if else.

As shown in above diagram , if first condition (condition-p) is true , then we want to check second condition(condition -q) , if second condition is true then we execute statement 1 and if false , then statement2 , Statement 1 and Statement 2 followed by statement 3 which is the part of outer if , and if condition-p is false , then only statement4 will execute . So in the above diagram , if contains another set of if else , so it is nested if else .In a similar way,else can also have if –else .

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 28: C Concepts

Programming Journey : Take a three integer numbers from user and print which is the maximum between them.

#include<stdio.h>#include<conio.h>void main(){clrscr();int fn,sn,tn,max;printf(“Please enter three numbers \n”);scanf(“%d %d %d”,&fn,&sn,&tn);

// check for max between themif(fn>sn)

{if(fn>tn)max=fn;elsemax=tn;

}else

{if(sn>tn)max=sn;elsemax=tn;

}

printf(“Maximum value is : %d”,max);

}

Exercise :1. Check the minimum

among three float values using nested if else

If Else Ladder

When a series of many conditions have to be checked

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 29: C Concepts

we may use the ladder else if statement which takes the following general form.

Syntax if(condition 1) statement-1; else if(condition 2) statement-2; else if(condition n) statement-n; else default statement;next statement;

This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement – x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.

Example of If-Else Ladder// leap year program using if else ladder#include<stdio.h>#include<conio.h>void main(){clrscr();int year;printf(“please enter the year for which you which you want to check leap: ”);scanf(“%d”,&year);

if(year%400==0)printf(“leap year”);else if(year%100==0)

printf(“not a leap year”);else if(year%4==0)

printf(“leap year”);elseprintf(“not a leap year”);

getch();}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 30: C Concepts

Switch Statements

C switch statement is a multiway decisions that tests whether a variable or expression matches one of a number of constant integer values, and branches accordingly.

This is the flow chart of the C switch statement:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 31: C Concepts

C switch statement syntax:

switch (expression) { case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */ break; ... default: /* execute default action */ break; }

In C switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value, which is returned by expression, must be an integer value otherwise the compiler will issue an error message.

The case constant expression must be a constant integer value.

When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. The break statement is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logic happens.

The default statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.

Example of C Switch Statement

#include <stdio.h>

int main() { int color = 1; printf("Please choose a color(1: red,2: green,3: blue):\n"); scanf("%d", &color);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 32: C Concepts

switch (color) { case 1: printf("you chose red color\n"); break; case 2: printf("you chose green color\n"); break; case 3: printf("you chose blue color\n"); break; default: printf("you did not choose any color\n"); } return 0;}

Conditional Operator This is an alternate way to perform if-else statements in a single line. Conditional operator is a ternary operator. Symbol for the ternary operator is ? :.

Syntax for ternary Operator(condition/expression) ? statement which we want when condition true : statement which we want when false

If condition returns 1 ,or expression returns non zero then statements which are after ? will executed , and if condition returns 0 and expression returns 0 ,then statement after : will executed.

For example, if want to find the max between two numbers then we can used conditional operator instead of if/else

#include<stdio.h>void main(){int fn,sn;printf(“Enter two numbers”);scanf(“%d %d”,&fn,&sn);(fn>sn) ? printf(“%d is greater then %d”,fn,sn) : printf(“%d is greater then %d”,sn,fn);}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 33: C Concepts

1. Conditional operator is an alternate way for if-else statement.2. Conditional operator can be nested like if else, means we can add

another conditional operator after ? and :.3. Conditional operator is ternary operator.4. ; is not required for statements in ?5. Last ; is for statement termination, not for :6. If we add more than one statement for ? and : . we have to add / after

each statement instead of ; which we used in if –else block.

Programming experience

1. While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses.

2. Write a program to check number is even or odd. Number is entered by the user.

3. Find the max value between two integer values. (without else statement)

4. In a company an employee is paid as under: If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary.)

5. find the max between three integer values .(Using nested if else)6. find the max between three integer values .(Using logical operators)7. Any year is entered through the keyboard, write a program to

determine whether the year is leap or not. Use the logical operators 0 and ||.

8. Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters.

C Characters AASCII Values

A – Z

a – z

0 – 9

65 – 90

97 – 122

48 – 57

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 34: C Concepts

special symbols 0 - 47, 58 - 64, 91 - 96, 123 – 127

9. A company insures its drivers in the following cases: − If the driver is married. − If the driver is unmarried, male & above 30 years of age. − If the driver is unmarried, female & above 25 years of age.

In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not.

Try all the Examples in c editor and let me know if any problem you faced , Contact Me : [email protected]

If we want to do same work again and again , then better approach is looping in programming language.Using conditional statements, we can decide which code we want to execute, but using loop statements in our code we can decide how many times we want our code to be executed.

So loops are the solution to do iterative task in programming .

Example : Suppose in a racing track , a racer have to complete the 5 round to finish the race. so each time when he finish the round , an counter indicated in his car indicates the completed round number , and if this number is less then 5 , racer continue with the race.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 35: C Concepts

After he completes the five round , counter indicates that race is finished for you . so the racer can stop the car.

In the above scenario , all time racer will do the same work until number of rounds are not completed ,So scenario like this, we require loops.

In looping there is three important constraints.

1. Racing starting point : Racing starting point means the starting point for our loop, for doing this ,we have initialize a counter , which increments or may be decrements after each iteration.

2. Condition : Racing car continue until they finish five rounds of the track , so we require something that will check each time when racer are on finish time . So we used some condition on the loop counter to check about the continuity of the code .

3. Increment/Decrement : when a round completes we have to increases the counter to the next round value , so we require some mechanism that will increases the counter.

So in English I can express like this .

Start the race In general programming it means we have to initialize the variable.

Check whether it complete 5 round or notIt is equivalent to the checking condition , if condition is satisfied , then continue with the race , else you complete it

Increment if 5 round is not completeThis step is done when we are in the race means when we are not completed the race , each time after round completion ,we increment the counter.

For doing such type of work ,C provides us three types of looping .

While Loop

While loop is most general loop for performing iteration in code, in which we define the loop variable before entering into the loop , condition for the loop is defined during the declaration of while loop. If there is only a single statement in the loop , then we can avoid curly braces for while body , else if there is more than one statement then, we have to put curly

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 36: C Concepts

braces for while body, Counter increment and decrement operations are done inside loop body. Syntax for the while loop is

while(condition/expression){// while loop body// increment and decrement}

So in general while loop look like

Read the below diagram very carefully , it will explain you each and every step for understanding the loop

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 37: C Concepts

For loop :

As we saw in while loop , there are three important parameters for loop

1. Initializing a loop variable2. Condition which evaluates how many time we want to iterate3. Some counter increment or decrement operation

And in loop body we write what we want to execute repeatedly.

In for loop all these concept are merge in a single line , which makes our reading and understanding much more easier , in general, for loop are the most popular among all looping technologies.

This is the flow chart diagram , as in the flow chart

1. Initialization activity is a onetime activity in for loop same as in while loop.

2. Then condition evaluates, if it returns nonzero value, then loop body will execute first, increment of counter will happen after the loop body.

3. When ending curly braces for the loop will come, then execution moves to the increment/decrement operation.

4. Then after again condition evaluates, if it returns non zero then same process proceed, else it is out from the loop and start with rest of code.

For loops makes our understanding of code much easier. We can initialize more then on variable in initialization part of for loop ,

or we can avoid it also We can increment/decrement more than one variable in the increment

section of the diagram

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 38: C Concepts

Loop condition can’t be multiple, we can combine more than one condition using logical operators && and ||.

Each section like initalization, condition , increment are separated using ‘;’ , It is must else compiler raises the compile time error .

Increment section is performed after executing loop body , and after increment again condition evaluation occurs.

For understanding this concepts , there is another diagram

do while loop

Sometimes it is not previously known whether to continue with the loop or not , for example in a program we have to take permission from user to continue , in such scenario if user don’t want to continue we have to skip the loop else we have to continue with the loop .For better understanding , I am trying to take a simple example , think in a program ,we see something like this :

Which Arithmethic Operation you want to perform Please Enter your Choice:

1. Addition of number 2. Subtraction of numbers3. Multiplication4. Division5. Exit

If user enters 1 to 4 , then respective operation will perform , and after operation , same menu will come until user enter 0 for exit .

It means my next working depends on what user enters . so in such cases , we want first this menu will show to the user , then condition evaluation will occur on user input , we will continue or not is decided by the condition result .

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 39: C Concepts

It means first we want to perform loop body at least once so that user can view menu, do while provide us this functionality.

As shown in diagram , first loop body executes for at least once , then after condition will evaluates , if it returns non zero , then continue with the loop , else we are out from the loop

Loops are used to do iterative task in programming There are three important concepts , loop counter , condition , and

loop body. C provides us three types of loops , while , for and do- while In while , counter is initialized before using while keyword , in while

there is condition and after while we mention loop body In for loop , initialization , condition and increment are mentioned in

the same line ,and loop body are after for this line Increment process in for loop are done after executing the loop body After increment , again condition evaluates In do –while , if condition false for the first iteration , then also loop

body will execute for one time do – while is used when it is not predefined ,when will we are out from

the loop means it depends on the user input at run time loop inside loop is allowed ,loop iteration will be equal to the

outerloop*innerloop

Control Transfer Statement

Break

Break keyword is used to come out from the loop , in which it is defined . It is also used in switch condition statements where it is used to avoid the rest of cases .

In general , In loops , if there is some condition satisfied then we want to skip all the remaining iteration of the loop, in such scenario , break keyword is used . Break is used to skip all the iterations and come out from the loop and statements which are after loops will execute.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 40: C Concepts

As shown in the above code , after executing some statements in the for loop , if compiler finds break , it skip the body , and continue with the outside code.

Continue

Continue is used to skip the current iteration of the loop and continue with the next iteration . It is used for skipping the loop iteration .For example , sometimes you want to skip some iteration in a loop , suppose if you want to print numbers from 1 to 100 but you want to skip those numbers that are divisible by 3 , then we can used continue command to skip those iteration for that value is divisible by 3.

for(int i=1;i<=100;i++) { if(i%3==0) continue; printf(“%d”,i); }

Above code will skip all the numbers that is divisible by 3 , and print rest all number from 1 to 100.

Programming experience

1. print the series : 2 4 6 8 10 12 14 16 18 202. print the series : 2 4 8 16 32 64 128 2563. Write a program to reverse a number. Number should be entered

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 41: C Concepts

through keyword.4. Write a program to check the entered number is Armstrong or not.

An Armstrong number is a number such that the sum of its digits raised to the third power is equal to the number itself

5. Write a program to check the given number is palindrome or not.

A palindromic number or numeral palindrome is a number that remains the same when its digits are reversed. Like 16461, for example, it is "symmetrical"

6. Write a program (WAP) to calculate the factorial of entered number.

7. Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

8. WAP to print the below series

***************

***************

* ** *** **** *****

112123123412345

122333444455555

9. WAP to print the below series

* * ** ***** *** **** **************

12345678910

* ** *** **** *****

10. WAP in which you have to show below menu to user :

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 42: C Concepts

Enter your choice :1. Addition of numbers2. Subtraction of numbers3. Division of numbers4. Exit

If user enters 4 , it should exit from the loop , and if user enter other than 4 , then it should ask for two numbers and performs the desired operation , remember after the operation is done , again it show the same menu.

11. WAP to print the series using break statement:1 12 123123412345

12. WAP to print all prime numbers from 1 to 100 using (Hint: Use nested loops, break and continue)

13. Write a program to add first seven terms of the following series using a for loop:

14. Write a program to generate all combinations of 1, 2 and 3 using for loop.

15. Write a program to produce the following output:

16. Write a program to check the entered number is perfect number or not. Perfect number example is 6 , 6 is divided by 1,2,3 and when added it is equal to 6.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 43: C Concepts

17. Write a program to check entered number is strong number or not. Strong number example : 145 --- 1! + 4! + 5 ! = 145

18. Write a program to print Fibonacci series of given range.19. Write a program to print multiplication table from 2 to 10.20. C program to print hello world without using semicolon.21. Write a c program to find out power of number.

Data Type Revisited

In the previous chapters of this book, we read about the primary data types of c language, Not only this, the primary data types themselves could be of several types. For example, a char could be an unsigned char or a signed char. Or an int could be a short int or a long int.

Integers ,Short and Long

As we know the range of integer depends on the compiler, for 16 bit compiler range of integer is -32768 to 32767, and for 32 bit compiler, range of integer is –2147483648 to +2147483647. So According to the range C divides Integer into three parts : short,int, and long. The intention to provide these variation is to provide different integers with different range’s. The Memory requirement for each type is dependent on the compiler but some rules are there which also follows

Short size is never bigger then int Int size is never bigger then long Short is atleast 2 byte big Long is atleast 4 byte big

long variables which hold long integers are declared using the keyword long, as in,

long int i ;long int abc ;

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 44: C Concepts

long integers cause the program to run a bit slower, but the range of values that we can use is expanded tremendously. The value of a long integer typically can vary from -2147483648 to +2147483647. More than this you should not need unless you are taking a world census.

If there are such things as longs, symmetry requires shorts as well—integers that need less space in memory and thus help speed up program execution. short integer variables are declared as,

short int j ;short int height ;

C allows the abbreviation of short int to short and of long int to long. So the declarations made above can be written as,

long i ;long abc ;short j ;short height ;

Naturally, most C programmers prefer this short-cutIntegers, signed and unsigned

Sometimes, we know in advance that the value stored in a given integer variable will always be positive—when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in,

unsigned int num_students ;

With such a declaration, the range of permissible integer values (for a 16-bit OS) will shift from the range -32768 to +32767 to the range 0 to 65535. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise take. This so happens because on declaring the integer as unsigned, the left-most bit is now free and is not used to store the sign of the number. Note that an unsigned integer still occupies two bytes. This is how an unsigned integer can be declared:

unsigned int i ;unsigned i ;

Like an unsigned int, there also exists a short unsigned int and a long unsigned int. By default a short int is a signed short int and a long int is a signed long int.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 45: C Concepts

Character : Unsigned and Signed

Character is also divided as signed and unsigned , but as obvious question is how character can be signed because character is never negative. But In reality for character variables , An equivalent ASCII value for character is store in memory , and ASCII value is an integer value, So if 65 is possible for A , then -65 is also possible, Consider that we divide character into two part: Unsigned char and signed char.

unsigned char ch; //for declaring unsigned char

By default all character are signed character.

Chapter 4: Functions

A function is a piece of code that is used to do some Specific task in programming. So writing different function for each task makes the coding learning and understanding easy , because there is any change if occur in future , we don’t worry about the others functions , only the function which perform that task needs to be change . In C , everything is kept inside the function.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 46: C Concepts

The first function in your program that c compiler runs is main() function ,so in your c code , there should be at least one function and that function should be main(). Without main your code will not execute. main() function is called by the compiler and we only need to define what main will do .

Note: main() is the starting point from where execution of your program starts.

There are three important parts for using functions1. Function declaration2. Function calling3. Function body

Before understanding above steps, lets first understand where we require functions in our code and what is the syntax of functions in c.

Suppose we want to print a series of triangle star three times in our code, so there is lot of approaches to do this

First Approach is write the same code three times because we want same output three times Second Approach write a different function which prints the series, and call that function three times from your function.

Obviously Second approach seems better than first , suppose in future if same series we have to print one more time , using first approach we add extra code in our program but in second approach we only need to call the same function again.

Function Signature

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 47: C Concepts

Function can accept values while calling (when we want our function to be execute) and return values to a caller (when our function is over and we want to return).As shown in above diagram, whenever we want to execute the function , we call it from the main() function (for this time), and when calling function completes its execution , then we back in the main() function(from where we call the function).

While calling we can also pass values to the function , so in function there should be some variables that hold these values , and these variables are called input arguments for the function , we can pass the arguments in function in two ways

Call by value Call by reference

These two concepts will be explained later , for now we only understand how to hold input arguments in the function.

Suppose there is a Add function which adds two integer values and print the result of addition , These two values are passed in the function as an input arguments ,lets look what is the syntax for the Add function

void Add(int a , int b){int c = a+b;printf(“%d”,c);}

int a and int b are two integer variables which hold integer values ,in the above function , Add is the name of the function and in the brackets ,we mention the input arguments . While defining input arguments ,we also mention the data type of arguments. What is ‘void’ here , we understand in the next topic. Variable a ,b and c scope is only in this function , outside the function , a ,b and c are unknown variables.

Example 2 : Try to fill the blanks

void CheckForOddandEven (int number){

}

Above function name is :- …………………………………Input arguments datatype :- …………………………………Inpu argument variable name:- …………………………………

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 48: C Concepts

Return values in function

Sometimes we also want back some values from the function , for example , we have to write a program which calculates the square root of the given number ,so we create a

function with the name sqrt which takes an input arguments (number for that we want square root) , after calculating the square root ,we want the answer back to the caller function , so we used return keyword after calculating the square root and pass the answer using return keyword . return is a keyword , which is used to return some values from the calling function to caller function .After executing the return , rest of the function body is skipped and execution moves to the caller function.

WE HAVE TO MENTION THE RETURN VALUE DATA TYPE IN THE FUNCTION SIGNATURE

Remember the void in the Add function, this void means that function don’t return any value to the caller function,Okay in our square root scenario, function can

produce a int value or may be float value , so its better to return a float from the function ,so instead of void as in add function ,we have to mention float in sqrt function .

float sqrt (int number) {

//logic for square rootreturn sqrtvalue

} So in general function signature is like this :

[return data type] [function name](input argument list){// function body;Return statement ;}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 49: C Concepts

Example : Write a Add function which takes two integer value and return an integer value.

int Add(int a, int b){//function body

}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 50: C Concepts

Function Calling

Function calling means we want to execute the function, As we know main function is called by compiler, means main is the first function which is executed in our program ,what we do if we want to execute another function , we need to call that function . Calling a function is very simple,

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 51: C Concepts

only the function name with the input arguments(without data types) is written in program from where we want to execute the function .

As shown in above diagram, from main() function we call function1() first , as in the function declaration ,there is no input arguments for the function, so we can’t pass any arguments while function calling. After execution of the function1() , it again returns from where it is called.

Function can call another function.

It is also possible to call another function from function . main is also a function in c and as in above diagram ,we call function1,function2 and function3 from main() function. Function1() can also call another function means if we want to call a function 2 from function1 , then we have to call function2 inside function1() , and again after function2 executes if returns to the function1 (from where it is called).

As shown in coin diagram, function calling is similar like this, the Current running function is at the top of the stack, and which calls that function, is at the next to the top function, main is sitting as first coin in the stack. As

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 52: C Concepts

shown in diagram , if we want to pick the last coin ,first we have to remove all the others coin.Function calling is similar like this, main is the first function which calls by compiler, and if main calls another function [suppose Abc()] and that function calls another [suppose xyx()], so xyz() function is at the top of list , and Abc() is the second one and main lies in the last, so first xyz() will execute and returns to Abc() , then Abc() executes and returns to main() , and then main executes , once main() function is over , our program execution also over.

Example : Write a program which reverse the given number using function.

Write this program in your editor and compile it ,you will see that compiler is unable to find the reverseTheNumber() function and starts complaining during compile time, why such error occurs.

This error occurs because we call the function before defining it , as main is the first function which executes and before main it reads the header files definition , when we call the function inside main ,it don’t know about the function ,so it starts complaining about the error . there is two ways to get rid of this problem.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 53: C Concepts

1. Declare the signature before calling the function2. Provide the function body above function from where it is called.

In first solution ,we only define the signature of function above all the functions without providing the function body, so compiler reads the function signature before executing any functions so that when we call the function, compiler knows about the function. Function signature is ended with semi colon.

So in the reverse program, we can define the function signature as :

int reverseTheNumber (int ,int );

this signature tells to the compiler that reverseTheNumber function returns integer value and accepts two integer values while calling , no need to define variable names for the input arguments.

Second solution is much easier , define the function body above the function from where it is called , So in our reverse program , define the reverseTheNumber() function before main() solve the problem.

Call by Value

Lets take an example to understand the concept of call by value.

Predict the output of program : …………………………………………………………..

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 54: C Concepts

Let’s take a look at the program

In above program, we define a variable number inside the function main() and get the value from user and pass it in the function changeTheNumber(), and in that function, we multiply it , and return back to the main() function. Let suppose number is 9, and we want to print 18 in the output, but when we run above program, we get 9 in output.

Compiler looks:

So number is different in main and changeTheNumber function , different means that are stored in different locations and if we change the value of one variable, other variable don’t get reflected, if is something like we have two things which are identical initially and then we make some changes in the one, and expected the identical changes in the second one , it is not possible. Arguments mention in function calling is called actual arguments and in the function body, it is called formal arguments, name of both

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 55: C Concepts

arguments can be identical as shown in above case. Formal arguments take the values of actual arguments and initialize a new variable with that value. This concept is called call by value, only the value is passed while calling a function and it is not reflected in the caller function.

Call by reference(address) : Before we understand the concept of call by address, we must understand the concept of pointers. So lets first cover pointer concept, then continue with call by address concept.

Pointer:

Every variable which we used in program is store in memory. Memory requirement to store these variables varies according to the type of data. For future referencing of variables, compiler must know about the memory location for that variable. We as a programmer can also want to know at what memory location our variable is stored.

To know the address, we must used & (address of) operator before variable name, and & operator returns the address where variable is store in memory.

For Example:

As shown in the diagram, variable i is stored at memory location 65526 and 65527, because in turbo c, integer requires two bytes of memory. In the first printf when we simply print i, it prints the value of i and in the second printf, &i prints the starting address for the variable i. So & operator returns the address where variable store in memory.

In C , it is also possible to store this address in the variable, but normal primitive variables are not intended for this purpose. So C provides a special

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 56: C Concepts

user defined variable called pointer which stores the address for the variable. Address is always unsigned integer so we used %u format specifier to print addess.

Declaration of pointer variable:

To differentiate the pointer variables from other primitive variables, C used * (star) symbol before pointer variable name. So declaration syntax for pointer variable is

[data type] *[variablename];

Here data type don’t indicate the type of pointer variable, it indicates that the address which pointer variable hold contains data type value. For example

int *ptr;

ptr is a pointer variable which holds the address, and address that it holds have integer value. Data type in pointer variable declaration never indicate the data type for the pointer variable because address is always an unsigned integer. So if we write

float *f;

means that f is a pointer variable which contains address and value at address is float value.

Initialization of pointer variable :

To initialize a pointer variable, we used & operator before variable name, and assign this value to pointer variable. For example

int i=10; // definition of integer variableint *ptr; // declaration of pointer variable which points to integer valueptr=&i; // initialization of pointer variable with i variable address

we can also combine declaration and initialization steps in single step which we will called defining a pointer variable as

int *ptr=&i;

To initialize a pointer variable is called referencing a pointer. Now we can also used this pointer variable for dereferencing. Dereferencing means using pointer variable, get the value for that it holds the address. We used * before

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 57: C Concepts

pointer variable to dereference it. *ptr means value at address which ptr holds.

ptr is an pointer variable in diagram, which points to steve variable. As shown in diagram , steve and *ptr both points to the same value, means if we make changes either using steve or *ptr, it reflected for other also because both refer to the same value. Pointer variable is used to dereferencing so it is also called

dereferencing variable or indirection variable.

Back To call by address concept:

In call by address, we don’t pass the value of the variable, we pass the address for that variable and in the function, we used pointer variable to hold that address. If now we dereference pointer variable for applying operation, then this operation result affects the value of the actual argument that we pass address in the function. So On applying operation on formal argument, it affected the value of actual argument.

Function recursion in C programming

Calling of same function from its function body is known as function recursion. It is alternative of loop. Any c program which is possible using loop it must be possible using function recursion.

How to write function recursion program in easier way:

I have already told it is very difficult to write function recursion program directly. If any person is writing such program directly he may be memorized that program. I am telling a very nice trick: how to write function recursion program in easier way? As we know any c program which possible using loop it must be possible using function recursion.

Steps for how to write a function recursion program:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 58: C Concepts

Step1: First of all write same program using while loop and function. (Except main function)Step 2: In that function make all local variable static.Step 3: Replace while keyword by if.Step 4: The increment or decrement of variable which is used for condition checking, replace with function call and pass the parameter of that incremented or decremented variable. Now understand by example:

Find the sum of all even numbers from 0 to 20 using function recursion.

Step 1: Write the same program using while loop and function. Here function is sum.

int main(){int total;total=sum(2);printf("%d",total);return 0;

}int sum(int i){

int even=0;while(i<=20){even=even+i;i=i+2;}return even;

}

Step 2: Make local variable even as static variable

int sum(int i){static int even=0;while(i<=20){even=even+i;i=i+2;}return even;

}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 59: C Concepts

Step 3: Replace while keyword by if keyword.

int sum(int i){int even=0;if(i<=20){even=even+i;i=i+2;}return even;

}

Step 4: Since here variable i has used in condition checking. So replace the statement i=i+2 by sum (i+2).

int sum(int i){int even=0;if(i<=20){even=even+i;sum(i+2);}return even;

}

Following only three simple change you can write any difficult function recursion program.

int main(){int total;total=sum(2);printf("%d",total);return 0;

}int sum(int i){

int even=0;if(i<=20){even=i +sum(i+2);}return even;

}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 60: C Concepts

One more example:

Write a program to find a factorial of given number using function recursion.

Step 1: write same program using while loop and function.

int main(){int fact,num;scanf("%d",&num);fact=factorial(num);printf("%d",fact);return 0;

}int factorial(int num){

int fact=1; //make it staticwhile(num>0){ //replace while by iffact=fact*num;num--; // replace by function call as factorial(num-1);}return fact;

}

After following step1, step 2, step 3:int main(){

int fact,num;scanf("%d",&num);fact=factorial(num);printf("%d",fact);return 0;

}int factorial(int num){

static int fact=1;if(num>0){fact=fact*num;factorial (num-1);}return fact;

}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 61: C Concepts

Note1: In step 3 while calling function don’t pass the parameter using unary operator like factorial (num--);

Note2: write the function in such a way parameter of calling function must be used in conditional statement. For example in the above program:

int factorial(int num)

num is function parameter and num is also used in the conditional if statement.

Function is used to perform some specific code in your program or it is used to divide a larger program in chunks.

Function have a signature which includes input argument, name of the function and return type.

Function can call other function and function can also call itself, function calling itself is called recursion.

Function calling is on the stack. Function can pass the values to other function by call by value and

reference. In call by value, we pass the variable value and copy it in another

variable in function. Variables declared in function have local scope , outside the function,

these variables have no scope First function which is called by the compiler is the main() function. main() is user defined function, not library functions. Return keyword is used to return the value from the function. Function which call the other function is called caller function and

which function it calls called calling function. There can be multiple return statement in a function, but function can

return only a single value.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 62: C Concepts

1. Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main( ) and print the results in main( ).

2. Write a function to calculate the factorial value of any integer entered through the keyboard.

3. Write a function power ( a, b ), to calculate the value of a raised to b.

4. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number

5. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89...

6. Write a function to check the entered number is palindrom or not .7. Write a function to reverse an entered number, values are passed by

address only.8. Write a function to calculate the square root of entered number.9. Write a function to calculate the prime number between a entered

range10. WAP to print pascal triangle using recursion.

Chapter 5: Arrays

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 63: C Concepts

An Array in C Programming Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.

An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a “string”, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can’t have an array of 10 numbers, of which 5 are ints and 5 are floats.

Array is a finite collection of similar type data.

How to declare Array

Array is declared in same way as normal variable declared but we add [] after array variable name. for Example , if we want to create a integer array of size 5 , then the declaration is as:

int a[5]; // declaration of array , array name is a , size is 5 , contains integer values

Above statement means that a is an array which contains integer values and size of array is 5, means it contain 5 integer values. How array contain these 5 integer values is shown in the diagram.

In reality, a is a pointer variables (a holds address of first element in array), which points to the first element in array. Array elements can be accessed by using index values for the array elements. First array element has index value 0 and last element have index value [size-1]. So we want to access the first element in array, then it is a[0] , and if we want to access the last element of array then it is a[size -1] as shown in diagram.

array of 10 elements , first element is a[0] and last element is a[9], 5th element is a[4]

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 64: C Concepts

Initialization an array

There are two ways to initialize an arraya. Direct initialization (using initializer list)b. Using loops

Direct Initialization : we can initialize array when we create it. Array declaration and initialization is in the same step. If the array elements are not initialized then it will initialized with zero when we used initialize list.

int a[]={1,2,3,4,5}; // declaration and initialization

If we initialize array at the same place where we declare it then it is not mandatory to provide the size of the array in declaration syntax.

int a[5]={1,2,3,4,5}; // fully initializer list

If we initialize all the elements of the array using initializer list then this list is called fully initialize list.

int a[10]={1,2,3,4,5}; // partial initialize list

If we define only some elements using initialize list, then it is called partial initialize list, remaining elements are initialize with zero value.

Using loops: we can also use loop technologies to initialize array with elements. Array indexing starts with 0 and ends with arraysize -1, so we can create a loop which starts from 0 and ends on arraysize-1 , and in each iteration we can put an element in array.

int a[10]; // declaration of array , array contain 10 integer elementsfor(int i=0;i<10;i++){// loop will start from 0 and ends on arraysize-1scanf(“%d”,&a[i]); // initialize a[0] in first iteration and a[9 ] in last iteration}

If we define only some array elements using loop, then remaining elements are initialized according to the storage class of array. If storage class is automatic or register then array initialize with Garbage value, if static or external then initialize with zero value.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 65: C Concepts

How to get array element values

There are two ways to get the values for array elements.

a. Using indexed valuesb. Using loops

Using indexed values: if we want to access a particular element in an array, then we can used the indexed value for the particular element to print the value. Suppose if we have an array with 10 elements and we want to print the 4th element in array , code is:

int a[]={1,2,3,4,5,6,7,8,9,10}; // array declaration and initializationprintf(“%d”,a[3]); // a[3] means we want to print 4th element in array that is 4.Printf(“%d”,a[9]); // a[9] prints last element in the array which is 10

Using loops : if we want to print all elements or elements which is contiguous ,then we can also used looping technologies of c to print the element. Suppose we want to print

all elements of array, so we start the loop from 0 (first index value in array) to size-1 (last index value in array), and for each iteration we print array value.

int a[10]={1,2,3,4,5,6,7,8,9,10}; // declaration and initialization of array for(int i=0;i<10;i++){// loop will start from 0 and ends on arraysize-1printf(“%d”,a[i]); // print a[0] in first iteration and a[9 ] in last iteration}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 66: C Concepts

Before going forward, lets first rewind some important points in array

An array is a finite collection of similar data. Array elements are accessed by using index value for the elements.

First element of array is at index 0 and last element of array is at index [array size -1]

Before use the array, we have to first declare an array Array initialization is done through by using loop or by initialization list. Array memory allocation is contiguous, means if we declare an array of

5 int elements then these 5 elements must be in contiguous memory location.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 67: C Concepts

As shown in diagram, As in turbo C integer takes 2 byte of memory, each elements are two memory locations apart but contiguous in memory.

There is no bound checking in array, if we declare an array of 5 elements and try to print a value that are not indexed, then it will print value according to storage class.

Array and Functions

We can pass array in function by call by value or by call be address. In call by value we pass individual array element in function and collect it in a variable that have same data type as array. Using call by value we can only pass individual element in function. Suppose if we want to print all elements of a array using function, then the code is:

As shown in code, we pass individual array elements using loop in printElements function that have an input arguments which is same data type as array have. And for each iteration, printElements function is called and print array elements for the ith indexed value.

We can also pass array elements by using address for each element. We used & operator to get the address of elements and in the function we require a pointer variable which holds the address for the elements. Pointer variable must able to hold the address for the array elements means if

array contains integer elements then pointer should able to hold the address of integer elements.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

#include<stdio.h>#include<conio.h>void main(){int a[]={1,2,3,4,5};for(int i=0;i<5;i++)printElements(a[i]);getch();}void printElements (int i){printf(“%d”,i);}

Page 68: C Concepts

As shown in code , now we pass the address for each element of array in printElements function which get this address in a pointer variable i which is able to hold the address of integer variables. As array contains integer elements , now we print the elements at the address using * before pointer variable.

Pointer Arithmetic

Before understanding function and array in more details, let us first understand the pointer arithmetic’s.

Addition a number in pointer variables : Suppose we have a pointer variable which holds the address for the integer variable, and let us suppose integer takes two bytes of memory, if we add any integer value to this pointer variable, then what happened is shown in the diagram

Increasing pointer variable means increase the address in pointer variable by the amount of data type. Suppose if integer takes 2 bytes in memory then if we add 2 in the pointer variable , then it increased by 4 address and this new address is store in pointer variable.

Let consider the below program

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

#include<stdio.h>#include<conio.h>void main(){int a[]={1,2,3,4,5};for(int i=0;i<5;i++)printElements(&a[i]);getch();}void printElements (int *i){printf(“%d”,*i);}

Page 69: C Concepts

#include<stdio.h>#include<conio.h>void main(){int i=10,*p;float f=9.9,*q;char c=’a’,*r;p=&i;q=&f;r=&r;printf(“value of integer = %d & address is = %u \n”,i,p);printf(“value of float = %f & address is = %u \n”,f,q);printf(“value of char = %c & address is = %u \n”,c,r);p++;q++;c++;printf(“After increment of pointer variables”);printf(“address is = %u \n”,p);printf(“address is = %u \n”,q);printf(“address is = %u”,r);}

Suppose in memory variables are stored like this:

Output of program is :Value of integer = 10 & address is = 65520Value of float is =9.9 & address is = 65956Value of char is =a & address is = 66300After increment of pointer variablesAddress is : 65522Address is : 65960Address is : 66301

As p is point to integer value and suppose integer takes 2 byte , so increment in pointer increases value by 2 ,q points to float value and increment by 1 means increase the address by 4 and r points to char , increment by 1 means increases the address by 1 as character takes 1 byte of memory.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 70: C Concepts

Same concept is apply for subtraction, when we subtraction a number from pointer variable, value is decreased according to data type which address points .

Subtraction of one pointer from another: One pointer variables can be subtracted from another pointer variable but both should point to the same array, it gives the differences between the memory location between those in memory.

int a[6]={1,2,3,4,5,6};int *p,*q;p=&a[1];q=&a[5]int c= q-p; // returns the address differences

Below operation on pointer are not applicable1. Addition of two pointer variables2. Multiplication of number with pointer variable3. Division of a number with pointer variable

Back to Array and function

As we saw that we can pass the array elements in function by using call by value or call be reference. In reality, array variable is like a pointer variable, which holds the address of first element in array, so if we pass only the array name in a function, it means we are passing the address for the first element in the function. By using this address and using pointer arithmetic, we can used all the elements of array in function and if we make any changes in the values of array , then it is also reflected on caller function.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 71: C Concepts

As shown in diagram, a contains the address for the a[0] element, and if we assign this address in pointer variable and then used pointer arithmetic, we can reach to all the elements of array because memory allocation for the array is always contiguous. Don’t increase the array variable, because it is like a pointer, not a pointer, so pointer arithmetic is not applicable on it. If we applied some operation on array variable, Compiler will complaint for lvalue required.

#include<stdio.h>#include<conio.h>void printArray(int *,int);void main(){int a[]={9,45,12,32,78};printArray(a,5);getch();}void printArray(int *p,int size){for(int i=0;i<size;i++){printf(“%d”,*p);p++;}}Output : 9,45,12,32,78

Two Dimensional Array : Array of linear array is called two dimensional array or we can say array with two subscripts(indexes) is called two dimensional array where first subscript denotes the number of linear array and second subscript denotes the element in each linear array.

Declaration of 2-D Array: It is similar like 1-D array except now we used two subscript instead of one. For Example:

int a[3][4];

It tells the compiler that it has 3 linear array and each linear array contains four elements of integer type. In the same way we can declare float or character array.

Initialization of 2-D Array:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 72: C Concepts

We can Initialize 2-D array using initialize list or using looping mechanism.For Example:

Using Initializer Listint a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

int a[3][4]={{1,2,3,4}, {5,6,7,8}, {9,10,11,12} };

All are same statements

We can also used loops for initialize 2-d array, first loop indicates the number of 1-d array where 0th index is used to denote first 1-d array and 1st index is used to denote second 1-d array. Inner loop indicates the number of elements in each 1-d array where 0 index indicates the first element,1 index indicates the second element and so on.

int a[3][5];for(int i=0;i<3;i++){for(int j=0;j<5;j++){scanf(“%d”,&a[i][j])}}

Strings : Single characters are stored in char variables, but in real life, names don’t contain only a single characters. Mostly all names have sequence of characters, so in c language, we can store names in character array. Character array is a collection of characters which are stored at contiguous memory location. But character array is a collection of characters which can be accessed one element each time, we can’t access them as a name. So c provides us a special type of character array which ends with a special character called ‘\0’ (NULL) character.

So Strings are the character array which ends with a special character called null character which indicates the end of the string.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 73: C Concepts

Character in c represents using single quote notation where as string is denoted by double quotes notation. User can supplied string in double quotes during the declaration of char array as

char arr[10]=”computer”;

arr is a character array name which can contain maximum 10 characters and we initialize this array with the value computer where c stores at 0th index, o is stored at 1st index and so on. Compiler will add a special character called null character after r character.

C also provides a special format specifier %s which is used to get the string from keyword and also to print string on monitor. If we used %s in printf and scanf function, then we can read all string at one go, we don’t need to put looping mechanism to get the array value. In scanf function, we never used & operator if use %s for getting string input, %s specifier works as

char name[15];printf(“please enter a name : ”);scanf(“%s”, name); // No & operator printf(“you entered %s”,name);

C never provides bound checking on array length means if you enter more characters then the array length then it can override some useful information of your program with that data. Data is not store as part of array. Now Suppose in the above program if you enter Ajay Sharma, then in output you only get “you entered Ajay”. The problem is when we used %s for String input in scanf, then it can take only one word of string. If there is any space in the string then it automatically insert the null character. So in scanf, %s can’t able to accept multiple word things which are delimited by space.

C provides gets function which is used to get String input and supports multi words String. Also There is puts function and it is used to print string output to console window. Both gets and puts functions are part of stdio.h header file.

#include<stdio.h>#include<conio.h>void main()

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 74: C Concepts

{char arr[30];puts(“Enter the String Input”);gets(arr); // to get the string input for arr puts(arr); // to print arr String}

puts function prints the string on console and move to next line as compared to printf which prints output on console but remains in the same line.

Standard Library String function :

C provides functions which work on String data type. Header file for these functions are “string.h”. All these library functions are used so we can perform different operations on string data type.

We will discuss some of them and list for all these inbuild functions is in the next page.

1. strlen function : strlen function is used to get the string length. This function takes an pointer of char type and we can pass either base address for the character array or we can pass a String in the function during calling . Strlen functions returns integer value which indicates the length for the string.For Example:int len= strlen(“Hello Welcome to C language”);

in len variable we get 27. Null character which is part of string are not included during calculation of string length.

char c[]=”hello how r u”;

int x = strlen(c); // x will have length for c.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 75: C Concepts

We as a programmer can also implement the same logic which works like string library functions to work with string. Now suppose if we want to implement logic for strlen() function, we do it like this

// Program to find string length without using strlen() function#include<stdio.h>#include<conio.h>

int strlength(char *);int main(){ char arr[]="Welcome to C language";

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 76: C Concepts

int z=strlength(arr); printf("%d",z); getch();}

int strlength(char *p){ int count=0; // to count number of characters while(*p!='\0') { count++; // increment count p++; // increment pointer variable } return count; // returing length of string}

2. strcmp function : strcmp function is used to compare two string. if both strings are identical then strcmp returns 0 else it returns non zero value. During calling we pass the strings which we want to compare in strcmp function.

For Exam:

char a[]=”Humpy Dumpy”;

char b[]=”Hello”;

int x = strcmp(a,b); // compare a and b

int y= strcmp(a,”Humpy Dumpy”); compare String a with Humpy Dumpy

In Above scenario, x becomes non zero because both string are not same and y becomes zero.

// Program to compare two Strings without using strcmp function#include<stdio.h>#include<conio.h>

int strcomparison(char *,char *);int main(){ char arr[]="Welcome"; char brr[]="welcome";

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 77: C Concepts

int z=strcomparison(arr,brr); if(z) printf("both string are not same"); else printf("both strings are same"); getch();}

int strcomparison(char *p,char *q){ while(*p!='\0' || *q!='\0') { if(*p != *q) { return (*p-*q); } p++; q++; } return 0;}

In string.h header file, syntax for strcmp function have two input arguments but each have const keyword like const char *p. What is the importance of this const keyword. When we pass String in function, then it is possible to change the original string using pointer variable. If we want that in the function we can’t change the value using pointer, then we should declare a pointer through which we are not able to change the value that it points. For this there is a concept of pointer to a constant. Lets take a tour of this concept

Pointer to a constant : If we declare a pointer to a constant then we can’t change the value that it points. It is possible to change the address which pointer contains.

Declaration of pointer to a constant:

const char *ptr; //ptr is a pointer to a constant.or char const *ptr; // ptr is pointer to a constant.

Program to prove the concept of pointer to a constant

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 78: C Concepts

Constant Pointer : In pointer to a constant we can’t able to change the value which pointer points but we can change the address in pointer variable, but if we want to create a variable that can’t points to other value after initialization then we should create constant pointer.

char * const ptr;

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 79: C Concepts

So in strcomparison function we should declare pointer as pointer to a constant so that we can’t change the string which pointer points. Through this we must ensure our self that string which we pass in function can’t be change.

So we rewrite the same program again

// Program to compare two Strings without using strcmp function#include<stdio.h>#include<conio.h>

int strcomparison(char *,char *);int main(){ char arr[]="Welcome"; char brr[]="welcome"; int z=strcomparison(arr,brr); if(z) printf("both string are not same"); else printf("both strings are same"); getch();}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 80: C Concepts

int strcomparison(const char *p,const char *q){ while(*p!='\0' || *q!='\0') { if(*p != *q) { return (*p-*q); } p++; q++; } return 0;}

3. Strcpy function : strcpy function copy the content of one string to other string. The target String should capable of holding the source string means target string should either greater then or equal to the source string. Compiler never worried about the bound checking in c language so it’s programmer responsibility to kept size enough so it can receive source string.

#include<stdio.h>#include<conio.h>#include<string.h> // for strcpy functionint main(){ char arr[]="computer"; char brr[20]; char *p =strcpy(brr,arr); //strcpy(target,source) syntax puts(brr); // prints computer on console getch();}

We can also create strcopy function which works similar like strcpy function.

// Program to copy the content of one string into other#include<stdio.h>#include<conio.h>

void strcopy(char *,const char *);int main()

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 81: C Concepts

{ char arr[]="shyam mohan"; char brr[20]; strcopy(brr,arr); printf("%s",brr); getch();}

void strcopy(char *p,const char *q){ while(*q!='\0') { *p=*q; // copy one character at a time p++; q++; } *p='\0';}

Programs

1. WAP to initialize a array which takes 10 integer values using loop mechanism and print all the elements also

2. WAP to sum all the elements present in the array which able to take 10 integer values, Values are assigned using initializer list.

3. WAP to find a element in integer array, also count the number of occurrence if element is found.

4. Twenty-five numbers are entered from the keyboard into an array. Write a program to find out how many of them are positive, how many are negative, how many are even and how many odd.

5. WAP to found number of odd and even element in the array.6. WAP to sort the 10 element integer array in ascending order.7. WAP to sort the 10 element using selection sort.8. WAP to sort the 10 element using bubble sort.9. WAP to sort the 10 element using insertion sort.10. WAP to insert a new element in the sorted array. Element

must be placed at its relevant position so that array should sorted.

11. WAP to delete an element from the sorted array, remember array element must be in sorted form.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 82: C Concepts

12. WAP to find the maximum element in the array.13. WAP to find the second minimum element in the array.14. WAP to add two matrix using 2-D array.15. WAP for matrix mulplication.16. WAP to calculate the sum of the diagonal elements in a

matrix.17. WAP to transpose a matrix.18. Implement the following procedure to generate prime

numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.

S step 1 Fill an array num[100] with numbers from 1 to 100 S step 2 Starting with the second entry in the array, set all its

multiples to zero. S step 3 Proceed to the next non-zero element and set all its

multiples to zero. step 4 Repeat step 3 till you have set up the multiples of all the

non-zero elements to zero s step 5 At the conclusion of step 4, all the non-zero entries left in

the array would be prime numbers, so print out these numbers. 19. Write a program to calculate the sum of all elements of 3*3

matrix. Matrix must be passed in a functiona. Using pointer arithmeticb. Using pointer to an arrayc. Using [] notation

String Programs1. Take a character array of size 10 and using scanf ,take the values

from user and print it using printf function.2. Use %s format identifier to scan and print the character array.3. Use inbuild library function gets and puts for taking and printing

the char array to user.4. Write a program to calculate the length of the string using logic

and inbuild function.5. Write a program to compare two string using logic and inbuild

function.6. Write a program to copy a string in another string using logic and

inbuild function.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 83: C Concepts

7. Write a program to calculate to reverse the string using logic and inbuild function.

8. Write a program to convert the lower case string in upper case using logic and inbuild function.

9. Write a program that converts a string like "124" to an integer 124.

10. Write a program that replaces two or more consecutive blanks in a string by a single blank. For example, if the input is Grim return to the planet of apes!!

the output should be Grim return to the planet of apes!!

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 84: C Concepts

Chapter 6: Structure

Array is a finite collection of similar type data but real world entity can’t be represent only by similar data. For example, we want to represent student which have id, name, email and address attributes. To represent student, we don’t have any data type and if we used different variables for these attributes then we require integer variable to store id, character array for name, email and address. If we want to store multiple students then we have to create multiple variables. Instead of declaring multiple variables for these attributes, we can create array for these attributes. For Example, we create array for id, an 2-D array for name, email and address.

Declaring array for these attributes behave independently. So Dennis Ritchie, created a new concept which is collection of dissimilar type data means we can bind dissimilar data under a name.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 85: C Concepts

In Other words, we can say that structure is a mechanism through which we can create user defined data type in C language.

Simple variable can store a single value at a time. Assigning a new value to a variable will overwrite

the previous value of variable.

Array variable can store a finite number of similar type elements, which is accessed using indexed notation.

Structure is a mechanism that can store dissimilar type data, means it can be used to create a data type.

Structure: A structure contains a number of data types grouped together which can be same type or different type. Suppose we want to create an employee which have name, date_hired and salary attributes. The syntax for creating structure for the employee is

Bullet Points:

1. struct is a keyword in C library which is used to define structure.2. Employee is name of structure.3. Structure members are defined inside the curly braces and after

closing curly brace we must put semicolon (;).4. All the members whom we want for employee must be inside the curly

braces.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 86: C Concepts

Declaring a structure doesn’t means that we can used it directly now. But like integer variable we must first declare a variable which is type of structure. So we must declare a structure variable like

struct [structure name] [structure variable name];

Memory Requirement to store structure variable: To Store integer variable we require 2 bytes of memory in turbo C. Similarly to store a structure variable we require some memory and that memory is equal to the sum of data fields size that are included in structure definition. For Example: We have a structure called employee that have three fields like name of employee, salary of employee and worker_no. Structure employee is defined as

struct employee{char name[32];float salary;float worker_no;

};

Each character requires one byte of memory so 32 characters requires 32 bytes + 4 for salary field and 4 for worker_no field. So Total Memory requires to store structure is 40 bytes.

Bullet Points:

1. Structures in C defines the group of contiguous (adjacent) fields, such as records or control blocks.

2. Memory Allocation for structure must be contiguous.3. Each structure variable requires same size of memory.4. Each structure variable access its members using dot (.) operator.

For Example : To access salary field for employee structure , first we have to create variable of employee likestruct Employee emp;

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 87: C Concepts

using this variable name and dot operator we can access each and every field of structure.

To receive value for salary: scanf(“%f”,& emp.salary);

To print value for salary:printf(“%f”,emp.salary);

Initializing structure variable :

Initializing structure variable means that we want to assign values to the attributes which is defined inside structure. Suppose we create two structure variables of type employee structure, then each structure variable have all the attributes defined in employee structure as shown in the diagram.

We created two structure variable emp and emp1. Each variable have all the attributes which is defined in struct employee. For initializing the values for these attributes in c, we can used

1. Initializer list : while declaring structure variable, we can also initialize attributes for that variable like:

struct employee emp={“Dennis”,17000.00, 150};

like this, name attribute is initialize with Dennis , salary attribute with 17000.00 and worker_no with 150. All these attributes are initialized during the initialization of structure variable.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 88: C Concepts

2. Initialize variable Using input library function

struct employee emp; // declaration of employee structure variableprintf(“Enter the name ”);

gets(emp.name); // to get string value from user

printf(“Enter the salary”);

scanf(“%f”,&emp.salary);

printf(“Enter worker no”);

scanf(“f”, &emp.worker_no);

3. We can initialize structure variable from already created structure variable similar like primitive variables using assignment operator.struct employee emp={“Dennis”,12000.00,5.0};

struct employee emp1= emp;

emp1 have same values which is assigned to emp.

Accessing Structure variable:

After understanding the concept of structure type and structure variable declaration and initialization, now let’s look how to retrieve values using structure variable. Array elements are accessed using indexed values. but structure elements are accessed using the dot operator with variable name.

syntax for referencing structure element is

[structure variable].structure element name;

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 89: C Concepts

Memory Allocation for structure: All the structure members which are referred using structure variable are allocated in contiguous memory locations. Two structure variables can allocate anywhere in memory but all members or attribute for each variable requires contiguous memory. Memory requirement for structure variable is equal to the sum of memory to store each of its members.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 90: C Concepts

As shown in the diagram, total memory requires to store structure employee variable is 26 bytes according to turbo c compiler. Integer requires 2 bytes, each character requires 1 byte memory and float require 4 byte.

Structure Array : what happened if we want to store multiple instance of structure, then we can create multiple variable of structure, else we can create an array of structure. Array is a finite collection of similar type data, so in each position of array we are going to store structure variable, but structure itself is a collection of dissimilar type data. So we create an array of structure. First structure variable is store at 0th index of array. Let we have below structure

struct Registration{char name[10];int roll;int fees;};

Now we create an array which contains 10 instance of this structure as

struct Registration s1[10];

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 91: C Concepts

first variable have 0th index, second variable have 1st index and so on. To access first structure variable empid, then we have to write as

s1[0].name;

here s1[0] denotes first instance of structure employee and using dot operator we can access name field of structure for that instance. Memory allocation for array is always contiguous and memory allocation for structure variable is also contiguous, so in array of structure, all memory allocation is contiguous.

Structure Pointer : pointer can point to integer value, a float value , a char value , an array , an function. So similarly pointer can points to a structure. Pointer can store an address for a structure also. Pointer which points to a structure is called structure pointer.

Lets we have the below code and diagram for structure pointer concept

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

struct team{char *name;int members;char *caption;}t1;

int main(){struct team *sptr=&t1;}

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 92: C Concepts

Declaration of structure pointer:

struct Employee *p;

here p is a pointer variable and points to structure employee. Now we can access structure member using pointer also. Let demonstrate this concept using a c program

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

int main(){ struct employee { int empid; char emp_name[20]; float salary; }; struct employee emp={10,"Sachin Tendulkar",100000.00}; struct employee *p=&emp;

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 93: C Concepts

printf("id= %d \n name = %s \n salary= %8.2f",(*p).empid, (*p).emp_name,(*p).salary); // print structure members using pointer //variable getch();}

we can access structure member using (*p).[structure member name]. C provides us an alternate way for this. if we used structure pointer to print structure members ,then we can used -> instead of dot as shown in the below code

// print structure member using structure pointer and ->#include<stdio.h>#include<conio.h>

int main(){ struct employee { int empid; char emp_name[20]; float salary; }; struct employee emp={10,"Sachin Tendulkar",100000.00}; struct employee *p=&emp; printf("id= %d \n name = %s \n salary= %8.2f",p->empid, p->emp_name,p->salary); getch();}

Chapter : File Handling

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 94: C Concepts

permanent storage of input/output that can be accessed at any point of time later. A file is a region of memory space in the storage media and it can be accessed using the library functions available in stdio.h or by the system calls of the operating system. File contains bytes of information. C supports a number of functions that have the ability to perform basic file operations, which include:

       1. Naming a file       2. Opening a file       3. Reading from a file       4. Writing data into a file       5. Closing a file

   

* Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems

It becomes cumbersome and time consuming to handle large volumes of data through terminals.

The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

File operation functions in C:

Function Name Operation

fopen()Creates a new file for useOpens a existing file for use

fclose Closes a file which has been opened for use

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 95: C Concepts

getc() Reads a character from a file

putc() Writes a character to a file

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

Defining and Opening a File

     If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the filename, data structure, purpose.

The general format :

     FILE *fp;     fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the structure FILE. As stated earlier, File is a structure that is defined in the stdio.h header file.

The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.

The second statement also specifies the purpose of opening the file.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 96: C Concepts

The mode does this job:

      r open the file for read only.      w open the file for writing only.      a open the file for appending data to it.

Input/Output operations between C program and file can be done using two ways

1. Text Based I/O or character I/O2. Binary Based I/O

In character I/O, everything goes in file in the form of character only. In others words, we can say that character mode not recognize data types. Character mode file is in readable format also.

In Binary I/O, we can write or/and read data according to data types. In orders words, we can say binary recognizes data types and binary mode file in not in readable format.

In C, t character is used to denote text based I/O and b is used for binary based I/O while opening file using fopen. text based I/O is by default value, so we can avoid t character in mode. but if we want binary I/O, then in mode we must specify

rb- read in binary mode wb- write in binary mode ab- append in binary mode

Example:

      FILE *p1, *p2;      p1=fopen(“data”,”r”);      p2=fopen(“results”,”w”);

     In these statements the p1 and p2 are created and assigned to open the files ‘data’ and ‘results’ respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur. Remember r and w is a string not single character because it denotes rt and wt. By default mode is text mode so we can avoid t in mode declaration.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 97: C Concepts

Closing a File

     The input output library supports the function to close a file.

The general format:

     fclose(file_pointer);

   A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.

Example:

FILE *p1 *p2;p1=fopen (“Input”,”w”);p2=fopen (“Output”,”r”);….…fclose(p1);fclose(p2)

getc()

The getc() function returns the next character from the specified input stream and increment file position indicator. The character is read as an unsigned char that is converted to an integer.

Declaration:

int getc(FILE *stream);

Example:

#include <stdio.h>#include <stdlib.h>int main() { FILE *fptr; char c; clrscr(); if((fptr = fopen(“TEST”,”r”))==NULL) { printf(“Cannot open file\n”);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 98: C Concepts

exit(1); } while((c=getc(fptr))!=EOF) putchar(c); if(fclose(fptr)) pritf(“File close error\n”); getch(); return 0; }

putc()

The putc() function writes the character ch to the specified stream at the current file position and then advance the file position indicator. Even though the ch is declared to be an int, it is converted by putc() into an unsigned char.

Declaration:

int putc(int ch, FILE *stream);

Example:

#include <stdio.h>#include <stdlib.h>void main() { FILE *fptr; char text[100]; int i=0; clrscr(); printf(“Enter a text:\n”); gets(text); if((fptr = fopen(“TEST”,”w”))==NULL) { printf(“Cannot open file\n”); exit(1); } while(text[i]!=’\0’) putc(text[i++],fptr); if(fclose(fptr)) pritf(“File close error\n”); getch(); }

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 99: C Concepts

EOF, getc() and feof() in C

In C/C++, getc() returns EOF when end of file is reached. getc() also returns

EOF when it fails. So, only comparing the value returned by getc() with EOF

is not sufficient to check for actual end of file. To solve this problem, C

provides feof() which returns non-zero value only if end of file has reached,

otherwise it returns 0.

For example, consider the following C program to print contents of

file test.txt on screen. In the program, returned value of getc() is compared

with EOF first, then there is another check using feof(). By putting this check,

we make sure that the program prints “End of file reached” only if end of file

is reached. And if getc() returns EOF due to any other reason, then the

program prints “Something went wrong”

#include <stdio.h> int main(){  FILE *fp = fopen("test.txt", "r");  int ch = getc(fp);  while (ch != EOF)   {    /* display contents of file on screen */    putchar(ch);      ch = getc(fp);  }     if (feof(fp))     printf("\n End of file reached.");  else     printf("\n Something went wrong.");  fclose(fp);       getchar();  return 0;}

Reading and Writings Strings in/from file : getc and putc functions are used to read and write a character from file. Similarly we have another two functions: fgetc and fputc which is also used to read and write characters from file. If we want to read and write string (multiple characters) then c

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 100: C Concepts

provides us fgets and fputs functions for reading and writing string respectively.

fgets() function read string from file and assign it in string (character array) in c. fgets function takes three argument.First argument is a name of the string, second argument is an integer value which indicates the number of characters which we want to read at once and third argument is file pointer.

char * fgets(char *s, int n, FILE *stream)

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

int main(){ FILE *fp= fopen("D://test.txt","r"); if(fp==NULL) { printf("Unable to open the file"); return 1; } char c[80]; while(fgets(c,79,fp)!=NULL) { printf("%s",c); } fclose(fp); getch();}

fputs() function is used to write strings in file. fputs functions takes two arguments. First argument is char pointer which points to string that we want to write and second argument is file pointer that points to the file.

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

int main(){ FILE *fp= fopen("D://test.txt","w");

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 101: C Concepts

if(fp==NULL) { printf("Unable to open the file"); return 1; } char c[80]; while(strlen(gets(c))!=0) { fputs(c,fp); fputs("\n",fp); } fclose(fp); getch();}

fprintf and fscanf function : what happened if we want to write and read different data types in file. First we must combine these data types in a structure and then we can write and/or read structure to/from file using fprintf and fscanf functions. fprintf function is similar like printf functions but in fprintf function we specify file pointer.

int fprintf(FILE *ptr,char * fmt,…)

fscanf functions is used to read structure data from file.

File Writing Program

#include<stdio.h>#include<conio.h>// combine data in a structurestruct Employee{ int empid; char ename[15];};

int main(){ FILE *fp= fopen("demo.txt","w"); // open the file in write mode if(fp==NULL) { printf("unable to open the file"); getch();

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 102: C Concepts

return 1; }

struct Employee e;printf("Enter the id : ");scanf("%d",&e.empid); printf("Enter the employee name : ");fflush(stdin);gets(e.ename);

fprintf(fp,"%d %s",e.empid,e.ename); // write it in filegetch(); }

File Reading Program

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

struct Employee{ int empid; char ename[15];};

int main(){ FILE *fp= fopen("demo.txt","r"); if(fp==NULL) { printf("unable to open the file"); getch(); return 1; }

struct Employee e;

while(fscanf(fp,"%d %s",&e.empid,e.ename)!= EOF){ printf("%d",e.empid); puts(e.ename); }

getch();

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 103: C Concepts

}

Function Syntax Example

fopen - Open file

FILE * fopen(char * filename, char * mode)

Filename – string filename with path

Mode – mode of opening

             r    read only

            w   write only

            a    append file

            +    read and write (r+/w+/a+)

Return value – FILE pointer on success

NULL on failure

FILE * infile ;

Infile = fopen(“a.txt”,”r”);

FILE *outfile = fopen(“b.txt”,”w”);

if(infile==NULL || outfile==NULL)

{

printf(“error”);

}

fclose – close the open file

fclose(FILE *fptr)

fptr – FILE * of the open file

Returns void

fclose(infile);

fgetc – read one char from file

int fgetc(FILE *fptr)

fptr – FILE * of the open file

returns – character read

            -1 on eof or error

while( (ch=fgetc())!=-1)

      putchar(ch);

//display content of file

//on screen

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 104: C Concepts

fputc – write one character to the file

int fputc(int ch,FILE *fptr)

ch – character to write

fptr – open file pointer

returns character written

           EOF if there is error

for(ch=’A’;ch<=’Z’;ch++)

       fputc(ch,fptr);

fscanf –

Formatted read from file

int fscanf(FILE *ptr,char * fmt,…)

ptr – FILE pointer

fmt – format specifier for variables to be read

Returns – number of values read successfully

fscanf(infile, “%d %d”,&n1,&n2);

fprintf – formatted write to file

  int fprintf(FILE *ptr,char * fmt,…)

ptr – FILE pointer

fmt – format specifier for variables to be read

Returns – number of characters  printed or negative number on error

fprintf(outfile,“Value is %d\n”,n1);

fread – read from binary file

int fread( void *buffer, size_t size, size_t num, FILE *ptr )

buffer – stores the value readsize – size of the buffernum – number of blocks to be readptr – file pointerReturns – number of values read

Char *str = malloc(50);

fread(str,50,1,infile);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 105: C Concepts

 

fwrite – write to a binary file

int fwrite( void *buffer, size_t size, size_t num, FILE *ptr )

buffer – stores the value readsize – size of the buffernum – number of blocks to be readptr – file pointerReturns – number of values written

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

   fwrite(&i,sizeof(i),1,outfile);

char a[]=”end”;

fwrite(a,strlen(a)+1,1,outfile);

fseek – move the file pointer by given offset

int fseek(FILE*ptr,long offset,int whence)

ptr – file pointeroffset – offset in bytes from third parameterwhence – SEEK_SET – from beginning of fileSEEK_CUR – from current positionSEEK_END – from end of fileReturns – zero on successNon-zero on failure

if(fseek(infile,4L,SEEK_SET)==0)

{

     char ch=fgetc(infile);

     printf(“The fourth char of the file is %c\n”,ch);

 }

ftell – get the position of file pointer

int ftell(FILE *ptr)

ptr – FILE pointerReturns – position of file pointer-1 on error

FILE *ptr = fopen(b[1],"r");

fseek(ptr,0L,SEEK_END);

 int size_of_file = ftell(ptr);

rewind – moves the file pointer to the beginning of the file

void rewind(FILE *ptr)

ptr – FILE pointer

rewind(infile);

int n = fscanf(infile,”%d”,&n);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 106: C Concepts

Chapter : Command line arguments and Dynamic Memory Allocation

Command Line Arguments:

The C language provides a method to pass parameters to the main() function. This is typically accomplished by specifying arguments on the operating system command line (console).

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 107: C Concepts

The prototype for main() looks like:

int main(int argc, char *argv[]){…}

There are two parameters passed to main(). The first parameter is the number of items on the command line (int argc). Each argument on the command line is separated by one or more spaces, and the operating system places each argument directly into its own null-terminated string. The second parameter passed to main() is an array of pointers to the character strings containing each argument (char *argv[]).

For example, at the command prompt:

test_prog 1 apple orange 4096.0

There are 5 items on the command line, so the operating system will set argc=5. The parameter argv is a pointer to an array of pointers to strings of characters, such that:

argv[0] is a pointer to the string “test_prog”argv[1] is a pointer to the string “1”argv[2] is a pointer to the string “apple”argv[3] is a pointer to the string “orange”andargv[4] is a pointer to the string “4096.0”

Bullet Points

The main() routine can check argc to see how many arguments the user specified.

The minimum count for argc is 1: the command line just contained the name of the invoked program with no arguments.

The program can find out its own name as it was invoked: it is stored in the argv[0] string! Some operating systems don't provide this feature, however.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 108: C Concepts

The arguments from the command line are not automatically converted: the characters are just copied into the argv strings.

If an argument on the command line is to be interpreted as a numerical constant, such as argv[1] and argv[4] in this example, it can be converted using a string conversion.

int int_val; float float_val;

int_val = atoi(argv[1]); //function to convert string to intfloat_val= atof(argv[4]); //function to convert string to floatsscanf(argv[4],”%f”,&float_val);

printf(“The 3rd and 4th items on the command line are %s and %s\n”, argv[2], argv[3]);

results in:1 4096.0The 3rd and 4th items on the command line are apple and orange

Programming Example:

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

int main(int argc, char *argv[]){ printf("%s",argv[0]); // print program name int i = atoi(argv[1]); // convert first argument to integer printf("%d",i); // print integer value getch();}

leap year program using command line arguments

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

int main(int count, char *arv[]){ // count == totol number of command line arguments in program printf("total arguments are : %d \n",count);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 109: C Concepts

puts(arv[0]); // print program name int i= atoi(arv[1]); // conversion from string to int // leap year logic printf("%d year is ",i); if(i%400==0) printf("leap year"); else if(i%100==0) printf("not a leap year"); else if(i%4==0) printf("leap year"); else printf("not a leap year"); getch(); }

Library function for type conversion(part of stdlib.h header file)

atof (String to double)Syntax:

#include <stdlib.h> double atof( const char *str );

The function atof() converts str into a double, then returns that value. str must start with a valid number, but can be terminated with any non-numerical character, other than "E" or "e". For example,

x = atof( "42.0is_the_answer" );

results in x being set to 42.0.

atoi (String to int)Syntax:

#include <stdlib.h>

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 110: C Concepts

int atoi( const char *str );

The atoi() function converts str into an integer, and returns that integer. str should start with some sort of number, and atoi() will stop reading from str as soon as a non-numerical character has been read. For example,

i = atoi( "512.035" );

would result in i being set to 512.

atol (String to long)Syntax:

#include <stdlib.h> long atol( const char *str );

The function atol() converts str into a long, then returns that value. atol() will read from str until it finds any character that should not be in a long. The resulting truncated value is then converted and returned. For example,

x = atol( "1024.0001" );

results in x being set to 1024L.

Dynamic Memory Allocation

Dynamic memory allocation is necessary to manage available memory. For example, during compile time, we may not know the exact memory needs to run the program. So for the most part, memory allocation decisions are made during the run time. C also does not have automatic garbage collection like Java does. Therefore a C programmer must manage all dynamic memory used during the program execution. The <stdlib.h> provides four functions that can be used to manage dynamic memory.

NAMEcalloc, malloc, free, realloc - Allocate and free

#include <stdlib.h>

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 111: C Concepts

void *calloc (size_t nmemb, size_t size);void *malloc(size_t size);void free(void *ptr);void *realloc(void *ptr, size_t size);

DESCRIPTIONcalloc() : allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero.

malloc() : allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared.

free() : frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

realloc() : changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

The malloc function

The malloc function allocates a memory block of size n bytes (size_t is equivalent to an unsigned integer) The malloc function returns a pointer (void*) to the block of memory. That void* pointer can be used for any pointer type. malloc allocates a contiguous block of memory. If enough contiguous memory is not available, then malloc returns NULL. Therefore always check to make sure memory allocation was successful by using

void* p;if ((p=malloc(n)) == NULL)return 1;else{ /* memory is allocated */}

Example: if we need an array of n ints, then we can do

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 112: C Concepts

int* A = malloc(n*sizeof(int));

A holds the address of the first element of this block of 4n bytes, and A can be used as an array. For example,

if (A != NULL)for (i=0;i<n;i++)A[i] = 0;

will initialize all elements in the array to 0. We note that A[i] is the content at address (A+i). Therefore we can also write

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

Recall that A points to the first byte in the block and A+I points to the address of the ith element in the list. That is &A[i]. We can also see the operator [] is equivalent to doing pointer arithmetic to obtain the content of the address. A dynamically allocated memory can be freed using free function. For example

free(A);will cause the program to give back the block to the heap (or free memory). The argument to free is any address that was returned by a prior call to malloc. If free is applied to a location that has been freed before, a double free memory error may occur. We note that malloc returns a block of void* and therefore can be assigned to any type.

double* A = (double*)malloc(n);int* B = (int*)malloc(n);char* C = (char*)malloc(n);

In each case however, the addresses A+i, B+i, C+i are calculated differently.• A + i is calculated by adding 8i bytes to the address of A (assuming sizeof(double) = 8)• B + i is calculated by adding 4i bytes to the address of B• C + i is calculated by adding i bytes to the address of C

calloc and realloccalloc and realloc are two functions that can be useful in dynamic memory management

void *calloc(size_t nmemb, size_t size);

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 113: C Concepts

allocates memory for an array of nmemb elements each of size and returns a pointer to the allocated memory. Unlike malloc the memory is automatically set to zero.calloc(n, sizeof(int)) is equivalent to malloc(n*sizeof(int)) except for the fact that calloc block is already initialized. Calloc is appropriate when allocating adynamic array of ints. Another useful function is realloc. Typically in order to resize an existing memory block, one must reallocate a new block, copy the old values to the new block and then free the old memory block.

void *realloc(void *ptr, size_t size);

realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

Realloc function

The realloc() function changes the size of a block of memory that was previously allocated with malloc() or calloc(). The function prototype is

void *realloc(void *ptr, size_t size);

The ptr argument is a pointer to the original block of memory. The new size, in bytes, is specified bysize. There are several possible outcomes with realloc():

If sufficient space exists to expand the memory block pointed to by ptr, the additional memory is allocated and the function returns ptr.

If sufficient space does not exist to expand the current block in its current location, a new block of the size for size is allocated, and existing data is copied from the old block to the beginning of the new block. The old block is freed, and the function returns a pointer to the new block.

If the ptr argument is NULL, the function ac ts like malloc(), allocating a block of size bytes and returning a

pointer to it. If the argument size is 0, the memory that ptr points to is freed,

and the function returns NULL. If memory is insufficient for the reallocation (either expanding the

old block or allocating a new one), the function returns NULL, and

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 114: C Concepts

the original block is unchanged.

Memory LeaksMemory leaks refer to memory that has been allocated by an application, but not properly released back once that memory is no longer needed. Many systems have multiple applications running on their systems and programming errors usually result in “memory leaks”. Memory leaks may not affect the functionality of the application, but left unattended in a system, memory leaks can cause the machine to crash. This is why, servers restart often to avoid them to from going down. Programmers typically allocate memory and then somehow may lose the reference to that memory block. For example, consider the following code.

int A[n],i=0;for (i=0;i<n;i++)A[i] = random();int* B = malloc(2*n);B = A;

The above code initializes a static array A to n random numbers and then requests a memory block (with reference B) that is twice the size of the array A. Then A is assigned to B (note that B = A is a legal assignment. But A = B; isillegal. Why?) This causes the program to lose a reference to the dynamic block of memory and hence that becomes garbage. We call this a “memory leak”. Therefore once you allocate memory and obtain a reference, DO NOT modify the originalreference. You can always define other pointers and copy the address but the original pointer is necessary to free the memory.

Quiz: Consider the following code.int* A = malloc(4*n);int *B = A;free(B);

does this free the original memory?It is a good idea to assign NULL to a pointer that has been freed. Otherwise the pointer still contains the original address and a programmer could accidentally assign valuesto the block that has been freed.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 115: C Concepts

Differences:

break continuebreak is used to skip all the remaining iterations of the loop and abruptly out from loop

continue is used to abruptly skip the current iteration of the loop and continue with next iteration

break is also used in switch continue is not used in switch

for(int i=1;i<10;i++){if(i==5)break;printf(“%d”,i);}

Output: 1,2,3,4

for(int i=1;i<10;i++){if(i==5)continue;printf(“%d”,i);}

Output: 1,2,3,4,6,7,8,9,10

Frequently asked c programs in interview

1. Write a c program to check given number is perfect number or not.2. Write a c program to check given number is Armstrong number or not.3. Write a c program to check given number is prime number or not.4. Write a c program to check given number is strong number or not.5. C program to check a number is odd or even.6. Write a c program to check given number is palindrome number or not.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 116: C Concepts

8. Write a c program to check given string is palindrome number or not.7. Write a c program to solve quadratic equation.8.  Write a c program to print Fibonacci series of given range.9. Write a c program to get factorial of given number.10. Write a c program for Floyd’s triangle.11. Write a c program to print Pascal triangle.12. Write a c program to generate multiplication table.13. Write a c program to print ASCII value of all characters.14. C program to print hello world without using semicolon15. Write a c program which produces its own source code as its output

C program with numbers

1. Write a c program to reverse any number.2. Write a c program to find out sum of digit of given number.3. Write a c program to find out power of number.          4. Write a c program to add two numbers without using addition operator.5. Write a c program to subtract two numbers without using subtraction operator.6. Write a c program to find largest among three numbers using binary minus operator. 7. Write a c program to find largest among three numbers using conditional operator8. Write a c program to find out generic root of any number.9. Write a c program to find out prime factor of given number.10. Write a c program to find out NCR factor of given number.11. Program in c to print 1 to 100 without using loop12. C program for swapping of two numbers

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 117: C Concepts

13. Program to find largest of n numbers in c14. Split number into digits in c programming15. C program to count number of digits in a number

Recursion

Example of recursion in c programming

L.C.M and H.C.F.

1.  Write a c program to find out L.C.M. of two numbers.2. Write a c program to find out H.C.F. of two numbers.3. Write a c program to find out G.C.D. of two numbers.

Swapping

1. Write a c program to swap two numbers.2. Write a c program to swap two numbers without using third variable.3. Write a c program for swapping of two arrays.4. Write a c program for swapping of two string.

Conversion ( Number System )

1. Write a c program to convert decimal number to binary number.2. Write a c program to convert decimal number to octal number.3. Write a c program to convert decimal number to hexa decimal number.4. Write a c program to convert octal number to binary number.5. Write a c program to convert octal number to decimal number.6. Write a c program to convert octal number to hexadecimal number.7. Write a c program to convert hexadecimal number to binary

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 118: C Concepts

number.8. Write a c program to convert hexadecimal number to octal number.9. Write a c program to convert hexadecimal number to decimal number.10. Write a c program to convert binary number to octal number.11. Write a c program to convert binary number to decimal number.12. Write a c program to convert binary number to hexadecimal number.13. C program for addition of binary numbers . 14. C program for multiplication of two binary numbers.15. C program fractional binary conversion from decimal.16. C program for fractional decimal to binary fraction conversion.17. C program to convert decimal number to roman.18. C program to convert roman number to decimal number.19. C program to convert each digits of a number in words20. C program to convert currency or number in word.

Conversion (Unit)

1. C program for unit conversion.

String

1. Write a c program to convert the string from upper case to lower case.2. Write a c program to convert the string from lower case to upper case.3. Write a c program to delete the all consonants from given

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 119: C Concepts

string.4. Write a c program to count the different types of characters in given string.5.  Write a c program to sort the characters of a string.6. Write a c program for concatenation two strings without using string.h header file.7. Write a c program to find the length of a string using pointer.  8. Write a c program which prints initial of any name.9. Write a c program to print the string from given character.10. Write a c program to reverse a string11. Reverse a string using recursion in c12. String concatenation in c without using strcat13. How to compare two strings in c without using strcmp14. String copy without using strcpy in c15. Convert a string to ASCII in c

16. WAP to remove extra spaces in string. For Example

Input string is : jain compters classes

Output String : jain computer classes

17. WAP to print occurrence of every character in a string

18. WAP to reverse each word in string.

Matrix

1. Write a c program for addition of two matrices.2. Write a c program for subtraction of two matrices3. Write a c program for multiplication of two matrices.4. Write a c program to find out sum of diagonal element of a matrix.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 120: C Concepts

5. Write a c program to find out transport of a matrix.6. Write a c program for scalar multiplication of matrix.7. C program to find inverse of a matrix8. Lower triangular matrix in c9. Upper triangular matrix in c10. C program to find determinant of a matrix

File

1. Write a c program to open a file and write some text and close its.2.  Write a c program to delete a file.3. Write a c program to copy a file from one location to other location.4. Write a c program to copy a data of file to other file.5. Write a c program which display source code as a output.6. Write a c program which writes string in the file.7. Write a c program which reads string from file.8. Write a c program which writes array in the file.9. Write a c program which concatenate two file and write it third file.10. Write a c program to find out size of any file.11. Write a c program to know type of file.12. Write a c program to know permission of any file.13. Write a c program to know last date of modification of any file.14. Write a c program to find size and drive of any file.

Series

1. Write a c program to find out the sum of series 1 + 2 + ….  + n.2. Write a c program to find out the sum of series 1^2 + 2^2 + ….

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 121: C Concepts

+ n^2.3. Write a c program to find out the sum of series 1^3 + 2^3 + …. + n^3.4. Write a c program to find out the sum of given A.P.5. Write a c program to find out the sum of given G.P.6. Write a c program to find out the sum of given H.P.7. Write a c program to find out the sum of series 1 + 2 + 4 + 8 … to infinity.

Array

1. Write a c program to find out largest element of an array.2. Write a c program to find out second largest element of an unsorted array.3. Write a c program to find out second smallest element of an unsorted array.4. Write a c program which deletes the duplicate element of an array.5. Write a c program for delete an element at desired position in an array.6. Write a c program for insert an element at desired position in an array.7. C program to find largest and smallest number in an array

Sorting

1. Write a c program for bubble sort.2. Write a c program for insertion sort.3. Write a c program for selection sort.

Recursion

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 122: C Concepts

1. Write a c program to find factorial of a number using recursion.2. Write a c program to find GCD of a two numbers using recursion.3. Write a c program to find out sum digits of a number using recursion.4. Write a c program to find power of a number using function recursion.5. Write a c program to reverse any number using recursion.

Size of data type

1. Write a c program to find the size of int without using sizeof operator.2. Write a c program to find the size of double without using sizeof operator.     3. Write a c program to find the size of structure without using sizeof operator.4. Write a c program to find the size of union without using sizeof operator.

Using pointer

1. Write a c program for concatenation two string using pointer.

Searching

1. Write a c program for linear search.2. Write a c program for binary search.3. Write a c program for binary search using recursion.

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 123: C Concepts

break continue

The break statement in c completely

terminates the execution of the current

loop, and processes the statement

which is placed immediately after the

loop.

The continue statement just skips the

current iteration of the loop and

processes the next iteration in the loop.

break statement is also used with

switch

continue statement not working with

switch

Example:

for (int i = 1; i <= 10; i++)

{

   if (i == 5)

   {

     break;

   }

   //

printf(“%d”, i);

}

//

printf("Statement after the for Loop");

Output

1

2

3

4

Statement after the for Loop

Example:

for (int i = 1; i <= 10; i++){   if (i == 5)   {     continue;   }   //   printf(“%d”, i);}//printf ("Statement after the for Loop");

Output

1

2

3

4

6

7

8

9

10

Statement after the for Loop 

while do while

while loop checks the condition before

it enters the loop.

do while loop first executes the

statements of loop and then checks the

condition.

if condition is false for 1st time, then

statements inside loop will not execute.

if condition is false for 1st time, then

statements inside loop will execute. It

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 124: C Concepts

means do while executes at least once.

syntax:

while(condition/Expression)

{

// statements

}

syntax:

do

{

// statements;

}while(condition/Expression);

Example:

int main()

{

int i=5;

while(i==6)

{

printf(“inside while loop”);

}

printf(“outside of while loop”);

getch();

}

Output

outside of while loop

Example:

int main()

{

int i=5;

do {

printf(“inside do while loop”);

}while(i==6);

printf(“outside of do while loop”);

getch();

}

Output

inside do while loop

outside of do while loop

Structure Union

Structure is an mechanism to create

user defined variables which can take all

the attributes defined inside structure at

same time

Union is a mechanism to create user

defined variables which can take only a

single attribute defined inside union at

a time.

Totol memory requirement for structure

is equal to the size of all its attributes

(members defined inside structure)

Totol memory requirement for union is

equal to the size of all its biggest

attribute (members defined inside

Union)

Concept Example :

a student can have roll number, name,

address , email and many more attribute

at same time. so if we want to create

data type which represent student ,

create student structure in c.

Concept Example:

Journey can be done either train, plane

or bus, but at the same time,

passenger can pick only one thing. so

if we want to create Journey datat

type, create Journey Union.

syntax: syntax:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 125: C Concepts

struct [structure name]

{

// members declaration;

};

union [union name]

{

// member declaration;

};

Example:

struct student

{

int roll_no;

char name[20];

char address[20];

};

void main()

{

struct student s; // student variable

s.roll_no=1;

s.name=”shyam”;

s.address=”JNV Road”;

printf(“size of structure is :

%d” ,sizeof(struct student));

}

Output

in turbo c compiler

size of structure is : 42

Example:

union journey

{

int train_id;

int bus_id;

int plane_id;

};

void main()

{

union journey j; // journey variable

j.train_id=10;

j.bus_id=20;

j.plane_id=30;

// now value for each variable is 30

printf(“size of union is :

%d” ,sizeof(union journey));

}

Output

in turbo c compiler

size of structure is : 2

pointer array

pointer is user defined data type which

contains memory address for a variable.

array is user defined data type which is

finite collection of similar type data.

deferencing operator is used to access

value which is pointed by the pointer.

[] operator with indexed values is used

to access array variable

syntax:

int *p;

// above declaration means p is pointer

which contains an address and value at

address is integer value.

syntax:

int arr[5];

// above declaration means arr is an

array which contains 5 integer values.

Example: Example:

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 126: C Concepts

void main()

{

int i=10;

int *p; // delaration of pointer

p=&i; // initialization of pointer

printf(“%d”,*p); //using of pointer

}

void main()

{

int arr[5]; // declaration of array

// initialization and printing array

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

{

scanf(“%d”,&arr[i]);

printf(“%d”,arr[i]);

}

}

malloc calloc

malloc () function is used to allocate

memory in heap. It allocated memory

block and returns the address of first

memory if successfully done else

returns NULL

calloc () function is used to allocate

memory in heap. It allocated number of

memory block and returns the address

of first memory if successfully done else

returns NULL

malloc() initialize memory with garbage

value during allocation

calloc () initialize memory with zero

value during allocation

malloc() takes only a single argument,

which is the size of memory

calloc() takes two arguments, first

specifies the number of block and

second specifies the size of block

syntax:

void *p = malloc(10);

/* it will allocate 10 memory and returns

the address of first allocated memory */

syntax:

void *p=calloc(5,10);

/* it will allocate 5 blocks each 10 bytes,

and returns address of first allocated

byte */

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner

Page 127: C Concepts

Shishav jain- 8290280309 Understanding C Jain Computer Classes , C-78 Samta Nagar Bikaner