C MODULE I - 2021 - Syllabus

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

C Programming – Module I

1. Explain the concept of Constants


o Constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
o Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal.
o Constants can be declared using const keyword.
o Constants are treated just like regular variables except that their values cannot be modified after their
definition.

Example for Constants

Integer constant : 023, 0x4b

2. Explain the concept of Variables


o A variable is nothing but a name given to a storage area that our programs can manipulate.
o Each variable in C has a specific type, which determines the size and layout of the variable's memory.
o The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore.

There will be the following basic variable types −

Sr.No. Type & Description

1 char : Typically a single octet(one byte). This is an integer type.

2 int : The most natural size of integer for the machine.

3 float : A single-precision floating point value.

4 double : A double-precision floating point value.

5 void : Represents the absence of type.


Variable Declaration Example

int a, b;

int c;

float f;

3. Explain Keywords
o Some words of “C” language are kept reserved. These words have special meanings for C compiler, so
they are called Keyword or Reserve Words.

o Every Reserve Word has its own special meaning and every Reserve Word is used only to accomplish
special work in a particular situation.

o We can not use any Reserve Word as a normal identifier.

Keywords in C Programming

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

4. Describe Control Instructions in C


o Control statements enable us to specify the flow of program control; ie, the order in which
the instructions in a program must be executed.
o They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of
code to another.
o Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed.
o There are four types of control statements in C:

1. Decision making statements


2. Selection statements
3. Iteration statements
4. Jump statements
➢ if statement
If statement is used to test a condition, if condition is true then the code inside the if statement is executed
otherwise that code is not executed.

Syntax:

if(Boolean_expression)

{
// Body of if
}

Example:

if(i<=10){
printf(“value of i is less than or equal to 10”);

➢ if-else statement
The if-else statement is used to carry out a logical test and then take one of two possible actions depending on
the outcome of the test (ie, whether the outcome is true or false).

Syntax:

if(Boolean expression)
{

// Body of if statement
}
Else
{
// Body of else statement

Example:

The following program checks whether the entered number is positive or negative.
if(a>0)
{
printf(“ \n The number %d is positive”, a);
}
else
{
printf(“ \n The number %d is negative”, a);
}

➢ if…else if…else Statement


After if statement else if is used to check the multiple conditions.

Syntax:
if(Boolean_expression1)
{
// Body of if statement
}

else if(Boolean_expression2)
{
//Body of else if
}
else
{
// Body of else statement
}

Example

if(i<10)
{
printf(“value of i is less than 10”);
}
else if(i==10)
{
printf(“value of i is equal to10”);
}
else
{
printf(“value of i is greater than 10”);
}

➢ Nested If Statement
It contains multiple if else condition. It is used to check the multiple conditions. This statement is like
executing an if statement inside an else statement.

Syntax

if(Boolean_expression1)
{
//Body of if statement

if(Boolean_expression2)
{
//Body of nested if
}
}
else
{
//Body of else statement
}

Example

if ( i < 30 )
{
printf("Value of i is less than 30");
if ( j == 10 )
{
printf ("Value of j is equal to 10");
}
}
else
{
printf ("Value of i is not less than 30");
}
getch();
}

➢ Switch Statement
It contains a number of cases with different conditions. When a variable value is matched with the case,
then that case is executed.

Syntax

switch(expression)
{
case value1 :
//Statements
break;
case value2 :
//Statements
break;
case valuen :
//Statements
break;
default : //Optional
//Statements
}

Example

char grade = 'B';


switch(grade)
{
case 'A’:
printf("Excellent!\n" );
break;
case 'B’:
case 'C’:
printf("Well done\n" );
break;
case 'D’:
printf("You passed\n" );
break;
case 'F’:
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}

5. Explain Logical operators and hierarchy of 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.

Operator Meaning of Operator Example


Operator Meaning of Operator Example

Logial AND. True only if all operands If c = 5 and d = 2 then, expression ((c == 5) && (d >
&&
are true 5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5) || (d >
||
operand is true 5)) equals to 1.

Logical NOT. True only if the operand is


! If c = 5 then, expression ! (c == 5) equals to 0.
0
Hierarchy of logical operators

Operator precedence

! High

&& Medium

|| Low

6. What are conditional operators?

A conditional operator is a ternary operator, that is, it works on 3 operands. It used in decision making process.
In C Programming, Conditional Operator returns the statement depends upon the given expression result.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

7. Explain Looping control structures.

Sometimes we want some part of our code to be executed more than once. We can either repeat the code in our
program or use loops instead. It is obvious that if for example we need to execute some part of code for a
hundred times it is not practical to repeat the code. Alternatively we can use our repeating code inside a loop.
There are three methods for, while and do-while which we can repeat a part of a program.

1. while loop
o while loop is constructed of a condition or expression and a single command or a block of commands
that must run in a loop.
Syntax:

while(expression)
{
block of statement
}

Example:

int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}

2. for loop
o for loop is something similar to while loop but it is more complex. for loop is constructed from a control
statement that determines how many times the loop will run and a command section.
o Command section is either a single command or a block of commands.
o Control statement itself has three parts: for ( initialization; test condition; run every time command
)

Syntax:
for(control statement)
{
block of statement
}
Example
int a;
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
3. do-while loop

o The while and for loops test the termination condition at the top. By contrast, the third loop in C, the do-
while, tests at the bottom after making each pass through the loop body; the body is always executed at
least once.

Syntax:
do
{
statements;

} while (expression);

o The statement is executed, then expression is evaluated. If it is true, statement is evaluated again, and so
on. When the expression becomes false, the loop terminates.
o A do-while loop is used to ensure that the statements within the loop are executed at least once.

Example
int a = 10;
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

8. Explain Break & Continue statement

o "break" statement is used inside loops to terminate a loop and exit it (with a specific condition).

In below example loop execution continues until either num>=20 or entered score is negative.
while (num<20)
{
printf("Enter score : ");
scanf("%d",&scores[num]);
if(scores[num]<0)
break;
}
o Continue statement can be used in loops. Like break command continue changes flow of a program.
o It does not terminate the loop however.
o It just skips the rest of current iteration of the loop and returns to starting point of the loop.

Example:

while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}
9. Describe Operators in C
C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

ARITHMETIC OPERATORS IN C:
o C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.

Arithmetic Operators/Operation Example

+ (Addition) A+B

– (Subtraction) A-B

* (multiplication) A*B

/ (Division) A/B

% (Modulus) A%B

EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS:

int a=40,b=20, add,sub,mul,div,mod;


add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);

ASSIGNMENT OPERATORS IN C:
• In C programs, values for the variables are assigned using assignment operators.
• There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

Operators Example/Description

sum = 10;
= 10 is assigned to variable sum

sum += 10;
+= This is same as sum = sum + 10

sum -= 10;
-= This is same as sum = sum – 10

sum *= 10;
*= This is same as sum = sum * 10

sum /= 10;
/= This is same as sum = sum / 10

sum %= 10;
%= This is same as sum = sum % 10

sum&=10;
&= This is same as sum = sum & 10

sum ^= 10;
^= This is same as sum = sum ^ 10

RELATIONAL OPERATORS IN C:

Relational operators are used to find the relation between two variables. i.e. to compare the values of
two variables in a C program.
Operators Example/Description

> x > y (x is greater than y)

< x < y (x is less than y)

>= x >= y (x is greater than or equal to y)

<= x <= y (x is less than or equal to y)

== x == y (x is equal to y)

!= x != y (x is not equal to y)

LOGICAL OPERATORS IN C:
• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).

Operators Example/Description

&& (logical (x>5)&&(y<5)


AND) It returns true when both conditions are true

(x>=10)||(y>=10)

|| (logical OR) It returns true when at-least one of the condition is true

!((x>5)&&(y<5))

It reverses the state of the operand “((x>5) && (y<5))”


! (logical
NOT) If “((x>5) && (y<5))” is true, logical NOT operator makes it false

BIT WISE OPERATORS IN C:


• These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^
(XOR), << (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.

1. & - Bitwise AND


2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift

CONDITIONAL OR TERNARY OPERATORS IN C:

• Conditional operators return one value if condition is true and returns another value is
condition is false.
• This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);

Example : (A > 100 ? 0 : 1);

• In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to
if else conditional statements.

Increment/decrement Operators

• Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
• Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
• Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

SPECIAL OPERATORS IN C:

Below are some of the special operators that the C programming language offers.
Operators Description

This is used to get the address of the variable.

& Example : &a will give address of a.

This is used as pointer to a variable.

Example : * a where, * is pointer to the variable


* a.

This gives the size of the variable.

Sizeof () Example : size of (char) will give us 1.

FUNCTIONS

A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. Logically the division is such that each
function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

The general form of a function definition in C programming language is as follows −

return_typefunction_name( parameter list ){


body of the function
}

A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function −
• Return Type − A function may return a value. The return type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.

• Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a


value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

• Function Body − The function body contains a collection of statements that define what the
function does.

Example

Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */


int max(int num1,int num2){
/* local variable declaration */
int result;
if(num1 > num2)
result= num1;
else
result= num2;
return result;
}

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling the
function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example −

#include<stdio.h>
/* function declaration */
int max(int num1,int num2);
int main (){
/* local variable definition */
int a =100;
int b =200;
int ret;
/* calling a function to get max value */
ret= max(a, b);
printf("Max value is : %d\n", ret );
return0;
}
/* function returning the max between two numbers */
int max(int num1,int num2){
/* local variable declaration */
int result;
if(num1 > num2)
result= num1;
else
result= num2;
return result;
}

We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result −

Max value is : 200

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.

Formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.

While calling a function, there are two ways in which arguments can be passed to a function −

S.N. Call Type & Description

1 Call by value

This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have
no effect on the argument.

2 Call by reference

This method copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within a function
cannot alter the arguments used to call the function.
SCOPE OF VARIABLES

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables can
be declared in C programming language −

• Inside a function or a block which is called local variables.

• Outside of all functions which is called global variables.

• In the definition of function parameters which are called formal parameters.

Let us understand what are local and global variables, and formal parameters.

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.

#include<stdio.h>
int main (){
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a =10;
b =20;
c = a + b;
printf("value of a = %d, b = %d and c = %d\n", a, b, c);
return0;
}
Global Variables

Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.

#include<stdio.h>
/* global variable declaration */
int g;
int main (){
/* local variable declaration */
int a, b;
/* actual initialization */
a =10;
b =20;
g = a + b;
printf("value of a = %d, b = %d and g = %d\n", a, b, g);
return0;
}

A program can have same name for local and global variables but the value of local variable inside a
function will take preference. Here is an example −

#include<stdio.h>
/* global variable declaration */
int g =20;
int main (){
/* local variable declaration */
int g =10;
printf("value of g = %d\n", g);
return0;
}

When the above code is compiled and executed, it produces the following result −

value of g = 10

RECURSION

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.

The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of
a number, generating Fibonacci series, etc.

Number Factorial

The following example calculates the factorial of a given number using a recursive function −

#include<stdio.h>
int factorial(unsigned int i){
if(i <=1){
return1;
}
return i * factorial(i -1);
}
int main(){
int i =15;
printf("Factorial of %d is %d\n", i, factorial(i));
return0;
}

When the above code is compiled and executed, it produces the following result −

Factorial of 15 is 2004310016
Fibonacci Series

The following example generates the Fibonacci series for a given number using a recursive function −

#include<stdio.h>
Int fibonaci(int i){
if(i ==0){
return0;
}
if(i ==1){
return1;
}
return fibonaci(i-1)+fibonaci(i-2);
}
int main(){
int i;
for(i =0; i <10; i++){
printf("%d\t\n",fibonaci(i));
}
return0;
}

When the above code is compiled and executed, it produces the following result −

0 1 1 2 3 5 8 13 21 34

You might also like