FC Unit I & II
FC Unit I & II
STUDY MATERIAL
CORE I
CLASS: I AI & DS
SEMESTER-I
1
FUNDAMENTALS OF COMPUTER PROGRAMMING
SYLLABUS
UNIT I: Introduction to C - Introduction to C 12 Hours Overview of C -
Introduction - Character set - C tokens - keyword & Identifiers - Constants -
Variables - Data types - Declaration of variables - Assigning values to
variables - Defining Symbolic Constants - Arithmetic, Relational, Logical,
Assignment, Conditional, Bitwise, Special, Increment and Decrement
operators - Arithmetic Expressions - Evaluation of expression - precedence
of arithmetic operators - Type conversion in expression – operator
precedence & as sociativity - Mathematical functions - Reading & Writing a
character - Formatted input and output.
2
FUNDAMENTALS OF COMPUTER PROGRAMMING
UNIT -I
Introduction
Constants and Variables
C is a programming language that allows the use of
constants and variables. Constants are values that cannot be
changed during program execution, while variables are values
that can be changed during program execution. Let's know
more about them.
Constants in C:
Constants are values that are fixed and cannot be
changed during program execution. In C, constants can be of
different types, including integer, floating-point, and character
constants. We use the “const” keyword to declare constants in
C.
There are two types of constants in C:
Numeric Constants: Numeric constants represent a
fixed value and can be either integers or floating-point
numbers.
3
FUNDAMENTALS OF COMPUTER PROGRAMMING
Initialization in C:
4
FUNDAMENTALS OF COMPUTER PROGRAMMING
Here, we initialized the arr variable with three values using a compound
literal.
Note: It is also possible to initialize variables with default
values. When a variable is declared without an initial value, it
is automatically initialized with a default value.
Comments and Header Files
C is a programming language that supports comments
and header files. Comments are used to add information to a
program, while header files are used to include external code
in a program. Let's know more about them.
Single-line comments:
Single-line comments start with two forward slashes (//) and extend to
the end of the line.
Let's see an example.
Multi-line comments:
Multi-line comments start with /* and end with */.
They can span multiple lines.
Let's see an example.
/*
This is a
multi-line
comment
*/
Header Files in C:
Header files in C are used to include external code in a
program. They contain function prototypes, variable
declarations, and other definitions that can be used in the
program.
To include a header file in a C program, we use the “#include”
directive.
5
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include <stdio.h>
int main() {
printf("Hello, world!");
return 0;
6
FUNDAMENTALS OF COMPUTER PROGRAMMING
// Function declaration
int add(int a, int b);
// Main function
int main() {
// Function call
int result = add(2, 3);
// Output
printf("The result is %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Output
The result is 5
7
FUNDAMENTALS OF COMPUTER PROGRAMMING
Low a to z a, b, c, d, e, f, g, h, i, j, k, l, m,
erca n, o, p, q, r, s, t, u, v, w, x, y, z
se
Alph
abet
s
Upp A to Z A, B, C, D, E, F, G, H, I, J, K, L,
erca M, N, O, P, Q, R, S, T, U, V, W,
se X, Y, Z
Alph
abet
s
Digits
The C programming language provides the support for
all the digits that help in constructing/ supporting the
numeric values or expressions in a program. These range
from 0 to 9, and also help in defining an identifier.
Type of Descr Characters
Charact iption
er
Digits 0 to 9 0, 1, 2, 3, 4, 5, 6,
7, 8, 9
Special Characters
We use some special characters in the C language for
some special purposes, such as logical operations,
8
FUNDAMENTALS OF COMPUTER PROGRAMMING
`~@!$#^*%&()[]{}<>+=_–
|/\;:‘“,.?
White Spaces
The white spaces in the C programming language
contain the following:
Blank Spaces
Carriage Return
Tab
New Line
1.3 C tokens:
Tokens are some of the most important elements used
in the C language for creating a program. One can define
tokens in C as the smallest individual elements in a program
that is meaningful to the functioning of a compiler.
Classification and Types of Tokens in C
Here are the categories in which we can divide the
token in C language:
Identifiers in C
Keywords in C
Operators in C
Strings in C
Special Characters in C
Constant in C
1. Identifiers in C
These are used to name the arrays, functions,
structures, variables, etc. The identifiers are user-defined
words in the C language. These can consist of lowercase
letters, uppercase letters, digits, or underscores, but the
9
FUNDAMENTALS OF COMPUTER PROGRAMMING
dou float
ble
stru unsign
ct ed
int short
brea continu
k e
10
FUNDAMENTALS OF COMPUTER PROGRAMMING
else for
swit void
ch
long signed
3. Operators in C
The operators in C are the special symbols that we use
for performing various functions. Operands are those data
items on which we apply the operators. We apply the
operators in between various operands. On the basis of the
total number of operands, here is how we classify the
operators:
Unary Operator
Binary Operator
Ternary Operator
1. Unary Operator
The unary operator in c is a type of operator that gets
applied to one single operand, for example: (–) decrement
operator, (++) increment operator, (type)*, sizeof, etc.
2. Binary Operator
Binary operators are the types of operators that we
apply between two of the operands. Here is a list of all the
binary operators that we have in the C language:
Relational Operators
Arithmetic Operators
Logical Operators
Shift Operators
Conditional Operators
Bitwise Operators
Misc Operator
Assignment Operator
3. Ternary Operator
11
FUNDAMENTALS OF COMPUTER PROGRAMMING
Special Characters in C
We also use some of the special characters in the C language
() Simple brackets – We use these during function calling as well as during
function declaration. For instance, the function printf() is pre-defined.
[ ] Square brackets – The closing and opening brackets represent the
multidimensional and single subscripts.
(,) Comma – We use the comma for separating more than one statement,
separating the function parameters used in a function call, and for separating
various variables when we print the value of multiple variables using only one
printf statement.
{ } Curly braces – We use it during the closing as well as opening of any
code. We also use the curly braces during the closing and opening of the loops.
(*) Asterisk – We use this symbol for representing the pointers and we also
use this symbol as a type of operator for multiplication.
(#) Hash/preprocessor – We use it for the preprocessor directive. This
processor basically denotes that the user is utilizing the header file.
(.) Period – We use the period symbol for accessing a member of a union or
a structure.
(~) Tilde – We use this special character in the form of a destructor for free
memory.
5. Constant in C
Constant is basically a value of a variable that does not
change throughout a program. The constants remain the
same, and we cannot change their value whatsoever. Here are
two of the ways in which we can declare a constant:
By using a #define pre-processor
By using a const keyword
Here is a list of the types of constants that we use in the C
language:
12
FUNDAMENTALS OF COMPUTER PROGRAMMING
bre else
ak
cas enu
e m
13
FUNDAMENTALS OF COMPUTER PROGRAMMING
ch exte
ar rn
co float
nst
co for
nti
nu
e
def goto
aul
t
do if
Identifiers in C:
Identifiers are names given to variables, functions, and
other program elements.
We use letters, digits, and underscore (_) to compose
identifiers.
Example:
int age;
float average_grade;
void print_student_info();
Character set
A character set is a set of alphabets, letters and some
special characters that are valid in C language.
Alphabets
14
FUNDAMENTALS OF COMPUTER PROGRAMMING
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
C accepts both lowercase and uppercase alphabets as
variables and functions.
Digits
0123456789
Special Characters
Special Characters in C Programming
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
White space Characters
Blank space, newline, horizontal tab, carriage return
and form feed.
C Keywords
Keywords are predefined, reserved words used in
programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as
an identifier. For example:
int money;
Here, int is a keyword that indicates money is
a variable of type int (integer).
As C is a case sensitive language, all keywords must be
written in lowercase. Here is a list of all keywords allowed in
ANSI C.
C Keywords
a
doubl str
ut int
e uct
o
br
swi
ea else long
tch
k
15
FUNDAMENTALS OF COMPUTER PROGRAMMING
ef
c
retu un
h extern
rn ion
ar
co
nt
sign voi
in for
ed d
u
e
d stati wh
if
o c ile
d
ef vol
sizeo
a goto atil
f
ul e
t
un
co
shor sig
n float
t ne
st
d
All these keywords, their syntax, and application will be
discussed in their respective topics. However, if you want a
brief overview of these keywords without going further,
visit List of all keywords in C programming.
C Identifiers
Identifier refers to name given to entities such as
variables, functions, structures etc.
Identifiers must be unique. They are created to give a
unique name to an entity to identify it during the execution of
the program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from
keywords. You cannot use int as an identifier because int is a
keyword.
1.5 CONSTANTS
A constant is a name given to the variable whose values
can’t be altered or changed. A constant is very similar to
variables in the C programming language, but it can hold only
a single variable during the execution of a program.
Types of Constants in C
16
FUNDAMENTALS OF COMPUTER PROGRAMMING
Type of Example of
Constants Data type
Integer
constants
int 2000u,
23, 738, - 5000U, etc.
1278, etc.
325,647
1,245,473,
940
Floating-
17
FUNDAMENTALS OF COMPUTER PROGRAMMING
point or 20.987654
Real
constants
doule
500.987654
321
Octal Example:
constant 013
/*starts
with 0 */
Hexadecimal Example:
constant 0x90
/*starts
with 0x*/
character Example:
constants ‘X’, ‘Y’, ‘Z’
string Example:
constants “PQRS”,
“ABCD”
Types of Constants in C
Integer Constants
It can be an octal integer or a decimal integer or even a
hexadecimal integer. We specify a decimal integer value as a
direct integer value, while we prefix the octal integer values
with ‘o’. We also prefix the hexadecimal integer values with
‘0x’.
The integer constant used in a program can also be of
an unsigned type or a long type. We suffix the unsigned
constant value with ‘u’ and we suffix the long integer constant
value with ‘l’. Also, we suffix the unsigned long integer
constant value using ‘ul’.
Examples,
55 —> Decimal Integer Constant
0x5B —> Hexa Decimal Integer Constant
O23 —> Octal Integer Constant
68ul —> Unsigned Long Integer Constant
50l —> Long Integer Constant
30u —> Unsigned Integer Constant
Floating Point Constants / Real Constants
This type of constant must contain both the parts-
decimal as well as integers. Sometimes, the floating-point
18
FUNDAMENTALS OF COMPUTER PROGRAMMING
19
FUNDAMENTALS OF COMPUTER PROGRAMMING
Real Constants
This type of constant must consist of one digit at least.
There must not be any decimal point.
This type of constant can be both negative or positive.
It does not allow any blanks or commas within.
We assume an integer constant to be positive if there is no sign in front of
that constant.
String and Character Constants
This type of constant can be a single digit, a single alphabet, or even a
single special symbol that stays enclosed within single quotes.
The string constants get enclosed within double quotes.
The maximum length of this type of constant is a single character.
Backslash Character Constants
These are some types of characters that have a special type of meaning in
the C language.
These types of constants must be preceded by a backslash symbol so that
the program can use the special function in them.
Here is a list of all the special characters used in the C language and their
purpose:
Meaning of Character Backs
lash
Chara
cter
Backspace \b
New line \n
Form feed \f
Horizontal tab \t
Carriage return \r
Single quote \’
Double quote \”
Vertical tab \v
Backslash \\
Question mark \?
Alert or bell \a
20
FUNDAMENTALS OF COMPUTER PROGRAMMING
1.6 VARIABLES
Variables are containers for storing data values, like numbers
and characters.
In C, there are different types of variables (defined with
different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -
123
float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
21
FUNDAMENTALS OF COMPUTER PROGRAMMING
Da Size Description
ta
Ty
pe
For Data
ma Type
t
Sp
eci
fier
%d int
or
%i
%f float
%lf double
%c char
%s Used
for string
s (text),
which
you will
learn
more 22
about in
a later
chapter
FUNDAMENTALS OF COMPUTER PROGRAMMING
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
OUTPUT:
5
5.990000
D
23
FUNDAMENTALS OF COMPUTER PROGRAMMING
* multiplication
/ division
24
FUNDAMENTALS OF COMPUTER PROGRAMMING
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
2. RELATIONAL
A relational operator checks the relationship between
two operands. If the relation is true, it returns 1; if the
relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Meaning of
Operator Example
Operator
5 == 3 is
== Equal to
evaluated to 0
5 > 3 is
> Greater than
evaluated to 1
5 < 3 is
< Less than
evaluated to 0
5 != 3 is
!= Not equal to
evaluated to 1
25
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
3.LOGICAL
An expression containing logical operator returns either
0 or 1 depending upon whether expression results true or
false. Logical operators are commonly used in decision
making in C programming.
Operator Meaning Example
Logical
If c = 5 and d = 2
AND. True
then, expression
&& only if all
((c==5) && (d>5))
operands
equals to 0.
are true
26
FUNDAMENTALS OF COMPUTER PROGRAMMING
True only if
then, expression
either one
((c==5) || (d>5))
operand is
equals to 1.
true
Llogical
NOT. True If c = 5 then,
! only if the expression !(c==5)
operand is equals to 0.
0
Example : Logical Operators
// Working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
27
FUNDAMENTALS OF COMPUTER PROGRAMMING
4.ASSIGNMENT
The assignment operators are used to assign right-hand
side value (Rvalue) to the left-hand side variable (Lvalue). The
assignment operator is used in different variants along with
arithmetic operators.
5.CONDITIONAL
The conditional operator is also called a ternary
operator because it requires three operands. This operator is
used for decision making. In this operator, first we verify a
condition, then we perform one operation out of the two
operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE
the second option is performed. The conditional operator is
used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Example
A = (10<15)?100:200; ⇒ A value is 100
28
FUNDAMENTALS OF COMPUTER PROGRAMMING
<< the Bitwise left shift operator shifts all the A <<
bits to the left by the specified number ⇒ of 100 (1100100)
positions
29
FUNDAMENTALS OF COMPUTER PROGRAMMING
Operat
or Meaning Example
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is
increased by one before the expression evaluation. In the case
of pre-decrement, the value of the variable is decreased by one
before the expression evaluation. That means, when we use
pre-increment or pre-decrement, first the value of the variable
is incremented or decremented by one, then the modified
value is used in the expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
1.10 EXPRESSION
EVALUATION OF EXPRESSION
30
FUNDAMENTALS OF COMPUTER PROGRAMMING
Priority
This represents the evaluation of expression starts from
"what" operator.
Associativity
It represents which operator should be evaluated first if
an expression is containing more than one operator with
same priority.
Operat Prio
Associativity
or rity
*, /, % 3 Left to right
+, - 4 Left to right
|| 7 Left to right
?: 8 Right to left
=, +=, -
=, *=, 9 Right to left
/=, %=
Example 1:
31
FUNDAMENTALS OF COMPUTER PROGRAMMING
Example 2:
32
FUNDAMENTALS OF COMPUTER PROGRAMMING
Hight priority
*/%
Low priority
+-
For example, the statement x = 8 – 15 / 5 + 2 * 5 – 7 is evaluated as
follows,
First pass
x = 8 - 5 + 2 * 5 -7
x = 8 - 5 + 10 - 7
Second pass
x = 3 + 10 - 7
x = 13 - 7
x=6
33
FUNDAMENTALS OF COMPUTER PROGRAMMING
int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;
printf("%f", sum);
return 0;
}
Explicit Conversion
Explicit conversion is done manually by placing the
type in parentheses () in front of the value.
Considering our problem from the example above, we can now
get the right result:
#include <stdio.h>
int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;
printf("%f", sum);
return 0;
}
Output:
2.500000
34
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include <stdio.h>
int main()
{
// printing the value of same expression
printf("10 + 20 * 30 = %d", 10 + 20 * 30);
return 0;
}
Output
10 + 20 * 30 = 610
As we can see, the expression is evaluated as,10 + (20
* 30) but not as (10 + 20) * 30 due to * operator having
higher precedence.
// C Program to illustrate operator Associativity
#include <stdio.h>
int main()
{
// Verifying the result of the same expression
printf("100 / 5 % 2 = %d", 100 / 5 % 2);
return 0;
}
Output
100 / 5 % 2 = 0
35
FUNDAMENTALS OF COMPUTER PROGRAMMING
int main()
{
int n,x;
printf("Enter an integer number ");
scanf("%d",&n);
x=abs(n);
printf("Absolute value of %d is %d",n,x);
return 0;
}
Output
Enter an integer number -18
Absolute value of -18 is 18
2.sqrt() Function
The sqrt() function returns the square root of a positive
number. Remember that square root of a negative can not be
calculated.
36
FUNDAMENTALS OF COMPUTER PROGRAMMING
int main()
{
int n,x;
printf("Enter an integer number ");
scanf("%d",&n);
x=sqrt(n);
printf("Square root of %d is %d",n,x);
return 0;
}
Output
Enter an integer number 25
Square root of 25 is 5
3.ceil() Function
The ceil() function returns the nearest integer number
greater than the number passed as argument.
Syntax of ceil() function
double ceil(double num);
A ceil() function takes input in double data type and
return the result in double data type.
Example
C program to input a floating point number and print its ceil value.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
float n,x;
printf("Enter a floating point (decimal) number ");
scanf("%f",&n);
x=ceil(n);
printf("Ceil value of %f is %f",n,x);
return 0;
}
Output
37
FUNDAMENTALS OF COMPUTER PROGRAMMING
gets
This is a predefined function in C language which is available
in stdio.h header file. This function is used to read a single
string from keyboard.
Example
gets(string);
putchar
putchar function is a same as getchar but is function is used
for display a character value of screen or console. This
function must be take one parameters.
Example
char ch='A';
putchar (ch);
putchar is equivalent to printf("%c",ch);
puts
puts is same as gets function but this is used to display a
string on screen or console. This function takes single
arguments.
Example
puts(str);
38
FUNDAMENTALS OF COMPUTER PROGRAMMING
Example:
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
39
FUNDAMENTALS OF COMPUTER PROGRAMMING
int main()
{
// Declaring an int type variable
int a;
return 0;
}
Output
20
2. scanf():
scanf() function is used in the C program for reading or
taking any value from the keyboard by the user, these values
can be of any data type like integer, float, character, string,
and many more. This function is declared in stdio.h(header
file), that’s why it is also a pre-defined function.
In scanf() function we use &(address-of operator) which is
used to store the variable value on the memory location of
that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
Example:
// C program to implement
// scanf() function
#include <stdio.h>
// Driver code
int main()
{
int num1;
// Printing a message on
// the output screen
printf("Enter a integer number: ");
40
FUNDAMENTALS OF COMPUTER PROGRAMMING
return 0;
}
Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56
3. sprintf():
sprintf stands for “string print”. This function is
similar to printf() function but this function prints the string
into a character array instead of printing it on the console
screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);
Example:
// C program to implement
// the sprintf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8;
4. sscanf():
sscanf stands for “string scanf”. This function is
similar to scanf() function but this function reads data from
the string or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);
Example:
// C program to implement
// sscanf() function
#include <stdio.h>
41
FUNDAMENTALS OF COMPUTER PROGRAMMING
// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;
1. getch():
getch() function reads a single character from the
keyboard by the user but doesn’t display that character on
the console screen and immediately returned without pressing
42
FUNDAMENTALS OF COMPUTER PROGRAMMING
// Driver code
int main()
{
printf("Enter any character: ");
return 0;
}
Output:
Enter any character:
2. getche():
getche() function reads a single character from the
keyboard by the user and displays it on the console screen
and immediately returns without pressing the enter key. This
function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
Example:
// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
printf("Enter any character: ");
43
FUNDAMENTALS OF COMPUTER PROGRAMMING
return 0;
}
Output:
Enter any character: g
3. getchar():
The getchar() function is used to read only a first single
character from the keyboard whether multiple characters is
typed by the user and this function reads one character at
one time until and unless the enter key is pressed. This
function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();
Example:
// C program to implement
// the getchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type variable
char ch;
4. putchar():
The putchar() function is used to display a single
character at a time by passing that character directly to it or
by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
// C program to implement
// the putchar() function
#include <conio.h>
44
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
// Driver code
int main()
{
// Declaring a char type array
// of length 50 characters
char name[50];
45
FUNDAMENTALS OF COMPUTER PROGRAMMING
6. puts():
In C programming puts() function is used to display a
group of characters or strings which is already stored in a
character array.
This function is declared in stdio.h(header file).
Syntax:
puts(identifier_name );
Example:
// C program to implement
// the puts() function
#include <stdio.h>
// Driver code
int main()
{
char name[50];
printf("Enter your text: ");
// Displays string
puts(name);
return 0;
}
Output:
Enter your text: GeeksforGeeks
Your text is: GeeksforGeeks
7. putch():
putch() function is used to display a single character
which is given by the user and that character prints at the
current cursor location. This function is declared in
conio.h(header file)
Syntax:
putch(variable_name);
Example:
#include <conio.h>
46
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character:\n ");
ch = getch();
---------------------------------------UNIT I
COMPLETED--------------------------------
UNIT II
Introduction If Statement
‘If’ is the most powerful decision making statement in C
language. Thus it is used to control the execution of
statements. ‘If’ is used along with an expression. It is a two
way branching or decision making statement.
47
FUNDAMENTALS OF COMPUTER PROGRAMMING
Syntax :
if(test expression)
{
Body of if;
}
48
FUNDAMENTALS OF COMPUTER PROGRAMMING
Example:
if(age>55){
printf(“ Retired”);
}
Depending upon the complexity and conditions to be tested if can be
further subdivided.
Simple if
if…..else
nested if…else
if…else…if ladder
simple if statement
The general syntax of a simple if statement is
if(test expression)
{
Body of if;
}
Statement X;
49
FUNDAMENTALS OF COMPUTER PROGRAMMING
else
girl=girl+1;
50
FUNDAMENTALS OF COMPUTER PROGRAMMING
Statement x;
Example :
if( a>b)
{
if(a>c)
printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
{
if(b>c)
{
Printf(“b is greater”);
}
else
{
Printf(“c is greater”);
}
}
Here it explains the greatest among three numbers.
51
FUNDAMENTALS OF COMPUTER PROGRAMMING
else
statement 4;
statement x;
52
FUNDAMENTALS OF COMPUTER PROGRAMMING
Syntax :
switch(expression)
{
case constant1 :
block1;
break;
case constant2 :
block2;
break;
case constant n:
block n;
53
FUNDAMENTALS OF COMPUTER PROGRAMMING
break;
.
.
.
default:
default block;
break;
}
statement x;
When the ‘switch’ is executed the value of the
expression is successfully compared against the case’s
constants. When a case constant is found the block of codes
associated with it is executed, and if till the last case
constant no match is found the block associated with the
default case is executed. The default is an optional case .
If it is not present and no matches are found then control
passes to the statement x.
Example :
int num;
printf(“enter a number”);
scanf(‘%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);
break;
default:
printf(“wrong choice”);
break;
}
54
FUNDAMENTALS OF COMPUTER PROGRAMMING
55
FUNDAMENTALS OF COMPUTER PROGRAMMING
56
FUNDAMENTALS OF COMPUTER PROGRAMMING
57
FUNDAMENTALS OF COMPUTER PROGRAMMING
loop structures:
while loop.
do loop.
for loop.
Control Variables:
These are the variables which control the number of times a
loop will be executed.
58
FUNDAMENTALS OF COMPUTER PROGRAMMING
be executed. Then the body of the loop will be executed till the
test condition becomes false.
Segment of a program is given below:
i = 0;
while (i<=10)
{
printf ("%d\n", i);
i++;
}
do
{
body of the loop;
}
while (test condition);
Example:
i=0;
do
{
printf ("%d\n", i);
i++;
} while (i< 10);
i=11;
do
{
printf ("%d\n",i);
i++;
} while (i< 10);
59
FUNDAMENTALS OF COMPUTER PROGRAMMING
Syntax:
Example:
for (i=6; i>7; i++)
{
printf ("%d\n", i);
}
break:
Using this statement an early exit from a loop can be achieved. That is
when the break statement is encountered within a loop then the loop is
exited immediately and the statements following the loop will be executed.
When a break is encountered within a nested loop, the loop in which this
statement is present only that loop will be exited. That means the break
will exit only one loop.
Syntax:
break;
60
FUNDAMENTALS OF COMPUTER PROGRAMMING
(a) i=0;
while (i<10>
{
:
:
if (condition)
break;
:
:
}
n=7;
(b) i=0;
do
{
:
:
if (condition)
break;
:
:
} while (i<10);
n=7;
(c) while (i<15)
{
:
for (j=0; j<10; j++)
{
:
if (condition)
break;
:
}
n=7; (d) for (i=0; i<10; i++)
{
:
if(condition)
break;
}
n=7;
In all the above cases the break statement will make the control exit
the loop in which it is residing. Thus it executes the statement n=7
in all the cases.
2.13 Arrays
Following are some usecases where using an array will
make things simpler: to store list of Employee or Student
names, to store marks of students, or to store list of numbers
or characters etc.
61
FUNDAMENTALS OF COMPUTER PROGRAMMING
Advantages of Arrays
In one go, we can initialise storage for more than one
value. Because you can create an array of 10, 100 or 1000
values.
They make accessing elements easier by providing
random access. By random access we mean you can directly
access any element in an array if you know its index.
Sorting and searching operations are easy on arrays.
Disadvantages of Arrays
Due to its fixed size, we cannot increase the size of an
array during runtime. That means once you have created an
array, then it's size cannot be changed.
Insertion and deletion of elements can be costly, in
terms of time taken.
Declaring Arrays in C
Like any other variable, arrays must be
declared(created) before they are used. General form of array
declaration is,
Data-type variable-name[size];
Char a[5];
Float ar[9];
Int arr[10];
62
FUNDAMENTALS OF COMPUTER PROGRAMMING
And in the last line of code, int is the data types, and arr is
the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type.
The index of an array starts from 0 to size-1 i.e first
element of any array will be stored at arr[0] address and the
last element will be at arr[size - 1].
Initialization of Array in C
After an array is declared it must be initialized.
Otherwise, it will contain garbage value(any random value).
An array can be initialized at either compile time or
at runtime. That means, either we can provide values to the
array in the code itself, or we can add user input value into
the array.
Compile time Array initialization in C
Compile time initialization of array means we provide the
value for the array in the code, when we create the array,
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
63
FUNDAMENTALS OF COMPUTER PROGRAMMING
Syntax
There are many syntaxes for creating a character array
in c. The most basic syntax is,
char name[size];
Example
Before seeing the example, let us understand the
method of dynamic memory allocation which is used to create
the dynamic array.
Dynamic memory allocation is an efficient way to allocate
memory for a variable in c.
The memory is allocated in the runtime after getting the
number of characters from the user.
It uses pointers, which are structures that point to an
address where the real value of the variable is stored.
sizeof(datatype)
64
FUNDAMENTALS OF COMPUTER PROGRAMMING
#include<string.h>
int main(){
//initialization
char char_array[] = {'c', 'h', 'a', 'r', '$','*'};
int a=puts(char_array); //print array
if(a>0){
printf("printed successfully\n");
}
printf("length of character array = %d",strlen(char_array));
//prints length of the character array.
return 0;
}
Output
char$*
printed successfully
length of character array = 6
2.14 STRING:
A String in C programming is a sequence of characters
terminated with a null character ‘\0’. The C String is stored
as an array of characters. The difference between a
character array and a C string is the string is terminated
with a unique character ‘\0’.
65
FUNDAMENTALS OF COMPUTER PROGRAMMING
C String Initialization
A string in C can be initialized in different ways. We
will explain this with the help of an example. Below are the
examples to declare a string with the name str and initialize
it with “GeeksforGeeks”.
Ways to Initialize a String in C
------------------------------------UNIT II
COMPLETED---------------------------------
66