Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
58 views

CS3353 Unit 1

This document discusses the fundamentals of C programming, including its history, structure, data types, and basic components. It was developed in 1972 at Bell Labs and standardized in 1988. A C program consists of preprocessing directives, global declarations, the main function, and optional other functions. It uses various data types and operators. The compilation process involves saving, compiling, and executing the code to generate executable files.

Uploaded by

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

CS3353 Unit 1

This document discusses the fundamentals of C programming, including its history, structure, data types, and basic components. It was developed in 1972 at Bell Labs and standardized in 1988. A C program consists of preprocessing directives, global declarations, the main function, and optional other functions. It uses various data types and operators. The compilation process involves saving, compiling, and executing the code to generate executable files.

Uploaded by

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

CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

UNIT- I
C PROGRAMMING FUNDAMENTALS
Data Types – Variables – Operations – Expressions and Statements – Conditional Statements –
Functions – Recursive Functions – Arrays – Single and Multi-Dimensional Arrays.
HISTORY OF C LANGUAGE:
 C is a case sensitive language and structure oriented language.
 C is a general purpose, block structured, procedural, case sensitive, free flow, portable and high- level
programming Language.
 Developed at AT&T’s Bell Labs of USA in 1972.
 Designed and written by Mr. Dennis Ritchie.
 American National Standards Institute (ANSI) standardized the definition of the C language as “ANSI C”
in 1988.
CHARACTERISTIC OF C:
 It is a highly Structured, Procedural, free-flow Language.
 It uses features of High Level Languages
 It is a powerful, efficient, portable and robust language.
 It can handle bit level operations.
 C is a machine-independent language, highly portable.
 It supports variety of data-types and powerful set of operators.
 It supports dynamic memory management by using Pointers.
 It enables hierarchical and modular programming with help of functions.
 C can extend itself by addition of functions to its library continuously.
 C is also used in many real-time systems programming.

STRUCTURE OF A “C” PROGRAM:


 The C program is made of number of building blocks, called functions or modules.
 Each function performs a specific task. A function is subroutine that may consists of one or more
statements.
Documentation Section /* First Program */
Link Section # include <stdio.h>
Definition Section # define PI 3.14
Global Declaration Section float a,b
main() function section
{
Declaration Part char a,b; int a,b;
Executable part
}
Sub Program Section
function 1
function 2
…………………………. User defined functions
function n
DOCUMENTATION SECTION (Comments statement)
 Comments are necessary in the program in order to understand the flow of a program.
 It is useful for documentaion.

1
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Single line comment:


 A single line comment starts with two forward slashes (//) and is automatically terminated with the end
of the line.
Multi-line comment:
 A multi-line comment starts with /* and terminates with */. A multi-line comment is used when multiple
lines of text are to be commented
Ex: /* This is a multiple lines statement */
// This is single line statement
PREPROCESSOR DIRECTIVES (LINK SECTION):
 #include<stdio.h> is a Preprocessor directive statement.
 The preprocessor statements begin with # symbol and are also called the preprocessor directive.
 These statements instruct the compiler to include C preprocessors such as header files and symbolic
constants before compiling the C program.
1. Preprocessor directive always starts with a symbol #.
2. The symbol # should be the first non-white space character in a line.
3. It should be terminated with a new line character.
4. Preprocessor directive are executed before the compiler compiles the source code.
Ex: #include<stdio.h> #include "stdio.h"
SYMBOLIC CONSTANTS:
 It is used to define or set values to variables.
Ex : #define PI 3.14
#define MAX 100
GLOBAL DECLARATION SECTION:
 This section declares some variables, known as global variables that are used in more than one
fuction.This section must be declared outside of all the functions.
Ex :int a,b;
MAIN FUNCTION SECTION:
 Every program written in C Language must containg main() function.
 Empty paraenthisis after main is necessary. Except main() function,other section may not be necessary.
 C program execution starts with the main() function. Usually, the main() function is prefixed with a void
return data type.
 The program starts from the opening brace{ and ends with closing brace }
Ex: main(), void main() , int main(),char main(),float main()
Declaration part
 The variables in C program must be declared first before it is used. A variable could be initialized with
an initial value.
Ex: int a=10, b=20;
Executable part
 The part contains a set of statements following the declaration of the variables.
Ex : {
c=a+b;
printf ("the sum is=%d",c) ;
}
SAMPLE C PROGRAM:
#include <stdio.h>
int main(void)
{

2
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

printf(“C is Sea\n”);
return 0;
}
PROGRAMMING RULES:
1. Statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constant.
3. The programmer can also write the statement within the two brace
4. The statements should end with semicolon(;)
5. Every program must have exactly one main function, more that one main function the compiler cannot
understand.
6. The opening and closing brace should be balanced.
COMPILATION AND LINKING PROCESSES:
If the code has been written, follow the steps to execute the program:
1. Save program:
With .c extension. This will help in retrieving the code in case the program crashes upon execution.
2. Compile program:
 The shortcut for this is step is the alt+f9 key. If working with Borland turbo C 4.5 go to the project menu
and invoke the compilation option. It has shortcut key.
 If there are errors, check that you have written code properly. There should be no typing mistake. If there
are no errors, you can execute the program.
 It generate object file “.obj”
3.Execute/run program:
 The shortcut for this is step is the ctrl+f9 key. If working with Borland turbo C 4.5, The shortcut for this
step is alt+f5. In Borland turbo C 4.5
 It generate executable file “.exe”.
4. See the output:
 The shortcut for this step is alt+f5. In Borland turbo C 4.5 and In Microsoft visual C++ 6.0, the output
screen automatically pop-up.
C CHARACTER SET:
 A character set is used to define the valid characters that can be used in a source program or interpreted
when a program is running.

Fig 1.1
Source Character set:
• The set of characters that can be used to write a source program is called Source Character set.
• It consists of the following:
1. Alphabets both in lower and upper case letters (A,B,C...Z and a,b,c...z)
2. Digits (0 to 9)
3. White Space characters ( enter,tabs, blankspace,etc.,)
Blank Space character
Horizontal Tab space character
Carriage Return, New Line, Form Feed character
3
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Special Characters ’ " ( ) * + - / : = ! & $ ; < > % ? , . ˆ # @ ˜ { } [ ] \ | space


Execution character set:
• The set of characters available when the program is being executed is called Execution character set.
• It consists of the following escape sequences

Characters Escape Sequence


Back Space \b
Horizontal Space \t
Vertical Space \v
Newline \n

Table 1.1
TOKENS:
• Tokens are the basic lexical building blocks of source code.
• There are five classes of tokens: identifiers, reserved words, operators, separators, and constants.
Identifiers:
 An identifier is a sequence of characters invented by the programmer to identify or name a specific
object and name is formed by a sequence of letters, digits, and underscores.
 Identifiers are names given to various program elements, such as variables, functions and arrays etc.
 They are user defined names consisting sequence of letters and digits, with the letter as the first
character.
 The underscore symbol( _ ) can be used as an identifier.
 A variable is an entity data name that may be used to store a data value.
 Uppercase and lowercase are significant.
Ex: average, total_marks
Keywords:
• Keywords are explicitly reserved words that have a strict meaning as individual tokens to the compiler.
 The C keywords are reserved words by the compiler.
 Key words have standard and predefined meaning in C language which cannot be changed and they are
the basic building blocks for program statements.
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Table 1.2 Keywords in C language
Operators:
• Operators are tokens used to indicate an action to be taken (usually arithmetic operations, logical
operations, bit operations, and assignment operations). Operators can be simple operators (a single
character token) or compound operators (two or more character tokens)
Separators:
• Separators are tokens used to separate other tokens. Two common kinds of separators are indicators
of an end of an instruction and separators used for grouping.
Constants:
• Constants are values that are fixed in a program.
• The value of the constant cannot change during execution.
• Say we have the following piece of code,
4
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

if(x<5)
x = x + 2;
else
x = x + 10;
• Here the tokens that will be generated are
 Keywords : if , else
 Identifier : x
 Constants : 2, 10,5
 Operators : +,=
 Separator : ;
Constants are classified into two categories.

Fig 1.2
1. NUMERIC CONSTANTS:
It can be sub divided into two types
a. Integer constants.
b. Real constants.
a. Integer constants:
 Numbers that have no decimal point and no fractional part.
Ex: 6 789 2345
b. Real constants:
 Numbers that have a decimal point and may have a fractional part.
Ex: 3.25 3456.12
Rules for Numeric constants
 A positive number can be preceded by a + sign.
 If a number is negative it can be preceded by a – sign.
 Special characters other than + - . are not allowed anywhere in the constant.
 No commas or blank are allowed.
2. NON-NUMERIC CONSTANTS:
It can be sub divided into two types
a. Character constants.
b. String constants.
a. Character Constants:
 A character constant is a single alphabet, a single digit or a single special symbol enclosed within single
quotes.
 The maximum length of a character constant can be 1 character
Ex: ‘a’, ‘1’, ‘5’, ‘=‘
Backslash Character (Escape sequence)Constants
C supports special backslash character constants that are used in output functions. These character
combinations are known as escape sequences.

5
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Escape Sequences Meaning


\0 Null
\b Backspace
\t Horizontal tab
\n New line
\v Vertical tab
\f Form feed
\r Carriage return
\” Double quote
\’ Single quote
\? Question mark
\\ Backslash
Table 1.2.1
b. String constants.
 A String Constants are sequence of characters enclosed in double quote marks.
 The string may be a combination of all kinds of symbols.
Ex: “INDIA” “ 2345”
VARIABLES:
• Programs operate on data.
• The instructions that make up the program, and the data that it acts upon, have to be stored somewhere
while the computer is executing that program.
• A variable is an identifier for a memory location in which data can be stored and subsequently recalled.
• Variables are used for holding data values so that they can be utilized in various computations in a
program
• All variables have three important attributes.
• A data type that is established when the variable is defined, e.g., integer, real, character.
• Once defined,the type of a C variable cannot be changed.
• A name of the variable
• A value that can be changed by assigning a new value to the variable.
• The kind of values a variable can assume depends on its type.
• For example, an integer variable can only take integer values, e.g., 2, 100, –12.
Rules for defining variables:
 They must begin with a character without spaces but underscore is permitted.
 The variable should not be a key word.
 The variable name should not start with a digit.
 The length of the variable varies from a compiler to another.
Variable Declaration
 Declaration introduces one or more variables within a program.
 Definition, on the other hand, directs the compiler to actually allocate memory for the variable.
 A declaration statement begins with the type, followed by the name of one or more variables.
 The general form is
data_type variable_name_1, variable_name_2, ...,variable_name_n;
 Declaration of multiple variables of the same data types can be done in one statement. For example,
int a;
int b;
int c;

6
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

can be rewritten as
int a, b, c;
Initializing variables
 Variables declared can be assigned or initialized using an assignment operator =
 The declaration and initialization can also be done in the same line.
Syntax:
data_ type variable_name = constant value;
Example:
int sum=0;
int salary=3000;
Constant and volatile variables
Constant:
 The values of some variable may be required to remain constant through-out the program.
 We can do this by using the qualifier const at the time of initialization.
Syntax:
const datatype variable name=value;
Example:
const int class_size = 40;
 The const data type qualifier tells the compiler that the value of the int variable class_size may not be
modified in the program.
Volatile variable:
 A volatile variable is the one whose values may be changed at any time by some external sources.
 Syntax:
volatile datatype variable name=value;
Example:
volatile int d;
DATA TYPES:
• The data type determines the set of values that a data item can take and the operations that can be
performed on the item.

Fig 1.3 Classification of Data Types


PRIMARY (OR) BASIC DATA TYPES consist following data types:
Integer:
 Integers are whole numbers with a machine dependent range of values.
 C has three classes of integer storage namely: int, short int, and long int.
 All of these data types have signed and unsigned forms (qualifiers).
Float:
 It represents a real number.
 Floating point numbers are denoted by the keyword float.

7
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Double:
 When the accuracy of the floating point number is insufficient, we can use the double to define the
number.
 The double is same as float but with longer precision.
 To extend the precision further we can use long double which consumes 80 bits of memory space.
Character:
 A single character can be defined as a character type of data.
 Characters are usually stored in 8 bits of internal storage.
 The qualifier signed or unsigned can be explicitly applied to char.
VOID:
 Using void data type, we can specify the type of a function.
 It is a good practice to avoid functions that does not return any values to the calling function.
Data type Size Format Range Use
(bytes) Specifiers
char 1 %c -128 to 127 To store characters
unsigned char 0 to 255
1 %c

signed char 1 -128 to 127


int 2 %d -32,768 to 32,767 To store integer numbers
unsigned int 2 %u 0 to 65535
signed int 2 –32768 to 32767
short int 2 %i -32,768 to 32,767
unsigned short int 2 0 to 65535
signed short int 2 –32768 to 32767
–2147483648 to
long int 4 %l
2147483647
unsigned long int 4 0 to 4294967295
–2147483648 to
signed long int 4
2147483647
3.4 E-38 to 3.4 E+38 To store floating point
float 4 %f or %g
numbers
double 8 %lf 1.7 E-308 to 1.7 E+308 To store big floating point
long double 10 %lu 3.4 E-4932 to 1.1 E+4932 numbers
Table 1.3
DERIVED DATA TYPES:
ARRAY:
 An Array is a data structure used to store homogenous data elements in successive memory
location.
 It is linear and homogenous data structure.
 It stores similar data type elements in one variable name in memory.
Ex :int salary[15]; where 'salary' is an array of integer data type which contains 15 elements.
 All the elements of an array share a common name known as array name.
 The position of an element in an array is specified with an integer value known as index or subscript.
 Arrays use indices or subscripts to access their elements known as indexed variables or sub scripted
variables
 Example : int a[5], char ch[10],float sal[10],long num[5];

8
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

POINTER:
 It is a variable that holds the address of a variable or a function
Syntax:
Datatype *pointer_name;
 Here * is called as Indirection Operator.
 Example : int *ptr -> ptr is a pointer to an integer
float *fptr ->fptr is a pointer to float
FUNCTION:
 A function is a self-contained block
 It is a subprogram of one or more statements
 It performs a specific task when the function is called.
Example:
void main( )
{
int a=10;
printf(“In main number is %d”, a);
void display( );
}
void display( )
{
int b=5;
printf(“ In display , the value of number is %d”, b);
}
USER DEFINED DATATYPES:
STRUCTURE:
 A structure is a collection of one or more variables of different data types grouped together under a
single name.
 It contains different data types.
Example:
struct student
{ // structure template
int rollno;
char name[100];
char address[100];
};
struct student s1,s2,s3; // structure declaration
UNION:
 Union is a collection of variables similar to structure.
 The union requires bytes that are equal to number of bytes required for the largest number.
Example:
union student
{
char name[20];
int rollno,m1,m2,m3,tot;
float avg;
}s1;

9
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

ENUMERATION:
 It can be used to declare variables that can have one of the values enclosed within the braces.
enum identifier {value1,value2,……value n};
Example 1:

Example 2 :
include <stdio.h>
int main()
{
enum days{ Sunday,Monday,Tuesday,Wednesday,Thursday, Friday,Saturday};
…..
}

OPERATORS AND EXPRESSIONS:


• An operator is a symbol that specifies the mathematical, logical, or relational operation to be performed.
Expression:
• An expression is any computation that yields a value.

Fig 1.4 Classifications of Operators in C Language


Arithmetical Unary
+ (unary) - (unary) + + (Increment) - - (Decrement)
Binary
+ Addition - Subtraction * Multiply / Divide
% Modulus
Ternary
?: Discussed later on
Assignment Simple Assignment
=
Compound Assignment
+= ,- = , *= , /= , %= ,&= , ^= , |=
Expression Assignment
A=5+(b=8+(c=2))-4
Relational >, < , >= , <=
Equality = = (Equal to) != (Not Equal to)
Logical && (Logical AND) || (Logical OR) ! (Logical NOT)

10
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Bitwise & (Bitwise AND) | (Bitwise OR) ~ (Complement)


^ (Exclusive OR) >> (Right Shift) << (Left Shift)
Others , (Comma) (*) indirection
. (membership operator) -> (membership operator)
Table 1.4
A+B Where ‘+’ is operator and ‘a’ , ‘b’ are the operands.
ARITHMETIC OPERATORS IN C:
 There are three types of arithmetic operators in C: Binary, Unary, and Ternary.
BINARY OPERATOR:
Operator Name Example
+ Addition 12 + 4.9 /* gives 16.9*/
- Subtraction 3.98 – 4 /* gives –0.02 */
* Multiplication 2 * 3.4 /* gives 6.8 */
/ Division 9 / 2.0 /* gives 4.5 */
% Remainder 13 % 3 /* gives 1 */
UNARY OPERATORS:
 The unary ‘–’ operator negates the value of its operand (clearly, a signed number).
Unary increment and decrement operators:
 The unary ‘++’ and ‘--’ operators increment or decrement the value in a variable by 1
Basic rules for using ++ and – – operators:
 The operand must be a variable but not a constant or an expression.
 The operator ++ and -- may precede or succeed the operand.
Example: int i = 42;
i++; /* increment contents of i, same as i = i + 1; */
/* i is now 43 */
i— —; /* decrement contents of i, same as i = i – 1; */
/* i is now 42 */
++i; /* increment contents of i, same as i = i + 1; */
/* i is now 43 */
– –i; /* decrement contents of i, same as i = i – 1; */
/*I is now 42 */
Postfix Operation:
(a) x = a++;

First action: Store value of a in memory location for variable x.


Second action: Increment value of a by 1 and store result in memory location for variable a.
(b) y=b- -;

First action: Put value of b in memory location for variable b.


Second action: Decrement value of b by 1 and put result in memory location for variable b.
Prefix Operation:
(a) x = ++a;

11
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

First action: Increment value of a by 1 and store result in memory location for variable a.
Second action: Store value of a in memory location for variable x.
(b) y= - -b;

First action: Decrement value of b by 1 and put result in memory location for variable b.
Second action: Put value of b in memory location for variable y.
Example: a=5;
b=++a;
b=6,a=6
b=a++;
b=5,a=6
RELATIONAL AND EQUALITY OPERATORS:
 Relational operators are used to compare two quantities (i.e. their operands).
 Relational operators are used to compare two or more operands.
 Operands may be variables, constants or expression
 The equality operators have lower precedence than the relational operators
S.N Operator Name of Operator Category -ary of Example Return Associativity
o operator value
1 < Less than Relational Binary 12 < 9 0 L -.>R
> Greater than operators 6 >2 1
<= Less than or Equal to 2<=2 1
>= Greater than or Equal 13>=9 1
to
2 == Equal To Equality Binary 2= =3 0 L ->R
!= Not Equal To Operators 3!=3 0
Table 1.4.1
Syntax:
AE1 relational operator AE2
Where AE1 and AE2 are constants or expression values
 If the relation is true then it returns a value 1, otherwise 0 for false relation.
LOGICAL OPERATORS:
 Logical operators are used to combine the results of two or more conditions.
 It is used to logically relate the sub-expressions.
S.No Operator Action Example Return value
1 && Logical AND 5 < 6 && 6 < 6 0
2 || Logical OR 5 < 6 || 6 < 5 1
3 ! Logical NOT ! (5= =5) 0
Table 1.4.2 Logical Operators

12
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

i) &&- This operator is used when two or more expressions are true.
Eg: (exp1)&&(exp2).
ii) ||- This is used in situation, if either of them (one at least) is true from two or more conditions.
Eg: (exp1) || (exp2).
iii) !- This operator reverses the value of the expression it operates on. i.e., it makes a true expression
false and false expression true.
Eg: !(exp1)
ASSIGNMENT OPERATORS:
 Assignment operators are used to assign a value to another variable.
Syntax:
Variable= expression (or) value;
 The usual assignment operator is ‘=’.
Eg: x=10;
x=a+b;
x=y;
 In addition, C has following Shorthand assignment operators,
Eg: x += 1;
This is same as the statement, x = x + 1;

Table 1.4.3
Abbreviated (Compound) assignment expressions:
 It is frequently necessary in computer programs to make assignments such as n = n + 5;
 C allows a shorter form for such statements, as shown.
 n += 5;
 n –= 5; /* is equivalent to n = n – 5; */
 n *=5; /* is equivalent to n = n * 5; */
 n /= 5; /* is equivalent to n = n / 5; */
 n %= 5; /* is equivalent to n = n % 5; */
Conditional Operator:
 A ternary operator pair “?:” is available in C to construct conditional expression of the form
Expression1 ? Expression2 : Expression3;
 Here Expression 1 is a condition which is evaluated first.
 If it is true then the expression2 is evaluated and becomes the value of the expression.
 If the condition is false then the expression3 is evaluated and its value becomes the value of the
expression.
Example:
int a=5,b=3,c=7,small;
small = (a < b ? ( a < c ? a : c) : ( b < c ? b : c ) );

13
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

BITWISE OPERATORS:
 Bit wise operators are used to manipulate the data at bit level.
 It operates on integers only and not applied to float or real.
 These operators do not consider the operand as one entity and operate on the individual bits of the
operands.
 C has the following bitwise operators.
Operator Name of operator Category Precedence -nary of operator associativity
~ Bitwise NOT Unary Level 1 Unary r->l
>> Left shift Shift operators Level 2 Binary l->r
<< Right shift
& Bitwise AND Bitwise operator Level 3 Binary l->r
^ Bitwise X-OR Bitwise operator Level 4 Binary l->r
| Bitwise OR Bitwise operator Level 5 Binary l->r
Table 1.4.4
Example Octal Value Bit Sequence
X 011 0 0 0 0 1 0 0 1
Y 027 0 0 0 1 0 1 1 1
~X 366 1 1 1 1 0 1 1 0
X&Y 001 0 0 0 0 0 0 0 1
X|Y 037 0 0 0 1 1 1 1 1
X^ Y 036 0 0 0 1 1 1 1 0
X << 2 044 0 0 1 0 0 1 0 0
X >> 2 002 0 0 0 0 0 0 1 0
Table 1.4.5
MISCELLANEOUS OPERATORS (OR) SPECIAL OPERATORS:
1.Comma operator( , ):
 The comma operator is used to separate two or more expressions.
 The operator has the lowest priority among the entire operator.
 Ex: a=2,b=4,c= a+b;
2.The sizeof ( ) operator:
 Sizeof operator is used to determine the size in bytes, which a value will take in memory.
 The sizeof() is a unary operator, that returns the length in bytes of the specified variable.
 It is very useful to find the bytes occupied by the specified variable in the memory.
Syntax:

 Where var is the variable for which to fine the size


Ex: Void main()
{
int a;
Printf(“size of the variable a is ……%d”, size of(a));
}
Output: Size of the variable a is……. 2
Operator precedence:
 Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated.

14
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom.
 Within an expression, higher precedence operators will be evaluated first.
Operator Associativity Operator Associativity
() [] -> ++ -- left-to-right & left-to-right
++ -- + - ! ~ (type) right-to-left left-to-right
^
*(indirection) &(address) sizeof
* / % left-to-right | left-to-right
+ - left-to-right && left-to-right
<< >> left-to-right || left-to-right
< <= > >= left-to-right ?: right-to-left
left-to-right = += -= *= /= %= &= ^= right-to-left
= = !=
|= <<= >>=
, left-to-right
Table 1.4.6

TYPE CONVERSIONS:
 In C, the type of a value can be changed during the run time of a program. This is known as type
conversion or type cast.
 In an expression, if an argument is long data type, all arguments are cast to long
 In an expression, if an argument is unsigned, all arguments are cast to unsigned
int a = 3;
float b = 5.0;
float c = a + b; /* a is transformed into double */

MANAGING INPUT AND OUTPUT OPERATIONS:

Fig 1.5
Formatted Input & Output functions:
• C uses two functions for formatted input and output.
1. Formatted input : reads formatted data from the keyboard.(scanf)
2. Formatted output : writes formatted data to the monitor.(printf)

Fig 1.5.1

15
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

FORMATTED I/O FUNCTIONS:


FORMATTED I/O Functions Syntax Example Program
1.scanf() scanf(“format #include <stdio.h>
 Scanf function reads the specifiers”, &var1, main() /* program which introduces keyboard input
formatted data from keyboard. &var2, . . . &varn); */
 It reads all types of data {
values. Example int number;
scanf(“%d”,&number); printf("Type a number \n");
scanf("%d", &number);
printf("The number you typed was %d\n", number);
}
OUTPUT:
Type a number 100
The number you typed was 100
1.1. Reading strings from the scanf(“format /*Reading strings from the Keyboard using Scanf
Keyboard using scanf specifiers”, &var1, function*/
&var2, . . . &varn); #include <stdio.h>
The scanf function with %s void main()
format specification can be used {
to read a string from the user Example char name[20];
and store it in a character array. scanf("%s", &name); printf("Enter your name \n");
scanf("%s", &name);
printf("your name is %s\n", namber);
}
OUTPUT:
Enter your name williams
your name is williams
2.printf() printf(“format #include <stdio.h>
 printf() function is used for specifiers”, var1, var2, .. void main()
printing variables and text . . varn) ; {
 It prints all types of data printf("Programming in C is easy.\n");
values. printf("And so is Pascal.”);
 It requires format specifiers Example }
and variable names to print the printf(“%d”,number1); Output:
data. Programming in C is easy.
 It prints the text appears in And so is Pascal.
double quotes "" without
modification
2.2. Printing Strings on the printf(“format #include <stdio.h>
Screen using printf function specifiers”, var1, var2, .. // Printing strings using printf function
The printf function can be used . varn) ; void main()
to print a string literal constant, {
the contents of a character array. char country_name[10]=”INDIA”;
Example printf("your country name is %s\n",
printf(“%s”,name); country_name);
}

16
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Format Specifiers used in Formatted I/O(scanf and printf) functions:


Formatted Specifier Effect
%d read a decimal integer
%o read an octal value
%x read a hexadecimal value
%h read a short integer
%l read a long integer
%f read a float value
%e read a double value
%c read a single character
%s read a sequence of characters or String
Table 1.5
UNFORMATTED I/O FUNCTIONS:
UNFORMATTED I/O Functions Syntax Example Program
1.getchar() Variable void main()
 Reads the character type name=getchar() {
data from the standard Example char c;
input. C=getchar() printf(“enter a char”);
 It reads one character at a c=getchar;
time till the user presses the printf(“a=%c”,c);
enter key }
OUTPUT:
enter the char g
a=g
2.putchar() Syntax: void main()
Putchar(variable {
This function prints one character name); char c=’C’;
on the screen at a time, which Example: putchar(c );
readby the standard input. Char c=’C’ }
Putchar(c); OUTPUT:
C
3.getche() and getch() Syntax: void main()
Getch(); {
 This functions read the Getche(); printf(“enter two alphabets”);
alphanumeric characters getche();
from the standard input getch();
device. }
 The character entered is not OUTPUT:
displayed by enter any two alphabet a
getch()function Explanation:
 Getche() accepts and  In the above program,even though the two
displays the character. characters are entered,the user can see only
one character on the screen .
 The second character is accepted by getch()
but not displayed on the console.
 The getche() accepts and displays the
character .

17
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

4.putch() Syntax: void main()


This function prints any putch(variable name); {
alphanumeric character taken by char ch;
the standard input device. printf(“press any key to continue”);
ch=getch();
printf(“ you pressed:”);
putch(ch);
}
OUTPUT:
Press any key to continue
you pressed:9
5.gets() Syntax: void main()
This function is used for accepting gets(variable name); {
any string through stdin(key board) Example: char ch[30];
until the enter key is pressed. gets(ch); prinf(“enter the string\n”);
gets(ch);
printf(“\n entered string is %s”,ch);
}
OUTPUT:
enter the string: hello world
entered string: hello world.
Difference between scanf and The scanf function void main()
gets while using string reads the characters {
only up to the first char ch[30];
white-space character. prinf(“enter the string\n”);
But gets function scanf(“%s”,&ch);
accepts any string until printf(“\n entered string is %s”,ch);
the enter key is }
pressed OUTPUT:
enter the string: hello world
entered string: hello
6.puts() Syntax: void main()
This function prints the string or puts(variable name); {
character array Example: char ch[30];
puts(ch); printf(“enter the string;”);
gets(ch);
puts(“entered sring”);
puts(ch);
}
OUTPUT:
enter the string: puts in use
entered string: puts in use
7.cgets() Syntax: void main()
This function reads string from the cgets(variable name); {
console. Example: char *t;
cgets(char *st); printf(“\n enter text here”);

18
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

cgets(t);
8.cputs() Syntax: t=t+2;
This function displays string on the cputs(variable name); printf(“\n your entered text”);
console cputs(t);
Example: }
OUTPUT:
cputs(char *st);
enter text here: how are you?
your entered text: how are you?

DECISION MAKING AND BRANCHING:


• The order in which statements are executed in a running program is called the flow of control.
• Controlling the flow of a program is a very important aspect of programming.
• Control flow relates to the order in which the operations of a program are executed.
• Control statements embody the decision logic that tells the executing program what action to carry out
next depending on the values of certain variables or expression statements.
• The control statements include selection, iteration, and jump statements that work together to direct
program flow.
• A selection statement is a control statement that allows choosing between two or more execution paths in a
program.
• The selection statements in C are the if statement, the if else statement, and the switch statement.
• These statements allow us to decide which statement to execute next.
• Each decision is based on a boolean expression (also called a condition or test expression), which is an
expression that evaluates to either true or false.
• The result of the expression determines which statement is executed next.
• The programming mechanism that executes a series of statements repeatedly a given number of times, or
until a particular condition is fulfilled, is called a loop.
• The construct used for loop is known as iteration statement.
• C language offers three language elements to formulate iteration statements: while, do-while, and for.
• Jump statements transfer the control to another point of the program.
• Jump statements include goto, break, continue and return.

CONDITIONAL STATEMENTS:
1. If statement 2.If…. Else statement
Syntax if(Test Expr) if(Test Expr)
{ {
Stmt 1; Stmt 1;
…… }
Stmt n; else
} {
Stmt x; Stmt 2;
}
Working of  Single-entry/single-exit control 1. The if -else statement is used to express decisions
the structure 2. The expression is evaluated; if it is true {that is,
statement  Performs statement block only if expression has a non-zero value}, statement 1
when the condition is true is executed.
3. If it is false {expression is zero} and if there is an
else part, statement 2 is executed instead.

19
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Flow

Example #include<stdio.h> #include<stdio.h>


#include <conio.h> int main()
int main ( ) {
{ int marks;
int a; printf("\nEnter a number:");
clrscr( ); scanf(“%d%d”,&a&b);
printf("\nEnter a number:"); if (a>b)
scanf("%d",&a); {
if(a>10) printf (“a is larger than b)”;
{ }
printf(" a is greater than 10"); else
} {
getch( ); printf (“a is NOT larger than b)”;
return 0; return 0; }
}
OUTPUT
Enter a number: 12
OUTPUT
Enter the number: 12 a is larger than b
a is greater than 10 Enter a number: 1
a is not larger than b
3.Nested if…else… statement 4.Switch… case statement
Syntax if ( test condition-1 ) switch(expr)
{ {
if ( test condition-2 ) case constant1: stmtList1;
{ break;
statement-1; case constant2: stmtList2;
} break;
else case constant3: stmtList3;
{ statement-2; break;
} ………………………….
} ………………………….
else default: stmtListn;
{ }
statement-3;
}
statement-x;
working of Nested if-else The switch statement is a multi-way branch statement.
the 1. Writing an if statement with in 1. The expression in switch statement must be a integer
statements another if is called as nested if. value or a character constant.(no real numbers allowed)

20
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

2. It is used to check more than 2. Each case block or default block must be terminated
one condition at a time with a break statement
3. The default is optional and can be placed anywhere
but usually placed at the end
4. The case keyword must be terminated with colon(:)
5. In absence of break statements all the statements that
are followed by matched cases are executed.
Flow

Example //Using nested if else statement #include<stdio.h>


#include <stdio.h> #include<conio.h>
#include <conio.h> int main( )
int main( ) {
{ int a,b,c,choice;
char username; clrscr();
int password; printf("\nEnter the value of a,b:\n");
clrscr(); scanf("%d%d",&a,&b);
printf("Username:"); printf("\nMENU");
scanf("%c",&username); printf("\n1.ADD\n2.SUB\n3.MULTIPLY\n4.DIVISION
printf("Password:"); ");
scanf("%d",&password); printf("\nEnter the choice:");
if(username=='a') scanf("%d",&choice);
{ switch(choice)
{
if(password==12345) case 1:
{ c=a+b;
printf("Login successful"); printf("\nThe result of Addition is:%d",c);
} break;
else case 2:
{ c=a-b;
printf("Password is printf("\nThe result of Subtraction is:%d",c);
incorrect, Try again."); break;
} case 3:
} c=a*b;
else printf("\nThe result of Multiplication is:%d",c);

21
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

{ break;
printf("Username is incorrect, Try case 4:
again."); c=a/b;
} printf("\nThe result of Division is:%d",c);
getch(); break;
return 0; default:
} printf(“Wrong Choice”);
}
return 0;
}
OUTPUT
Enter the value of a,b :5 6
MENU
1.ADD
2.SUB
3.MULTIPLY
4.DIVISION
Enter the choice:1
The result of Addition is:11
UNCONDITIONAL STATEMENTS (JUMP STATEMENTS):
1.goto 2.Return
Syntax goto label; return; or //form 1
…………
………… return expression; //form 2
…………
label:
statement
…………
working 1.A goto statement can cause program control 1. Form 1: A return statement without an
anywhere in the program unconditionally expression can appear only in a function
2.The goto statement requires a label to whose return type is void
identify the place to move the execution. 2. Form 2: A return statement with an
3.Label end with colon(:) expression cannot appear in a function whose
return type is void
3. A return statement terminates the execution
of a function and returns the control to the
calling function
Example #include<stdio.h>
#include<conio.h> int max(int num1, int num2)
int main() {
{ int result;
int x;
clrscr(); if (num1 > num2)
printf(“Enter a number to find odd or result = num1;
even no : “); else
scanf(“%d”,&x); result = num2;

22
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

if(x%2==0)
goto even; return result;
else }
goto odd;
return 0;
}
even:
printf(“%d is an even no”,x);

odd:
printf(“%d is an odd no”,x);
OUTPUT
Enter a number to find odd or even no :5
5 is an odd no
3.break 4.continue
Syntax while(condition) while (condition)
{ {
---- ----
---- -----
if(condition) if(condition)
break; continue;
------ ---
----- }
}
working  When break statement is encountered  Continue statement terminates the current
inside any block or loop, control loop iteration and persist the loop with next
automatically passes to the first statement iteration
after the block or loop  In some situation we want to take the
control to the beginning of the loop, continue
is used.
Example #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int a,b; int a;
clrscr(); clrscr();
printf(“Enter two value to subtract : for(a=1;a<=10;a++)
\n”); {
scanf(“\n%d%d”,&a,&b); if((a==5)||(a==7))
if(a>b) continue;
{ else
printf(“Subtracted value is : printf(“%d\n”,a);
%d\n”,(a-b)); }
} return 0;
else }
{

23
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

break; OUTPUT
} 1
return 0; 2
} 3
OUTPUT 4
Enter two value to subtract : 6
5 8
3 9
Subtracted value is : 2 10

Difference between Break and Continue statement


S.No Break Continue
1 Exits from current Loop takes next iteration
2 Control passes to next statement Control passes to the beginning of loop
3 Terminates the program Never terminates the program
LOOPING:
 A loop is defined as a block of statement which are repeatedly executed for certain number of times while
certain condition remains true.
 There are two types of loops,
1. Counter controlled loops(or repetition) and
2. Sentinel controlled loops (or repetition).
Counter controlled repetitions are the loops which the number of repetitions needed for the loop is known
before the loop begins; these loops have control variables to count repetitions.
 Counter controlled repetitions need initialized control variable (loop counter), an increment (or decrement)
statement and a condition used to terminate the loop (continuation condition).
 Ex : For Loop
Sentinel controlled repetitions are the loops with an indefinite repetitions; this type of loops use “sentinel
value” to indicate “end of iteration”.
 Ex : while, do...while
Iteration is a process of repeating the same set of statement again and again until the specified condition
holds true.
There are 3 iteration statements
1. for statement
2. while statement
3. do-while statement
1.‘for’ Loop
 For loop in C is the most general looping construct.
 The loop header contains three parts:
1. an initialization section,
2. a continuation condition, and
3. step separated by semicolons.
SYNTAX:
for(initialization; TestExpr; updating)
stmT;

24
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Flow control in C –for loop:

Fig 1.6
1.The first part is known as initialization. It is used to initialize the variable called “loop counter”.
2.The second part is known as the condition section which tests the value of the loop counter.
 This section determines whether the body of the loop is executed or not.
3.The third part is known as step or manipulation section.
 After successful execution of loop’s body, the counter variable is incremented or decremented, depending
on the operation (++ or ‒ ‒).
 If more than one variable is used for initialization they are separated by commas.
 The step can also applied to more than one variable separated by commas.
Example:
#include<stdio.h>
int main() Output:
{
int i; hello, World
for (i=1; i<=3; i++) hello, World
{ hello, World
printf("hello, World");
}
return 0;
}
2.‘While’ Loop
 A while loop repeatedly executes a target statement as long as a given condition is true.
 The while loop evaluates the test expression before every loop, so it can execute zero times if the condition
is initially false.
 It is Entry controlled loop
Flow control in C –while loop:
 If the evaluation result is true value, the block of
statement within is executed

 If the evaluation result is false value the block of


statements within the body of loop is skipped and
terminate the loop
Fig 1.6.1  The increment or decrement of the loop control
Ex: variable is generally done within the body of the
#include<stdio.h> loop.
int main(void)

25
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

{
int j;
j = 1;
while(j <= 5)
{
printf("%d \t", j);
j = j + 1;
}
return 0;
}
OUTPUT:
1 2 3 4 5
3.‘do while’ statement
 In this case the loop condition is tested at the end of the body of the loop.
 A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one
time.
 It is Exit controlled loop
do
{
stmT; /* body of statements would be placed here*/
}while(TestExpr);
Example:
#include <stdio.h>
int main()  The block of statement is executed without any
{ condition check.
int j= 1;  After this expression is evaluated and if it is true
do the block of statement in the body of the loop is
{ executed again.
printf("Hello %d\t", j);  Thus the block of statement is repeatedly executed
j = j +1; till the expression is evaluated to false.
} while (j<= 5);
return 0;
}
OUTPUT:
1 2 3 4 5
Difference between while and do-while loop
S.No While loop Do-while loop
1 Condition is specified at the top Condition is specified at the bottom
2 Body of the statements gets executed Body of the statements gets executed once even
when condition is satisfied when condition is false.
4 It is entry controlled loop It is exit controlled loop
Example Using while loop: Same example using do-while loop
void main() void main()
{ {
int i=0 int i=0

26
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

while(i==1) do
{ {
printf("while versus do- printf("while versus do-while\n");
while"); }while(i==1);
} printf("Out of loop");
printf("Out of loop"); }
} Output:
Output: while versus do-while
Out of loop Out of loop

FUNCTION :
Definition:
 A function is a group of statements that performs a specific task and is relatively independent of the
remaining code
 A function is a self-contained block
 It is a subprogram of one or more statements
 It performs a specific task when the function is called.
Example: void main ( )
{
int a=10;
printf(“In main, number is %d”, a);
void display( );
}
void display( )
{
int b=5;
Printf(“ In display, number is %d”, b);
}
Classification of Functions
1. Library Functions or Pre-defined Function.
2. User-defined Function

Fig 1.7
S.No Library functions User-defined function
The user cannot understand the internal The user can understand the internal
1.
working of these functions. working of these functions.
The user can not change or modify The user can change or modify these
2.
these functions. functions
Defined by the user according to his/her
3. These are Predefined set of functions.
requirements.
User-defined functions can be useful to
4. Their tasks are limited.
other programmers.
5. Eg: clrscr( ), sqrt( ); Eg: main( ), display( );
Table 1.7

27
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Uses of functions:
 The function can be used any number of times to perform the task.
 Large programs can be reduced to smaller ones.
 Easy to debug and find out the errors in it.
 Increases readability.
USER DEFINED FUNCTIONS:
 User defined functions are the functions that are defined by the user at the time of writing the program.
Elements of user defined functions:
1. Function declaration
2. Function definition.
3. Function call.
Function declaration:
 All identifiers need to be declared before they are used. It is also known as function prototype.
Syntax:
return-type function-name( parameter –list);
Example:
int add(int x,int y);
float sub(float a,float b);
Function definition:
It is also known as function implementation, means composing a function.
Syntax
return-type function-name( parameter _list)
{
local variable declaration;
statement1;
statement2;
return(value);
}
Example:
int add(int x,int y)
{
int c;
c=x+y;
return c;
}
Function call:
 It passes control to a called function.
 To use a function, you will have to call that function to perform the defined task.
Syntax
function_name (argument1,argument2,….argumentn);
Example:
add(x,y);
Working of a function
• Once a function is called, the control passes to the called function.
• The working of calling function is temporarily stopped.

28
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

• When the execution of called function is completed, then the control returns back to the calling
function and execute the next statement.

Return type:
 It indicates data type which could return value from called function to the calling function.
 The return type of the function can be int, float,double, char, void etc.,
 The default return_type is int.
Actual Argument or Parameters
 The arguments of calling functions are actual arguments.
Formal Argument or Parameters
 The arguments of called functions are formal arguments.
Example program for function:
#include<stdio.h>
#include<conio.h>
int mul(int x, int y);-----------------------------------------------------> function declaration
void main()
{
int x, y, result;
printf(“Input Two Numbers to Multiplied: “);
scanf(“%d”,&x);
scanf(“%d”,&y);
result = mul(x, y);------------------------------------------------------> calling function

actual arguments
printf(“The product of our two numbers %d\n”,result);
getch();
}
int mul(int a, int b) ------------------------------------------------------> called function

formal arguments
{
int c;
c=a*b
return (c);
}
Output:
Input Two Numbers to Multiplied: 10 20
The product of our two numbers 200

29
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

TYPES OF FUNCTIONS:
Depending upon the argument present & return value, the functions are divided into four types.
They are:-
1. Function without passing arguments and without return values.
2. Function with passing arguments but without return Values.
3. Function with passing arguments and return Values.
4. Function without passing arguments but with return Values.

1. Function without Passing Argument and 2. Function with Passing Arguments but Without
Without Return Values Return Values
void main( ) void main( )
{ {
…… ……
abc(); abc(x);
…… ……
} }
abc() abc(y)
{ {
……. ……
} }
 No arguments are passed from the calling  In this type, arguments are passed through the
function to the called function and no arguments are calling function.
sent back to the calling function from the called  The called function operates on the values.
function.  But no result is sent back.
 The function is only executed and nothing is Example:
obtained. #include<stdio.h>
Example: void main( )
#include<stdio.h> {
void main() void add(int, int);
{ int x,y;
void message(); clrscr();
message(); printf(“Enter the numbers to add\n”);
} scanf(“%d%d”, &x, &y);
void message() add(x,y);
{ getch( );
puts(“Have a NICE DAY”); }
} void add(int a, int b)
{
int c;
c=a+b;
Output: printf(“Sum = %d”, c);
}
Have a NICE DAY Output:
Enter the numbers to add
10 5
Sum = 15

30
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

3. Function with Passing Arguments and with 4. Function without Passing Arguments but with
Return Values Return Values
void main( ) void main( )
{ {
int z; int z;
z=abc(x); z=abc();
……. ……..
} }
abc(y) int abc(void)
{ {
y++; int y=5;
return(y); ………
} return(y);
 In this type, the copy of actual argument is }
passed to the formal argument.  In this type , No arguments are passed from calling
 Called function return the value to the calling function to the called function
function after execution.  But the called function returns the value after
 Here the data is transferred between the calling execution.
function and called function.  The called function is independent.
Example  Here both the calling and called functions are partly
#include<stdio.h> communicated with each other.
#include<conio.h> Example
int mul(int x,int y); #include<stdio.h>
void main() #include<conio.h>
{ int getmark( );
int x,y,result; void main()
printf(“input two numbers to beMultiplied :” ); {
scanf(“%d%d”,&x,&y); int total;
result= mul(x,y) total=getmark( );
printf(“The product of your two numbers printf(“The total of Two Subjects are : %d”, total);
is %d\n”,result); getch( );
getch(); }
}
int getmark( )
int mul(int x,int y) {
{ int M1,M2,total;
return x*y; printf(“Enter Two Subject Marks : “);
} scanf(“%d%d”,&M1,&M2);
total=M1+M2;
return(total);
Output: }
Please input two numbers to be Multiplied : 10 Output
20 Enter Two Subject Marks : 99 99
The product of your two numbers is 200 The total of Two Subjects are : 198
Passing Argument to Function:
 Whenever we call a function then sequence of executable statements gets executed.

31
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 We can pass some of the information to the function for processing called argument.
Two Ways of Passing Argument to Function:
1. Call by Value (or) Pass by value
2. Call by Reference (or)Pass by reference
1. CALL BY VALUE
 While Passing Parameters using call by value, photo copy of original parameter is created and passed to
the called function.
 Any update made inside the called function will not affect the original value of variable in calling
function.
Example (swapping of two numbers using call by value)
#include<stdio.h>
void main()
{
void swap(int,int);
int a=50,b=70;
swap(a,b);
printf(“\n In calling function”);
printf("\n a= : %d",a);
printf("\n b= : %d",b);
}
void swap(int x,int y)
{
int temp;
temp = x;
x=y;
y = temp;
printf(“\n In called function\n”);
printf("\n x= : %d",x);
printf("\n y= : %d“,y);
}
Output :
In called function
X= : 70
Y= : 50
In calling function
a= : 50
b= : 70
Explanation : Call by Value
 In the above example num1 and num2 are the original values in calling function and photo copy of these
values is passed to the called function and these values are copied into number1, number2 .
 The changes made in number1 and number2 will not affect the original value num1 and num2.
 As their scope is limited only within the called function, so they cannot alter the values inside main
function. Changes are temporary.
2. CALL BY REFERENCE or( Call by Pointer/Address)
 While passing parameter using call by address scheme, we are passing the actual address of the variable
to the called function.

32
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 Any updates made inside the called function will modify the original copy since we are
directly modifying the content of the exact memory location.
 Formal parameters are pointers to the actual parameters.
 Changes are permanent.
Example
#include<stdio.h>
void main()
{
void swap(int*,int*);
int a=50,b=70;
swap(&a,&b);
printf(“\n In calling function”);
printf("\n a= : %d",a);
printf("\n b= : %d",b);
}
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x=*y;
*y = temp;
printf(“\n In called function\n”);
printf("\n x= : %d",*x);
printf("\n y= : %d“,*y);
}
Output :
In called function
X= : 70
Y= : 50
In calling function
a= : 70
b= : 50
Explanation : Call by Address
 In the above example, we are passing actual address of num1 and num 2 to the called function .
 The changes made in number1 and number2 will affect the original value of num1 and num2.
Comparison:
Point Call by Value Call by Reference
Duplicate Copy of Original Parameter is
Copy Actual Copy of Original Parameter is Passed
Passed
No effect on Original Parameter after Original Parameter gets affected if value of
Modification
modifying parameter in function parameter changed inside function

RECURSIVE FUNCTIONS:
 A function that calls itself is known as recursive function
 It is a process of calling the same function itself again and again until some condition is satisfied.

33
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Example:
func1()
{
………..
func1();
}
TYPES OF RECURSION:
Direct recursion Indirect recursion
Function calls itself till the condition is true. A function calls another function, then, the called
function calls the calling function.
Example Example
F1() F1()
{ {
F1();//function calls itself F2();//function F1calls F2
} }
F2()
{
F1();//function F2calls F1
}

Example 1 of recursion (Factorial )


#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int a;
printf("\nEnter the number:");
scanf("%d",&a);
printf("The factorial of a given number is %d",fact(a));
}
int fact(int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(x-1);
return(f);
}
Output:
Enter the number:5
The factorial of a given number is 120
Explanation:
 In, this simple C program, fact() function is invoked from the same function.
 If x is equal to 1 then, the function directly returns value 1.

34
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 If x is not equal to 1 then, the function calls itself by passing argument 1 less than the previous argument
 Suppose, a is 5 initially, Then, during next function calls, 4 is passed to function and the value of
argument decreases by 1 in each recursive call.
 For better visualization of recursion in this example:

fact (5)

=5*fact(4)

=5*4*fact(3)

=5*4*3*fact(2)

=5*4*3*2*fact(1)

=5*4*3*2*1

=120
Example 2:
Write a C program to print the Fibonacci series using recursion.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,n;
printf("\n Enter the Fibonacci Series Limit\n");
scanf("%d",&n);
fib(n);
getch();
}
int fib(int n)
{
int a,b,c,i;
a=0;
b=1;
printf("\n FIBONACCI SERIES\n");
printf("\n%d\n%d",a,b);
for(i=0;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("\n%d",c);
}

return 0;
}
Output
Enter Fibonacci Series Limit: 5
FIBONACCI SERIES: 0 1 1 2 3
35
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Example 3
Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are
known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
Output
Enter a positive integer:
5
15
Explanation:
In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the
function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5
initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1
in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers
from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal
to 0, there is no recursive call and recursion ends.

36
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

ADVANTAGES OF RECURSION:

 Recursion requires few variables which make program clean.


 Recursion can be used to replace complex nesting code by dividing the problem into same problem
of its sub-type.
DISADVANTAGES OF RECURSION:
 In other hand, it is hard to think the logic of a recursive function.
 It is also difficult to debug the code containing recursion.

LIBRARY FUNCTIONS (OR) BUILT_IN FUNCTIONS (OR) PREDEFINED FUNCTIONS:


• It is pre-defined function.
• The library function provides functions like mathematical, string manipulation etc,.
Mathematical Library function
1.sqrt(x): It is used to find the square root of x
Ex: sqrt(36) is 6
2.abs(x): It is used to find the absolute value of x
Ex: abs(-36) is 36
3.pow(x,y): It is used to find the value of xy
Ex: pow(5,2) is 25
4.ceil(x): It is used to find the smallest integer greater than or equal to x
Ex: ceil(7.7) is 8
5.rand(): It is used to generate a random number.
6.sin(x): It is used to find the sine value of x
Ex: sin(30) is 0.5
7.cos(x): It is used to find the cosine value of x
Ex: cos(30) is 0.86
8.tan(x): It is used to find the tan value of x
Ex: tan(30) is 0.577
String operatios:
1.strlen()
It is used to find the length of the string.
syntax: strlen(string)
2.strcpy()
It is used to copy one string to another.
syntax: strcpy(string1,string2)
3.strcat()
It is used to combine two strings.
syntax:strcat(string1,string2)
4.strcmp()
It is used to compare two strings.
syntax: strcmp(string1,string2)
5.strrev()
It used to reverse a string.
syntax: strrev(string)
ARRAY:
Introduction:
 An Array is a data structure used to store data elements in successive memory location

37
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 It store similar data type elements are stored contiguous in memory in one variable name.
 These similar elements could be all integers or all floats or all characters etc.
 Usually, the array of characters is called a “string”,
 Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.
Ex :
int a[5], char ch[10],float sal[10],long num[5];
ARRAY INITIALIZATION :
 Array elements are called by array names followed by the element numbers.
 Arrays starts at position 0. The elements of the array occupy adjacent locations in memory.
syntax :
type variable_name[length of array];
Ex :int a[5]={10,30,40,50,60};
Here 5 elements are stored in an array a elements are integer. The elements are stored in sequential
a[0]=10,a[1]=30,a[2]=40,a[3]=50,a[4]=60.
ARRAY DECLARATION:
 Array needs to be declared and defined at the beginning.
 The data type of array elements and how large the array size are declared.
Syntax :
type var_name[size];
Where
Type decalare as data type
Var_name refer as array name
Size declare as maximum allocated memory
Ex : float marks[50];
Maximum 50 students marks stored in array in marks array name with float value.
CHARACTERISTICS OF ARRAY:
 An array is a collection of elements of the same data type. The data type of an element is called element
type.
 All the elements of an array share a common name i.e., the array name.
 Array elements are stored in subsequent memory locations
 Accessing and modify the elements easy without disturbing other elements.
 An array a[] can be assigned to elements unlimited.
 The array index in C starts with 0, i.e., index of the first element of an array is 0.
 The position of an element in an array is specified with an integer value known as index or subscript.
CLASSIFICATION:
1. One – Dimensional Array.
2. Two - Dimensional Array.
3. Three or Multi-Dimensional Array.
1)ONE DIMENSIONAL ARRAY :
An array with a single subscript is known as one dimensional array.
Example : int a[5];
• The integer elements required 2 bytes, assume starting address is 2000.
Elements are stored contiguous memory.
Elements : a[0] a[1] a[2] a[3] a[4]
Address : 2000 2002 2004 2006 2008
Data : 10 20 30 40 50

38
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

 In a One Dimensional array we have a single index i.e. the array consists of only a single subscript.
a[0],a[1],a[2],a[3],...........a[n-1]
 In C Programming language, an array is initialised from zero th element to (n-1)th element.
 But total number of elements will be 'n'. int num[]={2,8,7,6,0}
 An array can be declared in the following ways:-
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5],i;
clrscr();
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(i=0;i<5;i++)
{
printf("\nThe value in a[%d] is %d",i,a[i]);
} return 0;}
OUTPUT:
The value in a[0] is 10
The value in a[1] is 20
The value in a[2] is 30
The value in a[3] is 40
The value in a[4] is 50
TWO-DIMENSIONAL ARRAY:
(1) A two-dimensional array has its elements arranged in a rectangular grid of rows and columns.
(2) The elements of a two-dimensional array can be accessed by using a row subscript (i.e, row number) and a
column subscript (i.e., column number).
(3)Both the row subscript and the column subscript are required to select an element of a two-dimensional
array.
(4)A two-dimensional array is popularly known as a matrix
Ex : a[3][3] = 3 rows and 3 columns totally 9 elements
a[0[0] 2000 a[0][1] 2002 a[0][2] 2004
a[1][0] 2006 a[1][1] 2008 a[1][2] 2010
a[2][0] 2012 a[2][1] 2014 a[2][2] 2012

DECLARATION OF TWO DIMENSIONAL ARRAY:


The general form of a two-dimensional array declaration is
39
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

Type array_name [row_size] [column_size];


Example
int a[3][3]; a[3][3] = 3 rows and 3 columns totally 9 elements

a[0[0] 2000 a[0][1] 2002 a[0][2] 2004


a[1][0] 2006 a[1][1] 2008 a[1][2] 2010
a[2][0] 2012 a[2][1] 2014 a[2][2] 2012
USAGE OF TWO-DIMENSIONAL ARRAY:
 The elements of a two-dimensional array can be accessed by using row and column subscripts. The
following program to illustrate the usage of a two-dimensional array.
PROGRAM:
#include<stdio.h> OUTPUT:
main()
Elements of array are
{
int a[2][3]={2,1,3,2,3,4}; 2 1 3
Printf(“elements of array are”);
2 3 4
Printf(“%d %d %d \n”, a[0][0],a[0][1],a[0][2]);
Printf(“%d %d %d\n”, a[1][0],a[1][1],a[1][2]);
}
READING, STORING AND ACCESSING ELEMENTS OF A 2-D ARRAY
The elements can be read and stored in a 2-D array by using use of nested loops. The following
Program that illustrates the method to read, store and access the elements of a two-dimensional array.
Example: Matrix addition
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Input A - Matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("Input B - Matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("Sum of A and B Matrix=\n");
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
printf("%5d",c[i][j]);
printf("\n");
}

40
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

getch();
}
Output:
Input A- Matrix: 2 2 2 2 2 2 2 2 2
Input B –Matrix: 3 3 3 3 3 3 3 3 3
Sum of A and B Matrix= 5 5 5
5 5 5
5 5 5
Multi-Dimensional Array (Three –Dimensional)
C allows arrays of three or more dimensions.
The exact limit is determined by the compiler.
The general form of a multidimensional array is
type array_name [s1][s2][s3]…s[m];

Example : int survey [3][5][12];


float table [5][4][5][3];
ex :
int a[3][3][3] = { { {1,2,3}.{4,5,6},{7,8,9} },
{ {3,2,1},{6,5,4},{9,8,7} },
{ {9,0,0},{1,1,1},{2,2,2} } };

Example for getting input for 3 dimensional array


for(i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
for (k=0;k<3;k++)
{
scanf(“%d”,&a[i][j][k]);
}
}
}
ADVANTAGES OF ARRAYS:
 The direct indexing is the biggest advantage.
 Direct indexing means the time required to access any element in an array of any dimension is almost the
same irrespective of its location in the array.
DISADVANTAGES OF ARRAYS:
 The memory to an array is allocated at the compile time.
 Arrays are static in nature.
 The size of an array cannot be expanded or cannot be squeezed at the run time.
 The size of an array has to be kept big enough to accommodate the worst cases. Therefore, memory usage
in case of arrays is inefficient.
41
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

SOLVING SIMPLE SCIENTIFIC AND STATISTICAL PROBLEMS


1. To write a c program to check whether given Number is odd or even.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,rem;
printf("Enter a Number\n"); Output:
scanf("%d",&a); Enter a Number
rem=a%2; 13
if(rem==0) The Given Number is Odd
printf("The Given Number is Even");
else
printf("The Given Number is Odd");
getch();
}
2. C program to examine the biggest of given three numbers.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("Enter 3 Numbers\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("The First Number %d(a) is Biggest\n",a); Output:
} Enter 3 Numbers 5 9 2
} The Second Number 9(b) is Biggest
else if(b>c)
{
printf("The Second Number %d(b) is Biggest\n",b);
}
else
printf("The Third Number %d(c) is Biggest\n",c);
getch();
}
3. C program to find the sum of N‟ natural numbers for given range.(1+2+3+………+n)
Program:
#include<stdio.h>
#include<conio.h>
void main()

42
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

{
int i,n,sum=0;
printf("Enter the range\n");
scanf("%d",&n); Output:
i=1; Enter the range 16
while(i<=n) The sum of first 16 numbers is 136
{
sum=sum+i;
i++;
}
printf("\nThe sum of first %d numbers is %d\n",n,sum);
}
4. C program to find the factorial of a given number
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,fact=1;
printf("Enter the number to find factorial");
scanf("%d",&n); Output:
i=1; Enter the number to find factorial 5
while(i<=n) the factorial of a given number is 120
{
fact=fact*i;
i++;
}
printf("\nThe factorial of a given number is %d \n",fact);
}
5. Program to check whether the given number is Palindrome
Program:
#include<stdio.h>
void main()
{
int num,reverse=0,digit;
printf(“enter the number”); output:
scanf(“%d”,&num); enter the number:535
while(num!=0) Given Number is Palindrome
{
digit=num%10;
num=num/10;
reverse=reverse*10+digit;
}
if(num==reverse)
printf("Given Number is Palindrome\n");
else
printf("Given Number is Not Palindrome\n");

43
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

getch();
}
6. Program to check whether the given number is Armstrong
#include<stdio.h>
#include<math.h>
void main()
{
int a,i,sum=0,n;
printf("\nEnter a Number\n");
scanf("%d",&a);
n=a;
do
{
i=a%10;
sum=sum+(i*i*i);
a=a/10;
}while(a>0);
if(n==sum)
printf("Given Number is Armstrong\n");
else
printf("Given Number is Not Armstrong\n");
getch();
}
7. Program to check whether the given number is prime or not
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int a,i,sum=0,n,ch,m;
printf("\nEnter a Number\n");
scanf("%d",&a);
m=5;
n=sqrt(a);
for(i=2;i<=n;i++)
{
if(a%i==0)
{
m=0;
break;
}
}
if(m==0)
printf("Given Number is Prime\n");
else
printf("Given Number is Not Prime\n");
break;

44
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

}
}
8. SUM OF DIGITS
#include<stdio.h>
void main()
{ output:
int num,sum=0,digit; enter the number:786
printf(“enter the number”); sum of digits:21
scanf(“%d”,&num);
while(num!=0)
{
digit=num%10;
sum=sum+digit;
num=num/10;
}
printf(“sum of digits is %d”,sum);
}
9. REVERSE A NUMBER
#include<stdio.h>
void main()
{
int num,reverse=0.digit;
printf(“enter the number”); output:
scanf(“%d”,&num); enter the number:534
while(num!=0) reverse is:435
{
digit=num%10;
num=num/10;
reverse=reverse*10+digit;
}
printf(“reverse is %d”,reverse);
}
10. Fibonacci series
#include<stdio.h>
#include<conio.h>
void main()
{
int a=0,b=1,n,c,count=2;
printf(“how many terms do you want to print”);
scanf(“%d”,&n);
printf(“%d\t%d\t”,a,b);
while(count<n)
{
c=a+b;
printf(“\t %d”,c);
a=b;
b=c;

45
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

count++;
}
getch();
}
11. C program to evaluate the sine series.
Program:
#include<stdio.h>
#include<conio.h
void main()
{
int i,n,j,dr;
float res=0.0,x,nr;
printf("\nEnter the Value of x\n");
scanf("%f",&x);
printf("\nEnter the total no of terms\n");
scanf("%d",&n);
j=1;
for(i=1;i<n*2;i+=2)
{
nr=pow(x,i)*j;
dr=factorial(i);
res+=(nr/dr);
j=-j;
}
printf("The Result of sine series is : %f\n",res);
}
int factorial(int n)
{
int i,sum=1;
for(i=1;i<=n;i++)
sum=sum*i;
return sum;
}
Output:
Enter the Value of x
0.21
Enter the total no of terms
5
The Result of sine series is : 0.208460

12. Write a program to find the solutions of a quadratic equation. ax2 + bx + c = 0


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
float a, b, c, root1, root2;

46
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-I C PROGRAMMING FUNDAMENTALS

float realp, imagp, disc;


printf("Enter the values of a, b and c \n");
scanf("%f %f %f", &a, &b, &c);
if (a == 0 || b == 0 || c == 0)
{
printf("Error: Roots cannot be determined \n");
exit(1);
}
else
{
disc = b * b - 4.0 * a * c;
if (disc < 0)
{
printf("Imaginary Roots\n");
realp = -b / (2.0 * a) ;
imagp = sqrt(abs(disc)) / (2.0 * a);
printf("Root1 = %f +i %f\n", realp, imagp);
printf("Root2 = %f -i %f\n", realp, imagp);
}
else if (disc == 0)
{
printf("Roots are real and equal\n");
root1 = -b / (2.0 * a);
root2 = root1;
printf("Root1 = %f\n", root1);
printf("Root2 = %f\n", root2);
}
else if (disc > 0 )
{
printf("Roots are real and distinct \n");
root1 =(-b + sqrt(disc)) / (2.0 * a);
root2 =(-b - sqrt(disc)) / (2.0 * a);
printf("Root1 = %f \n", root1);
printf("Root2 = %f \n", root2);
}
}
}

47

You might also like