You are on page 1of 60

Medi-Caps University, Indore

Faculty of Science
Department of Computer Science

CA3CO01
Problem Solving and Programming

Unit-II
Basics of Language
Books to be Referred
• Text Books
1. R.G. Dromey, How to Solve it by Computer, Pearson Education
2. B.W. Kernighan and D. M. Ritchie, The C Programming Language, Pearson Education.
3. B. Gottfried, Programming with C , 2nd Edition, (Indian Adapted Edition), TMH .

• References Books
1. H. Schildt C, The Complete Reference, Tata McGraw Hill.
2. E. Balaguruswamy, Programming in C, Tata McGraw Hill.
3. Y. Kanetkar, Let us C, BPB Publications.
4. Practical C Programming, 3rd Edition, A Nutshell Handbook O’Relly.
5. A. N Kamthaneet. al, Computer Programming and IT, Pearson Education, 2011.
Character Set
Every language contains a set of characters used to construct words, statements, etc., C language also has a
set of characters which include alphabets, digits, and special symbols. C language supports a total of 256
characters.
Every C program contains statements. These statements are constructed using words and these words are
constructed using characters from C character set. C language character set contains the following set of
characters...
1. Alphabets
2.Digits
3.Special Symbols

Alphabets
• C language supports all the alphabets from the English language. Lower and upper case
letters together support 52 alphabets.
• lower case letters - a to z
• UPPER CASE LETTERS - A to Z
Character Set
Digits
• C language supports 10 digits which are used to construct numerical values in C language.
• Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols
• C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL
bell backspace vertical tab etc.,
Identifier
• In C programming language, programmers specify names to a variable, array, pointer or function. An identifier is a collection
of characters which acts as the name of variable, function, array, pointer, structure, etc. That is, an identifier can be defined
as the user-defined name to identify an entity uniquely in the C Programming Language.

The identifier is a user-defined name of an entity to identify it uniquely during the program execution

Rules for Creating Identifiers

1.An identifier can contain letters (UPPERCASE and lowercase), numeric & underscore symbol only.


2.An identifier should not start with a numerical value. It can start with a letter or an underscore.
3.We should not use any special symbols in between the identifier even whitespace. However, the only underscore symbol is
allowed.

4.Keywords should not be used as identifiers.

5.There is no limit for the length of an identifier. However, the compiler considers the first 31 characters only.
6.An identifier must be unique in its scope.
Rules for Choosing a Variable
• A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits
0-9, and the underscore character.
• The first character must be a letter or underscore.
• Blank spaces cannot be used in variable names.
• Special characters like #, $ are not allowed.
• C keywords cannot be used as variable names.
• Variable names are case sensitive.
• Values of the variables can be numeric or alphabetic.
• Variable type can be char, int, float, double, or void.
Keywords
• A keyword is a reserved word. It has a predefined meaning and it is known to the compiler well in advance along with
its meaning.

• One cannot use it as a variable name, constant name, etc.

• There are only 32 reserved words (keywords) in the C language.

• Keywords are specific reserved words in C each of which has a specific feature associated with it.
• Almost all of the words which help us use the functionality of the C language are included in the list of keywords. 
Constants

 The value of Constants never changes during execution once defined.

 They are like a variable.


 Constants are also called literals.
 Constants can be any of the data types.

 It is considered best practice to define constants using only upper-case names.


 C Constants is the most fundamental and essential part of the C programming language.
 Constants in C are the fixed values that are used in a program, and its value remains the same during the entire execution of the
program.
2 ways to define constant in C
There are two ways to define constant in C programming.

1. const keyword
2.#define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.
Example - const float PI=3.14;  
#include<stdio.h>    
int main(){    

    const float PI=3.14;    

    printf("The value of PI is: %f",PI);    
    return 0;  

}     

The value of PI is: 3.140000


Data Types in C

• A data-type in C programming is a set of values and is determined to act on those values.


• Each variable in C has an associated data type.
• Each data type requires different amounts of memory and has some specific operations which can be performed over it.
• C provides various types of data-types which allow the programmer to select the appropriate type for the variable to
set its value.
• A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

C Data Types are used to:

• Identify the type of a variable when it declared.


• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.
Basic Data Types / Primary Data Types / System-Defined Data Type

• The definition of Basic Data Types / Primary Data Types / System-Defined Data Type is known to the compiler in
advance.
• The basic data types are char, integer-based and floating-point based. C language supports both signed and
unsigned literals.
• The memory size of the basic data types may change according to 32 or 64-bit operating system.
Basic Data Types / Primary Data Types / System-Defined Data Type
Format Specifiers of Basic Data Types / Primary Data Types /
System-Defined Data Type
Variables and Declaration
Syntax 1 :
type variable_name;

Or
Syntax 2 :
When the number of variables are more –
type variable_name, variable_name, variable_name;

EXAMPLES
1. int age ;
2. float percent ;
3. float radius, area;
Variable Declaration And Initialization

Syntax 1 :
type variable_name = Value ; (For Numeric Data Types)
Syntax 2 :
type variable_name = ‘Value’ ; (For Character Data Types)

EXAMPLE

int width, height=5;


char letter='A’;

float age, area;

double d;

/* actual initialization */

width = 10; age = 26.5;


Program Example of Data Type
/* c program to print value of a variable */

#include<stdio.h>
void main()
{
int age = 33;
printf("I am %d years old. \n", age);
}

Program Output

I am 33 years old.
Operators and Expressions
• An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

• C has a wide range of operators to perform various operations.

• Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is
incomplete without the use of operators.

• An operator operates on the operands. 


For example
c = a + b;
Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to
add both of the
operands ‘a’ and ‘b’. 
Other Operators
1. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division
etc. on numerical values (constants and variables). For example: if A = 10, B= 20, then
2. Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
3. Bitwise Operators
Bitwise operators are used in C programming to perform bit-level operations. Bitwise operator works on bits and perform
bit-by-bit operation. 

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-
level which makes processing faster and saves power.

The following table lists the bitwise operators. Assume variable 'A' holds 60 and variable 'B' holds 13, then −
3. Bitwise Operators
cont..
3. Bitwise Operators
cont..
Let A = 60 and
B = 13
Then in binary format, they will be as follows −

A = 0011 1100
B = 0000 1101
--------------------------------
A & B = 0000 1100
A | B = 0011 1101
A ^ B = 0011 0001
~A = 1100 0011

A =00111100
B =00001101
-------------------------------------
A&B =00001100
-------------------------------------
4. Logical Operators

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.

Example:
Let A = 1 and
B=0
5. Relational Operators
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.
For example: if A = 10, B= 20, then
5. Other Operators
Apart from above operators there are some other operators in C that are used to perform some specific task.

1. sizeof Operator: sizeof is a much used in the C programming language. It is a compile time unary operator which can be
used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.
Basically, sizeof operator is used to compute the size of the variable.
2. Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand
and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the
lowest precedence of any C operator. Comma acts as both operator and separator.
3. & Operator: Returns the address of a variable.
Example: &a; (It returns the actual address of the variable.)
4. * Operator: It is called Pointer to a variable.
Example: *a; (It is used to return the pointer to a variable.)
5. ?: Operator: It is called Conditional Operator and it is used to find Conditional Expressions. It is also called
Ternary Operator.
Broad Classification of Operators
• 1. Unary Operator: It has a Single Operand.
• Example: -
Minus is an Unary Operator

• 2. Binary Operator: It has Two Operands for its operation.


• Example: + , / , %
Plus, Division, Mod are Binary Operators

• 3. Ternary Operator: It has a Three Operands.


• Example: ?:
Conditional Operator is a Ternary Operator
All the operators that we’ve studied can be classified according to the number of operands.
Operator Precedence and Associativity

Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated.

Certain operators have higher precedence than others; for example, the multiplication operator has a higher
precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.

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 Precedence and Associativity cont.
Input and Output Functions
• C programming language provides many built-in functions to
(i) read any given input and 
(ii) display/write data on screen or in a file.

• To give input by the keyboard -------------------------- scanf( ), getchar( ) and gets( ) are used.
• To give output onto the screen ------------------------ printf( ), putchar( ), and puts( ) functions are used.
• These functions are inbuilt library functions, defined in stdio.h (header file).

The main difference between scanf( ) and gets( ) is:

1.scanf( ) reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters
newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.

2.Scanf( ) can read multiple values of different data types whereas gets() will only get character string data.
Input and Output Functions Contined

• printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);  
The format string can be (%d for int, %c for Character, %f for float data etc.)

Example: printf("enter a number:");    

• scanf() function
The scanf() function is used for input. It reads the input data from the console.
The syntax of printf() function is given below:
scanf("format string", &argument_list);  

Example: scanf("%d",&number);    
Simple Computational Problems involving the above constructs
C Program to print cube of given number
#include<stdio.h>    

void main()

{    

int number;    

printf(“Enter a number:");    

scanf("%d",&number);    

printf("cube of number is:%d ",number*number*number);    

}    

Output:
Enter a number: 4
Cube of number is: 64
Control Statements
The statements that are used to control the flow of execution of statements are known as conditional control statements.

Conditional statements are divided into three types

Conditional Statements Or Repetitive, Looping Jump Statements


Branching Statements Statements Or
Or Iterative Statements
Selection Statements

if statement switch..case for while do..while Conditional Jump Unconditional Jump

Break Continue goto


Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements


• Conditional Statements is used to check some given condition and perform some operations depending upon the correctness of that condition. It is
mostly used in the scenario where we need to perform the different operations for the different conditions.
• Types of decision-making statements
(i) if statement
(i.i) if-else statement
(i.2) else-if ladder statement
(ii) switch..case statement

(i) if statement
The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly
used in the scenario where we need to perform the different operations for the different conditions.
The syntax of the if statement is given below.
if(expression)
{  
//code to be executed  
}  
Example:
if(a > b)
{ printf(“A is bigger”);
}
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements

How if statement works?

The if statement evaluates the test expression inside the parenthesis ().


•If the test expression is evaluated to true, statements inside the body of if are executed.

•If the test expression is evaluated to false, statements inside the body of if are not executed.
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements

(i.i) if-else statement


The if statement may have optional else block. In it, the true condition block is executed if the condition is true otherwise the false condition block us executed.
The syntax of the if statement is given below.
if(expression)
{  
//code to be executed for true condition
}  
else
{  
//code to be executed for false condition

}  
Example:
if(a > b)
{ printf(“A is bigger”);
}
else
{ printf(“B is bigger”);
}
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements


(i.2) else..if ladder statement
The if else-if ladder statement is used to execute one code in comparison of multiple conditions in C programming.
The syntax of the if statement is given below.
if(expression 1)
{  
//code to be executed  if expression 1 is true
}  
else if(expression 2)
{  
//code to be executed  if expression 2 is true

}  
else if(expression 3)
{  
//code to be executed  if expression 3 is true

}  
else
{  
//code to be executed  if all the conditions are false
}  
// Program to relate two integers using =, > or < symbol
#include <stdio.h>

void main( )
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else
{
printf("Result: %d < %d",number1, number2);
}
}

Output:
Enter two integers: 13 24
Result : 13 < 24
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements

(ii) switch..case statement


It is a multiway decision statement. The switch statement tests the value of guven variable( or expression) against a list of
"case" values and when a match is found, a block of statements associated with that case is executed.
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the
different possible values of a single variable called switch variable. Here, We can define various statements in the multiple cases
for the different values of a single variable.

• The c switch statement is used to execute the code of multiple conditions. In a switch statement, you can not use operators, you have to
compare with a direct value like int value, float value, etc.

• Switch case statements have multiple cases to execute conditions and a default case that works like as else statement. This statement
allows a variable to be compared for equality against a list of values. Each value is known as a case, and the variable being checked for
each switch case.

• The break statement is optional in the switch statement. If there is no break statement in the switch case, all the switch cases will be
executed after matching the case value. It is called fall through the state of C switch statement.
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.


2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all
the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.

Limitations of switch
•Good for equality comparisons but not for range comparisons.
•Works good for int type data only and not good for other types of data.
•Works good with constants but not with variables (as case labels).
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements

Syntax for switch statement in C language

switch(expression)
{    
case value1:     //code to be executed;    
   break;  //optional  

case value2:      //code to be executed; 
   break;  //optional  
......    
    
default:        // code to be executed if all cases are not matched;    

}    
Control Statements Continued

Selection Statements Or Conditional Statements Or Branching Statements


Example for switch statement in C language
#include<stdio.h>  
void main()
{    
int number=0;     
printf("enter a number:");    
scanf("%d",&number);    
switch(number)
{    
case 10:    
printf("number is equals to 10");    
break;    
case 50:    
printf("number is equal to 50");    
break;    
case 100:    
printf("number is equal to 100");    
break;    
default:    
printf("number is not equal to 10, 50 or 100");    
}    
  }    
Control Statements Continued

Repetitive Statements Or Iterative Statements Or Looping Statements

The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are
three types of loops used in the C language. that is,(i) do..while (ii) while (iii) for

Why use loops in C language?


The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that
instead of writing the same code again and again, we can repeat the same code for a finite number of times. For
example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can
print inside a loop which runs up to 10 iterations.

Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Control Statements Continued

Repetitive Statements Or Iterative Statements Or Looping Statements

(i) do-while loop


The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is
necessary to execute the loop at least once (mostly menu driven programs).

The syntax of do-while loop in c language


do
{  
//code to be executed  
}while(condition);  
Control Statements Continued

Repetitive Statements Or Iterative Statements Or Looping Statements

(ii) while loop


The while loop in c is to be used in the scenario where we don't know the number of iterations in advance. The block of
statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.

The syntax of while loop in c language


while(condition)
{  
//code to be executed  
}  
Control Statements Continued

Repetitive Statements Or Iterative Statements Or Looping Statements

(iii) for loop


The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied.
The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in
advance.
The syntax of for loop in c language
for(initialization; condition; increment / decrement)
{  
//code to be executed  
}  
Control Statements Continued

Jump Statements
(i) Conditional Jump
(i) Break
(ii) Continue

(i) Break Statement

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used
inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it
breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following
two scenarios:
1.With switch case
2.With loop
Syntax:
//loop or switch case   
break;  
Control Statements Continued

Jump Statements
(i) Conditional Jump
(i) Break
(ii) Continue

(ii) Continue Statement

The continue statement in C language is used to bring the program control to the beginning of the loop. The continue
statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a
condition so that we can skip some code for a particular condition.
Syntax:
//loop statements  
continue;  
//some lines of the code which is to be skipped  
Control Statements Continued

Jump Statements
(ii) Unconditional Jump
(i) goto

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program
control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition.
It can also be used to break the multiple loops which can't be done by using a single break statement. However, using
goto is avoided these days since it makes the program less readable and complicated.
Syntax:
label:   
//some part of the code;   
goto label;  
Nesting of Control Statements
• C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside
another loop. Let's observe an example of nesting loops in C.

• Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example,
you can define 'while' loop inside a 'for' loop.

Syntax for Nested Control statements:


Outer_loop  
{  
    Inner_loop  
   {  
         // inner loop statements.  
   }  
       // outer loop statements.  
}  
• Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
Nested for loop
The nested for loop means any type of loop which is defined inside the 'for' loop.

for (initialization; condition; update)   
{  
    for(initialization; condition; update)  
    {  
           // inner loop statements.  
    }  
    // outer loop statements.  
}  

Nested while loop


The nested while loop means any type of loop which is defined inside
the 'while' loop.
Nested while loop
The nested while loop means any type of loop which is defined inside the ‘while' loop.

while(condition)  

{  

    while(condition)  

    {  

         // inner loop statements.  

    }  

// outer loop statements.  

}  
Nested do..while loop
The nested do..while loop means any type of loop which is defined inside the ‘do..while' loop.

Syntax of Nested do..while Loop

do  
{  
do  
{   
  // inner loop statements.  
   } while(condition);  
// outer loop statements.  
} while(condition);  
C Program to print all the characters of C Character Set

#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}

You might also like