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

Index

1. Introduction……..…………………………………….02
2. Operators in C Programming……………..…...08
3. Loops in C programming………………………….15
4. Arrays in C programming…………………………25
5. Switch case in C programming…………………31
6. Functions in C programming……………………36
7. Recursion in C programming……………………45
8. String in C programming………………………….50
9. Pointer in C programming……………………….57
10. Patterns Display…………………………………….63

Siyam
EEE 16th
Structured Programming Language (CSE113)
Lecture # 01
Introduction to C Programming
C Programming Language
C is a powerful general-purpose programming language. It is fast, portable and available in all platforms.
It is used for wide range of applications from Operating systems like Windows and iOS to software that
is used for creating 3D movies.

C programming is considered as the base for other programming languages, that is why it is known as
mother language.
It can be defined by following ways:
 Mother language
 System programming language
 Procedure-oriented programming language
 Structured programming language
 Mid-level programming language

C is called a structured programming language because to solve a large problem, C programming


language divides the problem into smaller modules called functions or procedures each of which
handles a particular responsibility. The program which solves the entire problem is a collection of such
functions.

History of C Language
 C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in U.S.A.
 C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
 C language was invented for implementing UNIX operating system

Uses of C programming language:


The C programming language is used for developing system applications that forms a major portion of
operating systems such as Windows, UNIX and Linux. Below are some examples of C being used.
 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


First C program: “Hello, World!” program:
“Hello, World!” is a simple program that displays “Hello, World!” on the screen. Since, it’s a very simple
program, it is used to illustrate the basic syntax of any programming language.
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Let’s look into various parts of the above C program:
 #include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h.
 The main() function is the entry point of every program in C language. The code inside the curly
braces { } is the body of main() function. The main() function is mandatory in every C program.
 The printf() is a library function is used for output. It prints the given statement to the console.
In this program, it displays Hello World! on the screen.
 The return statement return 0; inside the main() function ends the program. This statement isn’t
mandatory. However, it’s considered good programming practice to use it.

printf() & scanf() in C


The printf() and scanf() functions are used for output and input in C language. Both functions are
built-in library functions, defined in stdio.h (header file).
printf() function: The printf() function is used for output. It prints the given statement to the console.
scanf() function: The scanf() function is used for input. It reads the input data from the console.

Purposes of printf() function:


1. To display any message
Example: printf(“Welcome 2017”);
2. To create new line, tab space etc.
Example: printf(“\n”);
printf(“Hello\n2017”);
printf(“\t”);
3. To display any value
Example: printf(“%d”,10+20+6);
%d for integer %f for float %lf for double %c for char (character)
4. To display any value of a variable
int x;

Variable Type Variable Name


Example:
int x = 100; // x is a variable name, int is variable type
printf(“%d”, x); // %d for integer
2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com
Program Example: Write a C program to add two numbers. Here, variable type should
be float and value of variables must be taken using keyboard.
Source Code:
#include<stdio.h>
int main()
{
float x, y; //Variable declaration
printf("Enter first number = "); //message for user
scanf("%f", &x); //input from user
printf("Enter second number = "); //message for user
scanf("%f", &y); //input from user
printf("Result = %f\n", x + y); //output
return 0;
}
Output:

Comments in C:
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. Comments are explanatory notes for user. They are ignored by the compiler. There
are two types of comments:
1. Single line comment
Example: //Creator: Bulbul Ahamed
2. Multiple line comment
Example:
/* Creator: Bulbul Ahamed
Date: February 12, 2017 */
Variables in C:
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be
reused many times.
The syntax to declare a variable:
type variable_list;
The example of declaring variable is given below:
 int a;
 float b;
 char c;
Here, a, b, c are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
 int a = 10, b = 20; //declaring 2 variable of integer type
 float f = 20.8;
 char c = 'A';
3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com
Rules for defining variables
 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. int, float etc.
Valid variable names: Invalid variable names:
 int a;  int 2;
 int _ab;  int a b;
 int a30;  int long;

Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable : A variable that is declared inside the function or block is called local variable.
void main() {
int x = 10; //local variable
}
You must have to initialize the local variable before it is used.

Global Variable: A variable that is declared outside the function or block is called global variable. Any
function can change the value of the global variable. It is available to all the functions.
int value = 20; //global variable
void main () {
int x = 10; //local variable
}

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
There are 4 types of data types in C language.

Types Data Types


Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Void Data Type void
Enumeration Data Type enum
The following table provides the details of standard integer types with their storage sizes and value
ranges –
Types Storage size
char 1 byte
int 2 or 4 bytes
float 4 bytes
double 8 bytes
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes.

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example: sizeof() function
#include<stdio.h>
int main() {
printf("%d\n", sizeof(char));
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(float));
printf("%d\n", sizeof(double));
return 0;
}
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are only
32 reserved words (keywords) in C language. A list of 32 keywords in c language is given below:
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
Escape sequences in C
The backslash (\) is called an escape character. It indicates that printf() is supposed to do something out
of the ordinary.
List of common Escape Sequences in C:
Escape Sequence Meaning
\n New Line
\t Tab (Horizontal)
\' Single Quote
\" Double Quote
\? Question Mark
\a Alarm or Beep
\0 Null
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 'a', 3.4,
"programming" etc. There are different types of constants in C programming.
Constant Example
Decimal Constant 10, 20, 450 etc.
Real or Floating-point Constant 10.3, 20.2, 450.6 etc.
Character Constant 'a', 'b', 'x' etc.
String Constant "c", "program", "Hello World" etc.
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
Example:
const float PI=3.1416;
#define PI 3.1416

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example: A program to find the area of a circle. Here, the value of radius must
be taken from user.

Source Code: Source Code:


#include<stdio.h> #include<stdio.h>
#define PI 3.1416 int main()
int main() {
{ const float PI = 3.1416;
float radius,area; float radius,area;
printf("Enter the value of radius: "); printf("Enter the value of radius: ");
scanf("%f",&radius); scanf("%f",&radius);
area = PI * radius * radius; area = PI * radius * radius;
printf("Area = %f\n",area); printf("Area = %f\n",area);
} }
Output:

……………………..

6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture # 02
Operators in C programming
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Misc Operators
1. Arithmetic Operators
int x = 13, y = 6, z;
Operator symbol Example Result
Addition + z=x+y 19
Subtraction - z=x-y 7
Multiplication * z=x*y 78
Division / z=x/y 2
Modulus % z=x%y 1
(Post) increment ++ x++ 13
x=x+1
(Pre) increment ++ ++x 14
x=x +1
(Post) Decrement -- x-- 13
(Pre) Decrement -- --x 12
Program Example 1: Arithmetic Operators
Source Code:
#include<stdio.h>
int main()
{
int x = 20, y = 10; //Variable Declaration
printf("%d\n", x + y); //Addition
printf("%d\n", x - y); //subtraction
printf("%d\n", x * y); //Multiplication
printf("%d\n", x / y); //Division
return 0;
}
Output:

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 2: division and modulus
Source Code:

#include<stdio.h>
int main()
{
int x = 13, y = 6, z;
z = x / y; // division
printf("Division = %d\n", z);
z = x % y; // modulus
printf("Modulus = %d\n", z);
return 0;
}
Output:

Program Example 3: Pre and Post decrement

Source Code:

#include<stdio.h>
int main()
{
int x = 13;
printf("%d\n", x--); //13 but in memory 12
printf("%d\n", x); //12
printf("%d\n", --x); //11
printf("%d\n", x);//11
return 0;
}
Output:

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


2. Relational Operators
int x = 13, y = 6;
Operator symbol Example Result
x == y
Equal == 0
13 == 6
x != y
Not equal != 1
13 != 6
x>y
Greater than > 1
13 > 6
x<y
Less than < 0
13 < 6
x >= y
Greater than or equal to >= 13 >= 6 1
6 >= 6
x <= y
Less than or equal to <= 0
13 <= 6

Program Examples: Relational Operators

Q1. Write a C program to check a number whether it is odd or even.


Source Code:
#include<stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d",&number);
if(number%2 == 0)
printf("Even Number\n");
else
printf("Odd Number\n");
return 0;
}
Output:

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q2. Write a C program to check a number whether it is positive or negative.
Source Code:
#include<stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d",&number);
if(number < 0)
printf("%d is a negetive Number\n",number);
else
printf("%d is a postive Number\n",number);
return 0;
}
Output:

Q3. Write a C program to display You are an adult if the value of age is 18 or more,
otherwise it will display You are a child.
Source Code:
#include<stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d",&age);
if(age >= 18)
printf("You are an adult. Your age is %d\n",age);
else
printf("You are a child. Your age is %d\n",age);
return 0;
}
Output:

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


3. Logical Operators
Operator symbol
Logical AND &&
Logical OR ||
Logical NOT !
Q1. Write a C program to find the grade according to the following table:
Marks (M) Grade
80 – 100 A+
70 – 79 A
60 – 69 A-
50 – 59 B
40 –49 C
33 – 39 D
0 – 32 F
Here, the value of marks(M) must be taken from user.
N.B. If any user put more than 100 or less than 0 the program will give the following
error message:
You entered invalid marks!
Source Code:
#include<stdio.h>
int main()
{
int M; //M : marks
printf("Enter your marks: ");
scanf("%d", &M);
if(M > 100 || M < 0) //double pipe
printf(" You Entered Invalid Marks! ");
else if(M >= 80)
printf("A+");
else if(M >= 70)
printf("A");
else if(M >= 60)
printf("A-");
else if(M >= 50)
printf("B");
else if(M >= 40)
printf("C");
else if(M >= 33)
printf("D");
else
printf("F");
return 0;
}
5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com
Output:

4. Assignment Operators

The following table lists the assignment operators supported by the C language –
Operator Description Example
Simple assignment operator. Assigns values C = A + B will assign the value of
=
from right side operands to left side operand A + B to C
Add AND assignment operator. It adds the
+= right operand to the left operand and assign C += A is equivalent to C = C + A
the result to the left operand.
Subtract AND assignment operator. It
subtracts the right operand from the left
−= C -= A is equivalent to C = C - A
operand and assigns the result to the left
operand.
Multiply AND assignment operator. It
multiplies the right operand with the left
*= C *= A is equivalent to C = C * A
operand and assigns the result to the left
operand.
Divide AND assignment operator. It divides
/= the left operand with the right operand and C /= A is equivalent to C = C / A
assigns the result to the left operand.
Modulus AND assignment operator. It takes
%= modulus using two operands and assigns the C %= A is equivalent to C = C % A
result to the left operand.

5. Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The following table lists the
bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −

Operator Description Example


Binary AND Operator copies a bit to the
& (A & B) = 12, i.e., 0000 1100
result if it exists in both operands.
Binary OR Operator copies a bit if it exists
| (A | B) = 61, i.e., 0011 1101
in either operand.
Binary XOR Operator copies the bit if it is
^ (A ^ B) = 49, i.e., 0011 0001
set in one operand but not both.
Binary Ones Complement Operator is unary (~A ) = -61, i.e,. 1100 0011 in 2's
~
and has the effect of 'flipping' bits. complement form.
Binary Left Shift Operator. The left
<< operands value is moved left by the number A << 2 = 240 i.e., 1111 0000
of bits specified by the right operand.
Binary Right Shift Operator. The left
operands value is moved right by the
>> A >> 2 = 15 i.e., 0000 1111
number of bits specified by the right
operand.
6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com
6. Misc Operators
Besides the operators discussed above, there are a few other important operators including sizeof
and ? : supported by the C Language.

Operator Description Example


sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
&a; returns the actual address of the
& Returns the address of a variable.
variable.
* Pointer to a variable. *a;
If Condition is true ? then value X :
?: Conditional Expression.
otherwise value Y

Q1. Write a C program using conditional expression (ternary operator) to check a


number whether it is odd or even.
Source Code:
#include<stdio.h>
int main()
{
int n;
printf("Enter a numebr : ");
scanf("%d",&n);
(n%2==0)? printf("Even Number\n") : printf("Odd Number\n");
return 0;
}
Output:

7 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #03
Loops in C programming
Loops are used for executing a block of statements repeatedly until a given condition returns
false. There are three types of loop in C. They are:
1. for loop
2. while loop
3. do-while loop

1. for Loop
The for loop is commonly used when the number of iterations is known.
The syntax of for loop is:
for(initialization; condition ; increment/decrement)
{
statement-block;
}

How for loop works?


 The initialization statement is executed only once.
 Then, the condition (test expression) is evaluated. If the condition is false (0), for loop is
terminated. But if the test expression is true (nonzero), codes inside the body of for
loop is executed and the update expression (increment/decrement) is updated.
 This process repeats until the condition is false.
Flowchart of for loop

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 1: Display numbers from 1 to 10
Source Code:
#include<stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
printf("%d\t",i);
return 0;
}
Output:

Program Example 2: Display numbers from 1 to n


Source Code:

#include<stdio.h>
int main()
{
int i,n;
printf("Enter any numebr: ");
scanf("%d",&n); //Input upper limit from user
for(i = 1; i <= n; i++)
printf("%d\t",i);
return 0;
}
Output:

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 3: Display odd numbers from 1 to n

Source Code:

#include<stdio.h>
int main()
{
int i,n;
printf("Enter any numebr: ");
scanf("%d",&n); //Input upper limit from user
for(i = 1; i <= n; i = i + 2)
printf("%d\t",i);
return 0;
}
Output:

Program Example 4: Display even numbers from 1 to n


Source Code:

#include<stdio.h>
int main()
{
int i,n;
printf("Enter any numebr: ");
scanf("%d",&n); //Input upper limit from user
for(i = 2; i <= n; i = i + 2)
printf("%d\t",i);
return 0;
}
Output:

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 5: Display alphabets from A to Z
Source Code:

#include<stdio.h>
int main()
{
char i;
for(i = 'A'; i <= 'Z'; i = i + 1)
printf("%c\t",i);
return 0;
}
Output:

Program Example 6: Display alphabets from A to Z using ASCII values

Source Code:

#include<stdio.h>
int main()
{
int i;
for(i = 65; i <= 90; i = i + 1)
printf("%c\t",i);
return 0;
}
Output:

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 7: Display number from n to 1
Source Code:
#include<stdio.h>
int main()
{
int i,n;
printf("Enter any numebr: ");
scanf("%d",&n); //Input upper limit from user
for(i = n; i >= 1; i = i - 1)
printf("%d\t",i);
return 0;
}
Output:

Program Example 8: Sum of number from 1 to n


Source Code:
#include<stdio.h>
int main()
{
int i,n,sum = 0;
printf("Enter any number: ");
scanf("%d",&n); //Input upper limit from user
for(i = 1; i <= n; i = i + 1){
sum = sum + i;
}
printf("Summation = %d\n",sum);
return 0;
}
Output:

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 9: Display multiplication table
Source Code:
#include<stdio.h>
int main()
{
int i,num,p;
printf("Enter any number: ");
scanf("%d",&num); //Input upper limit from user
for(i = 1; i <= 10; i = i + 1){
p = num * i;
printf("%d * %d = %d\n",num,i,p);
}
return 0;
}
Output:

6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


2. While loop

 while loop iterates the code until condition is false. Here, condition is given before the
code. So code may be executed 0 or more times.
 It is better if number of iteration is not known by the user.

The syntax of a while loop is:


while (condition)
{
//Statements to be executed repeatedly
}
How while loop works?
 The while loop evaluates the condition.
 If the condition is true (nonzero), codes inside the body of while loop are executed. The
condition is evaluated again. The process goes on until the condition is false.
 When the condition is false, the while loop is terminated.

Flowchart of while loop

Infinite while loop


If the condition to be tested is always true, the loop will run forever i.e. infinite times.
For example,
while (1)
{
printf("This is infinite loop");
}

7 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 1: Display numbers from 1 to 10
Source Code:
#include<stdio.h>
int main()
{
int i = 1;
while(i <= 10){
printf("%d\t",i);
i++;
}
return 0;
}
Output:

Program Example 2: Display numbers from 1 to n


Source Code:

#include<stdio.h>
int main()
{
int i = 1,n;
printf("Enter any number: ");
scanf("%d",&n);
while(i <= n){
printf("%d\t",i);
i++;
}
return 0;
}
Output:

8 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


3. do…while loop
 In do while loop, statement is given before the condition, so statement or code will be
executed at least one time. In other words, we can say it is executed 1 or more times.
 It is better if you have to execute the code at least once.
The syntax of C language do-while loop is given below:

do{

//code to be executed

} while(condition);

How do…while loop works?


 The code block (loop body) inside the braces is executed once.
 Then, the condition is evaluated. If the condition is true, the loop body is executed
again. This process goes on until the condition is evaluated to 0 (false).
 When the condition is false (nonzero), the do...while loop is terminated.

Flowchart of do...while loop

Infinite do-while loop


There may be a condition in a do-while loop which is always true. In such case, the loop will run
infinite times. For example,
do
{
printf("This is infinite loop");
}while(1);

9 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Program Example 1: Display numbers from 1 to 10
Source Code:
#include<stdio.h>
int main()
{
int i = 1;
do{
printf("%d\t",i);
i++;
}while(i <= 10);
}
Output:

Program Example 2: Display numbers from 1 to n


Source Code:
#include<stdio.h>
int main()
{
int i = 1,n;
printf("Enter any number: ");
scanf("%d",&n);
do{
printf("%d\t",i);
i++;
}while(i <= n);
}
Output:

Difference between while & do while loops in C language:


while do while
Loop is executed for first time irrespective of the
Loop is executed only
condition. After executing while loop for first
when condition is true.
time, then condition is checked.

10 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #04
Arrays in C programming
An array is a collection of data that holds fixed number of values of same type. For example, if
you want to store marks of 100 students, you can create an array for it.
float marks [100];
The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays

How to declare an array in C?


data_type array_name[array_size];
This is called a one-dimensional array. The array_size must be an integer constant greater than
zero and type can be any valid C data type.
For example:
float marks[100];
Here, we declared an array, marks, of floating-point type and size 100. Meaning, it can hold 100
floating-point values.
Following are the important terms to understand the concept of Array.
 Element − each item stored in an array is called an element.
 Index − each location of an element in an array has a numerical index, which is used to
identify the element.

As per the above illustration, following are the important points to be considered.
 Array length = 10, First Index = 0, Last Index = 9
 Index starts with 0.
 Array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 27.

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Why do we need arrays?
We can use normal variables (v1, v2, v3, ...) when we have small number of objects, but if we
want to store large number of instances, it becomes difficult to manage them with normal
variables. The idea of array is to represent many instances in one variable.

Basic Operations
Following are the basic operations supported by an array.
 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.

Q1. Print 1-dimension array elements with index.


Source Code: Output:
#include<stdio.h>
int main()
{
int a[5] = {7,2,3,9,5};
int i;
for(i = 0; i < 5; i++)
printf("a[%d] = %d\n",i,a[i]);
return 0;
}

Source Code: Output:


#include<stdio.h>
#define MAX 10

int main()
{
int a[MAX] = {7,2,3,9,5};
int i;
for(i = 0; i < MAX; i++)
printf("a[%d] = %d\n",i,a[i]);
return 0;
}

 A one-dimensional array is like a list.

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q2. Write a program to find average marks obtained by a class of 5 students in a test.

Source Code:
#include<stdio.h>
main()
{
int avg, i, sum=0;
int marks[5] ; //array declaration
for ( i = 0 ; i < 5 ; i++ )
{
printf ( "Enter marks: " ) ;
scanf ( "%d", &marks[i] ) ; //store data in array
}
for ( i = 0 ; i < 5 ; i++ )
sum = sum + marks[i] ; //read data from an array
avg = sum / 5 ;
printf ( "\nAverage marks = %d\n", avg ) ;
}

Output:

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q3. Write a program to find largest element of an array.

Source Code:
#include<stdio.h>
int main()
{
int a[100];
int i,n;
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
// Stores number entered by the user
for(i = 0; i < n; i++){
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
// Loop to store largest number to arr[0]
for(i = 0; i < n; i++){
if(a[0] < a[i]){
a[0] = a[i];
}
}
printf("Largest Element is: %d\n",a[0]);
}
Output:

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q4. Print 2-dimension array elements.

Source Code: Output:


#include<stdio.h>

int main()
{
int a[3][2] = { {10,20}, {30,40}, {50,60} };
int i,j;

for(i = 0; i < 3; i++){


for(j = 0; j < 2; j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
}

Q5. Print 2-dimension array elements with index.

Source Code: Output:


#include<stdio.h>

int main()
{
int a[3][2] = { {10,20}, {30,40}, {50,60} };
int i,j;

for(i = 0; i < 3; i++){


for(j = 0; j < 2; j++){
printf("a[%d][%d] = %d\t",i,j,a[i][j]);
}
printf("\n");
}
}
 A two-dimensional array is like a table.

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q6. 2-dimension array summation

Source Code:
#include<stdio.h>
int main()
{
int a[3][2] = { {5,0}, {1,2}, {2,3} };
int b[3][2] = { {1,2}, {2,3}, {3,6} };
int c[3][2];
int i, j;

for(i = 0; i < 3; i++){ //no. of rows


for(j = 0; j < 2; j++){ //no. of columns
c[i][j] = a[i][j] + b[i][j];
printf( "%d\t", c[i][j] );
}
printf("\n");
}
return 0;
}

Output:

6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #05
Switch Case in C programming

Switch statement
• A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
• Switch statement is used to solve multiple option type problems for menu like program,
where one value is associated with each option.
• Switch case statements mostly used when we have number of options (or choices) and we
may need to perform a different task for each choice.

Syntax of switch...case
switch(n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;

case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}

Break statement
Break statements are useful when you want your program-flow to come out of the switch
body. Whenever a break statement is encountered in the switch body, the execution flow
would directly come out of the switch.

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


switch Statement Flowchart

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Few points about Switch Case
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value
after case keyword. Also, case doesn’t need to be in an ascending order always, you can
specify them in any order as per the need of the program.
2) You can also use characters in switch case. for example –
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("Case D ");
break;
case 'b':
printf("Case B");
break;
case 'c':
printf("Case C");
break;
case 'z':
printf("Case Z ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case B

3) The expression provided in the switch should result in a constant value otherwise it
would not be valid.

Valid expressions for switch –


// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
// Variable expression are allowed
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)

4) Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes
program more complex and less readable.

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Q1. Write a C Program to perform the following operations between two integers
using switch case:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Source Code
#include<stdio.h>
int main()
{
int choice;
int a,b;
printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter the value of a & b: ");
scanf("%d %d",&a,&b);
printf("a + b = %d\n",a+b);
break;
case 2:
printf("Enter the value of a & b: ");
scanf("%d %d",&a,&b);
printf("a - b = %d\n",a-b);
break;
case 3:
printf("Enter the value of a & b: ");
scanf("%d %d",&a,&b);
printf("a * b = %d\n",a*b);
break;
case 4:
printf("Enter the value of a & b: ");
scanf("%d %d",&a,&b);
printf("a / b = %d\n",a/b);
break;
default:
printf("Invalid choice\n");
}
return 0;
}

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Exercise Questions
1. Write a C program to read weekday number (1-7) and print weekday name (Saturday,
Sunday …) using switch.
2. Write a C program to read gender (M/F) and print corresponding gender using switch.
3. Write C program to check whether a character is VOWEL or CONSONANT using switch.
4. Write a C program to check whether number is EVEN or ODD using switch.
5. Write a C program to find number of days in a month using switch case.
6. Write a C program to design calculator with basic operations using switch.

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #06
Functions in C Programming

Function: A function is a block of code that performs a specific task.

Types of functions in C programming


There are two types of functions in C programming:
• Standard library functions
• User defined functions

Standard library functions


The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc. These functions are defined in
the header file. When you include the header file, these functions are available for use.
Example: printf(), scanf(), getchar(), fprintf() etc.

User-defined functions (UDF)


The functions are declared and defined by the programmer/user known as User Define Function.
Example: SU(), add(), area() etc.

Advantages of user-defined function


• The program will be easier to understand, maintain and debug.
• Reusable codes that can be used in other programs
• A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.

Uses of C functions:
• Used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C functions to make use of same functionality wherever
required.
• We can call functions any number of times in a program and from any place in a
program.
• A large C program can easily be tracked when it is divided into functions.
• The core concept of C functions are re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


C function declaration, function call and function definition:
There are 3 aspects in each C function. They are,
• Function declaration or prototype – This informs compiler about the function name,
function parameters and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.
C functions aspects syntax
function declaration return_type function_name (argument list);
Return_type function_name (arguments list)
function definition
{ Body of function; }
function call function_name (arguments list);

C function arguments and return values


All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example
C programs for each one of the below.
1. C function without arguments and without return value
2. C function with arguments and with return value
3. C function with arguments and without return value
4. C function without arguments and with return value

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


1. C function without arguments and without return value
Example: Add Two Numbers
Source Code:
#include<stdio.h>

void add(); //function declaration

int main()
{
add(); // function call
return 0; output:
}

//function definition
void add()
{
int a,b,sum;
printf("Enter the value of a & b : ");
scanf("%d %d",&a,&b);
sum = a + b;
printf("a + b = %d\n",sum);
}

2. C function with arguments and with return value


Example: Add Two Numbers
Source Code:
#include<stdio.h>
int add(int x, int y); //function declaration
int main()
{
int a,b,k;
printf("Enter the value of a & b : ");
scanf("%d %d",&a,&b); output:
k = add(a,b); // function call
printf("a + b = %d\n",k);
return 0;
}
//function definition
int add(int x, int y)
{
int sum;
sum = x + y;
return sum;
}

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


3. C function with arguments and without return value
Example: Add Two Numbers
Source Code:
#include<stdio.h>

void add(int x, int y); //function declaration

int main()
{
int a,b;
printf("Enter the value of a & b : "); output:
scanf("%d %d",&a,&b);
add(a,b); // function call
return 0;
}

//function definition
void add(int x, int y)
{
int sum;
sum = x + y;
printf("a + b = %d\n",sum);
}
4. C function without arguments and with return value
Example: Add Two Numbers
Source Code:
#include<stdio.h>
int add(); //function declaration
int main()
{
int k;
k = add(); // function call
printf("a + b = %d\n",k); output:
return 0;
}
//function definition
int add()
{
int a,b, sum;
printf("Enter the value of a & b : ");
scanf("%d %d",&a,&b);
sum = a + b;
return sum;
}

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


5. Program to Swap Numbers Using Temporary Variable

Source Code:
#include<stdio.h>

void swap(); //function declaration

int main()
{
swap(); //function call
return 0;
}

//function definition
void swap(){
int x, y, temp;

printf("Enter the value of x : ");


scanf("%d", &x);

printf("Enter the value of y : ");


scanf("%d", &y);

printf("Before Swapping: x = %d, y = %d\n", x, y);

temp = x;
x = y;
y = temp;

printf("After Swapping: x = %d, y = %d\n", x, y);


}

Output:

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


6. Program to Swap Numbers without Using Temporary Variable
a) using + and – operators
b) using * and / operators
c) using bitwise X-OR

a) Source Code:
#include<stdio.h>

void swap();//function declaration

int main()
{
swap();//function call
return 0;
}

//function definition
void swap(){
int x,y;

printf("Enter the value of x : ");


scanf("%d",&x);

printf("Enter the value of y : ");


scanf("%d",&y);

printf("Before Swapping: x = %d, y = %d\n",x,y);


x = x * y;
y = x / y;
x = x / y;
printf("After Swapping: x = %d, y = %d\n",x,y);
}

Output:

6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


b) Source Code:
#include<stdio.h>

void swap();//function declaration

int main()
{
swap();//function call
return 0;
}

//function definition
void swap(){
int x,y;

printf("Enter the value of x : ");


scanf("%d",&x);

printf("Enter the value of y : ");


scanf("%d",&y);

printf("Before Swapping: x = %d, y = %d\n",x,y);


x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("After Swapping: x = %d, y = %d\n",x,y);
}

Output:

7 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


c) Source Code:
#include<stdio.h>

void swap();//function declaration

int main()
{
swap();//function call
return 0;
}

//function definition
void swap(){
int x,y;

printf("Enter the value of x : ");


scanf("%d",&x);

printf("Enter the value of y : ");


scanf("%d",&y);

printf("Before Swapping: x = %d, y = %d\n",x,y);


x = x + y;
y = x - y;
x = x - y;
printf("After Swapping: x = %d, y = %d\n",x,y);
}

Output:

8 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


7. Create two functions named square() and area() to perform the following tasks:
o square() : to find the square of a number
o area() : to find the area of a circle

#include<stdio.h>

void square();
void area();

int main(){
square();
area();
}

//This segment help us to find the square of a number


void square(){
int k, s;
printf("Enter a number : ");
scanf("%d", &k);
s = k*k;
printf("Square = %d\n",s);
}

//This segment help us to find the area of a circle


void area(){
const float pi = 3.1416,r,k;
printf("Enter radius of a circle : ");
scanf("%f",&r);
k = pi*r*r;
printf("Area = %f\n",k);
}

9 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #07
Recursion in C Programming

A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
Recursive function is very useful to solve many mathematical problems like to
calculate factorial of a number, generating Fibonacci series, etc.

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where
one branch makes the recursive call and other doesn't.

Advantages and Disadvantages of Recursion


 Advantages: Recursion makes program elegant and cleaner. All algorithms can be
defined recursively which makes it easier to visualize and prove.
 Disadvantages: If the speed of the program is vital then, you should avoid using
recursion. Recursions use more memory and are generally slow. Instead, you can
use loop.

1 Bulbul Ahamed www.bulbulcse.com


Example 1: Factorial of a Number Using Recursion
#include<stdio.h>

int fact(int n); int fact(int n){


if(n == 0)
int main()
return 1;
{
else
int n, k;
return n * fact(n-1);
printf("Enter the value of n : "); }
scanf("%d", &n);
k = fact(n);

printf("Factorial of %d is %d\n", n,k);


return 0;
}

Factorial of 5: Operational steps

2 Bulbul Ahamed www.bulbulcse.com


Example 2: Find the Nth Fibonacci Number using Recursion
#include<stdio.h>

int fact(int n); int fibo(int n){


if(n == 1 || n == 2)
int main() return 1;
{ else
int n, k; return fibo(n-1) + fibo(n-2);
printf("Enter the value of n : "); }
scanf("%d", &n);
k = fibo(n);
printf("%dth Fibonacci number is %d\n",n, k);

return 0;
}

Example 3: Print Fibonacci Series using Recursion


#include<stdio.h>

int fact(int n); int fibo(int n){


if(n == 1 || n == 2)
int main() return 1;
{ else
int n,k,i; return fibo(n-1) + fibo(n-2);
}
printf("Enter the value of n : ");
scanf("%d",&n);

for(i=1; i<= n; i++){


k = fibo(i);
printf("%d\t",k);
}
return 0;
}

3 Bulbul Ahamed www.bulbulcse.com


Example 4: Sum of Natural Numbers Using Recursion
#include<stdio.h>
int sum(int num); int sum(int num){
int main() if(num == 0)
{ return 0;
int num, k; else
return num + sum(num-1);
printf("Enter a number : ");
}
scanf("%d", &num);
k = sum(num);
printf("%d", k);
return 0;
}

Example 5: Display series (1, 2, 3, 4, 5 , … … , n)


#include<stdio.h>
int series(int n); int series(int n){
int main(){ int k;
int n; if(n == 0) return 0;
series(n-1);
printf("Enter the last number of a series: "); printf("%d\t",n);
scanf("%d",&n); }
series(n);
return 0;
}

4 Bulbul Ahamed www.bulbulcse.com


Example 6: Display series (n, n-1, … … , 5, 4, 3, 2, 1)
#include<stdio.h>
int series(int n); int series(int n){
int main(){ int k;
int n; if(n == 0) return 0;
printf("%d\t",n);
printf("Enter the last number of a series: "); series(n-1);
scanf("%d",&n); }
series(n);
return 0;
}

Note: In order to prevent infinite recursive call, we need to define proper exit condition in
a recursive function.

Example: C Program to show infinite recursive function


#include<stdio.h>

int main()
{
printf("Hello world");
main();
return 0;
}

In this program, we are calling main() from main() which is recursion. But we haven't
defined any condition for the program to exit. Hence this code will print "Hello world"
infinitely in the output screen.

5 Bulbul Ahamed www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture #08
String in C programming
string: In C programming, array of characters is called a string. A string is terminated by a null
character ‘\0’. Example: "Hello World"
Format Specifier: %s
char: A single symbol. Example: 'A' 'B' '1'
Format Specifier: %c
Declaration of strings: Strings are declared in a similar manner as arrays. Only difference is
that, strings are of char type.
Example: char str[10];

Example: Write a C program to read and write your nickname


Source Code Output
#include<stdio.h>
int main()
{
char str[100];
printf("Enter your nickname: ");
scanf("%s",&str); //string input
printf("Nickname = %s\n",str); //string output
return 0;
}

Initialization of strings: In C, string can be initialized in a number of different ways.


• char str[50] = "BULBUL";
‘\0’ would automatically be inserted at the end in this type of declaration
OR
• char str[ ] = "BULBUL";
OR
• char str[50] = {'B', 'U', 'L', 'B', 'U', 'L', '\0'};
OR
• char str[] = {'B', 'U', 'L', 'B', 'U', 'L', '\0'};

\0 means null character

1 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


Example: Write a C program to display your nickname

Source Code Output


#include<stdio.h>
int main()
{
char str[50] = {'B', 'U', 'L', 'B', 'U', 'L', '\0'};
char str1[50] = "Bulbul";

printf("%s\n",str);
printf("%s\n",str1);
return 0;
}

gets() vs. puts()


▪ gets() : Reads characters from the standard input and stores them as a string.
Syntax for gets():
gets(char_array_variable);
▪ puts() : prints characters from the standard output. Just like printf() function.
Syntax for puts():
puts(char_array_variable);

Example: Write a C program to read & write your full name using gets() and puts()
Source Code Output
#include<stdio.h>
int main()
{
char str[100];
printf("Enter your full name: ");
gets(str);
printf("Full Name: ");
puts(str);
}

2 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


String Length: strlen()

▪ strlen() function in C gives the length of the given string.


▪ strlen() function counts the number of characters in a given string and returns the
integer value.

Example: Write a C program to find the length of a string

Source Code Output


#include<stdio.h>
int main()
{
char st[100] = "Bulbul Ahamed";
char s2[50];
printf("Length of string = %d\n",strlen(st));
gets(s2);
printf("Length of 2nd string = %d\n",strlen(s2));
return 0;
}

String Compare: strcmp()

▪ strcmp() function in C compares two given strings and returns zero if they are same.
Negative value is returned when str1 < str2 and positive value is returned when str1 >
str2.
▪ strcmp() function is case sensitive. i.e, “A” and “a” are treated as different characters.

Example: Write a C program to compare two string whether they are same or not

Source Code Output


#include<stdio.h>
int main()
{
char password[50] = "hello2018";
char conpass[50] = "Hello2018";
if(strcmp(password,conpass) == 0){
printf("Login successful!\n");
}else{
printf("Password didn't match. Plz try again!\n");
}
}
3 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com
Examples
1. Write a C program to print string characters one by one using Loop.
Source Code Source Code
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
char str[100]; char str[100];
int index; int index = 0;
printf("Enter a string:\n"); printf("Enter a string:\n");
gets(str); gets(str);
for(index = 0; str[index] != '\0'; index++) while(str[index] != '\0'){
printf("%c",str[index]); printf("%c",str[index]);
printf("\n"); index++;
} }
}

Output

2. Write a C program to print individual characters of string in reverse order.


Source Code Source Code Source Code
#include<stdio.h> #include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h> #include<string.h>
int main() int main() int main()
{ { {
char str[100]; char str[100]; char str[100];
int i; int i; int i;
gets(str); gets(str); gets(str);
int L = strlen(str) - 1; printf("%s", strrev(str)); int L = strlen(str);
for(i = L; i >= 0; i--) } for(str[L] = '\0'; L > 0; L--)
printf("%c", str[i]); printf("%c", str[L-1]);
} }

Output

4 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


3. Write a C program to print 1st and last character of a string.
Source Code Output
#include<stdio.h>
#include<string.h>
int main(){
char str[100];
int i;
gets(str);
int L = strlen(str);
printf("1st Character: %c\n",str[0]);
printf("last Character: %c\n",str[L-1]);
return 0;
}

4. Write a C program to count alphabets, digits, spaces & special characters in a string.
Uses of isalpha(), isdigit() & isspace()
Source Code Output
#include<stdio.h>
int main(){
char str[100];
int alpha = 0, digit = 0, space=0, special = 0;
gets(str);
int i = 0;
while(str[i] != '\0'){
if(isalpha(str[i]) != 0 ){
alpha++;
} You can also write the following in while:
else if(isdigit(str[i]) != 0){
digit++; while(str[i] != '\0'){
} if(isalpha(str[i])){
else if(isspace(str[i]) != 0){ alpha++;
}
space++;
else if(isdigit(str[i])){
}
digit++;
else{ }
special++; else if(isspace(str[i])){
} space++;
i++; }
} else{
printf("Alphabet(s): %d\n", alpha); special++;
printf("Digit(s): %d\n", digit); }
printf("Space(s): %d\n", space); i++;
printf("Special character(s): %d\n", special); }
return 0;
}

5 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


5. Write a C program to count alphabets, digits, spaces & special characters in a string without
using library functions.
Source Code Output
#include<stdio.h>
int main()
{
char str[100];
int alpha = 0, digit = 0, space = 0, special = 0;
gets(str);
int i = 0;
while(str[i] != '\0'){
if((str[i]>='A' && str[i]<='Z')||(str[i]>='a' && str[i]<='z')){
alpha++;
}
else if(str[i]>='0' && str[i]<='9'){
digit++;
}
else if(str[i] == ' '){
space++;
}
else{
special++;
}
i++;
}
printf("Alphabet(s): %d\n", alpha);
printf("Digit(s): %d\n", digit);
printf("Space(s): %d\n", space);
printf("Special character(s): %d\n", special);
return 0;
}

isalpha() Return Value:

Return Value Remarks

Zero (0) If the parameter isn't an alphabet.

Non zero number If the parameter is an alphabet.

6 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


isdigit() Return value:

Return Value Remarks

Non-zero integer ( x > 0 ) Argument is a numeric character.

Zero (0) Argument is not a numeric character.

isspace() Return value: This function returns a non-zero value(true) if c is a white-space


character else, zero (false).

strlen() Return value: This function returns the length of string passed.
strcmp() Return value: This function return values that are as follows −
• if Return value = 0 then it indicates str1 is equal to str2.
• if Return value < 0 then it indicates str1 is less than str2.
• if Return value > 0 then it indicates str2 is less than str1.

Other necessary library functions:


▪ strcat(): This function concatenates (joins) two strings.
▪ strcpy(): The function copies the string to the another character array.
▪ isalnum(): This function checks whether the passed character is alphanumeric.
▪ isupper(): This function checks whether the passed character is lowercase letter.
▪ islower(): This function checks whether the passed character is an uppercase letter.
▪ tolower(): This function converts uppercase letters to lowercase.
▪ toupper(): This function converts lowercase letters to uppercase.
▪ isxdigit(): This function checks whether character is hexadecimal.
▪ isprint(): This function checks whether character is a printable character.
There are many types of printable characters in C such as:
o digits (0123456789)
o uppercase letters (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
o lowercase letters (abcdefghijklmnopqrstuvwxyz)
o punctuation characters ( !”#$%&'()*+,-./:;?@[\]^_`{ | }~ )
o space ( )
▪ ispunct(): This function checks whether character is a punctuation.
All punctuation characters in C programming are:
! " # $ % & ' ( ) * +, - . / : ; ? @ [ \ ] ^ _ ` { | } ~

Thank You☺

7 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


Structured Programming Language (CSE113)
Lecture # 09
Pointer in C programming

What is a pointer?
A pointer is a variable that stores the address of another variable. Pointers are used in C
program to access the memory and manipulate the address.

Pointer Syntax:
data_type *pointer_variable_name;
Example: int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

Address in C:
If you have a variable var in your program, &var will give you its address in the memory, where
& is commonly called the reference operator. The & operator is also known as “Address of”
Operator.
Source Code Output
#include <stdio.h>
int main()
{
int var = 10;
printf("Value: %d\n", var);
printf("Address: %x\n", &var);
return 0;
}
Note: You may obtain different value of address while using this code.

var Variable Name

10 Value of var
60ff0c Address of var

1 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


Reference operator (&) and Dereference operator (*)
As discussed, & is called reference operator. It gives you the address of a variable.
Likewise, there is another operator that gets you the value from the address, it is called a
dereference operator *.
Below example clearly demonstrates the use of pointers, reference operator and dereference
operator.
Source Code Output
#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %x\n", &c);
printf("Value of c: %d\n\n", c);

pc = &c;
printf("Address of pointer pc: %x\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);

c = 11;
printf("Address of pointer pc: %x\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);

*pc = 2;
printf("Address of c: %x\n", &c);
printf("Value of c: %d\n\n", c);
return 0;
}

Explanation of the program

1. int* pc, c;

Here, a pointer pc and a normal variable c, both of type int, is created.


Since pc and c are not initialized at first, pointer pc points to either no address or a
random address. And, variable c has an address but contains a random garbage value.

2 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


2. c = 22;

This assigns 22 to the variable c, i.e., 22 is stored in the memory location of variable c.
Note that, when printing &c (address of c), we use %x rather than %d since address is
usually expressed as a hexadecimal number. We can also use %u unsigned integer
(always positive).

3. pc = &c;

This assigns the address of variable c to the pointer pc.


You see the value of pc is same as the address of c and the content of pc is 22 as well.

4. c = 11;

This assigns 11 to variable c.


Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as
well.

5. *pc = 2;

This change the value at the memory location pointed by pointer pc to 2.


Since the address of the pointer pc is same as the address of c, value of c is also
changed to 2.

3 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


Another Example
Example of Pointer demonstrating the use of & and *
Source Code Output
#include <stdio.h>
int main()
Value of variable var is: 10
{
Value of variable var is: 10
int *p; Address of variable var is: 0x7fff5ed98c4c
int var = 10; Address of variable var is: 0x7fff5ed98c4c
p = &var; Address of pointer p is: 0x7fff5ed98c50
printf("Value of variable var is: %d\n", var);
printf("Value of variable var is: %d\n", *p);
printf("Address of variable var is: %p\n", &var);
printf("Address of variable var is: %p\n", p);
printf("Address of pointer p is: %p\n", &p);
return 0;
}

Note: %p is used to get the address in hexadecimal number

Common mistakes when working with pointers


Suppose, you want pointer pc to point to the address of c. Then,
int c, *pc;

// Wrong! pc is address whereas,


// c is not an address.
pc = c;

// Wrong! *pc is the value pointed by address whereas,


// &c is an address.
*pc = &c;
// Correct! pc is an address and,
// &c is also an address.
pc = &c;
// Correct! *pc is the value pointed by address and,
// c is also a value (not address).
*pc = c;

4 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


1. Write a C program to swap two numbers using pointers (Call by reference/call by address).
Source Code
#include<stdio.h>
void swap(int *a, int *b);
int main()
{
int a = 20, b = 50;
printf("Before Swapping: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After Swapping: a = %d, b = %d\n",a,b);
return 0;
}
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output

Call by Value vs. Call by Reference


There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. Call by value:
 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter cannot be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.
Note:
 Actual parameter – This is the argument which is used in function call.
 Formal parameter – This is the argument which is used in function definition
2. Call by reference:
 In call by reference method, the address of the variable is passed to the function as
parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used
by both parameters.

5 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com


Example of Call by Value:
#include<stdio.h>
void swap(int a, int b);
int main(){
int m = 22, n = 44;
printf("Before swap:\n m = %d\t n = %d\n", m, n);
swap(m, n);
printf("After swap:\n m = %d\t n = %d\n", m, n);
}
void swap(int a, int b) {
int tmp;
tmp = a;
a = b; Output shows that there are no changes in the values,
b = tmp; though they had been changed inside the function.
}
Output:

Example of Call by Reference:


#include<stdio.h>
void swap(int *a, int *b);
int main(){
int m = 22, n = 44;
printf("Before swap:\n m = %d\t n = %d\n", m, n);
swap(&m, &n);
printf("After swap:\n m = %d\t n = %d\n", m, n);
}
void swap(int *a, int *b) {
int tmp;
tmp = *a;
*a = *b; Output shows that the change has reflected outside
*b = tmp; the function as well, unlike call by value where the
} changes do not reflect outside the function.
Output:

Thank You☺
6 Bulbul Ahamed, Associate Professor, SU www.bulbulcse.com
Structured Programming Language (CSE113)
Lecture # 10
Patterns Display in C Programming
Create a program to display the following cases using for loops:
case 1: case 2: case 3: case 4:
1 1 2 3 4 5 1 5 4 3 2 1
1 2 1 2 3 4 2 1 4 3 2 1
1 2 3 1 2 3 3 2 1 3 2 1
1 2 3 4 1 2 4 3 2 1 2 1
1 2 3 4 5 1 5 4 3 2 1 1

case 5: case 6: case 7: case 8:


1 5 5 5 5 5 * * * * * *
2 2 4 4 4 4 * * * * * *
3 3 3 3 3 3 * * * * * *
4 4 4 4 2 2 * * * * * *
5 5 5 5 5 1 * * * * * *

case 9: case 10: case 11: case 12: Floyd's Triangle


5 1 1 1 1 1 1 1
4 4 2 2 2 2 0 0 2 3
3 3 3 3 3 3 1 1 1 4 5 6
2 2 2 2 4 4 0 0 0 0 7 8 9 10
1 1 1 1 1 5 1 1 1 1 1 11 12 13 14 15

case 13: case 14: case 15: case 16:


1 5 6 7 8 9 Square star patter Rectangular star pattern
2 3 4 5 6 7 ***** **********
3 4 5 3 4 5 * * * *
4 5 6 7 2 3 * * * *
5 6 7 8 9 1 * * * *
***** **********
case 17: Pascal's triangle case 18: Pyramid/triangle using numbers
1 1
1 1 2 1 2
1 2 1 3 2 1 2 3
1 3 3 1 4 3 2 1 2 3 4
1 4 6 4 1 5 4 3 2 1 2 3 4 5
1 5 10 10 5 1 6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7

case 19: Pyramid/triangle using numbers case 20: Pyramid/triangle using *


1 *
1 2 1 * * *
1 2 3 2 1 * * * * *
1 2 3 4 3 2 1 * * * * * * *
1 2 3 4 5 4 3 2 1 * * * * * * * * *
1 2 3 4 5 6 5 4 3 2 1 * * * * * * * * * * *
1 2 3 4 5 6 7 6 5 4 3 2 1 * * * * * * * * * * * * *

…………………………………….

1 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


1. Write C program to print half pyramid using numbers.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <=r; c++){
printf("%d ",c);
}
printf("\n");
}
return 0;
}

2. Write C program to print inverted half pyramid using numbers


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
for(c = 1; c <=r; c++){
printf("%d ",c);
}
printf("\n");
}
return 0;
}

2 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


3. Write C program to print half pyramid using numbers.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = r; c >=1; c--){
printf("%d ",c);
}
printf("\n");
}
return 0;
}

4. Write C program to print inverted half pyramid using numbers.


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
for(c = r; c >=1; c--){
printf("%d ",c);
}
printf("\n");
}
return 0;
}

3 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


5. Write C program to print triangle number pattern.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <=r; c++){
printf("%d ",r);
}
printf("\n");
}
return 0;
}

6. Write C program to print inverted triangle number pattern.


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
for(c = 1; c <=r; c++){
printf("%d ",r);
}
printf("\n");
}
return 0;
}

4 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


7. Write C program to print half pyramid using *
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <=r; c++){
printf("* ");
}
printf("\n");
}
return 0;
}

8. Write C program to print inverted half pyramid using *


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
for(c = 1; c <=r; c++){
printf("* ");
}
printf("\n");
}
return 0;
}

5 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


9. Write C program to print triangle number pattern.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <=r; c++){
printf("%d ",t-r+1);
}
printf("\n");
}
return 0;
}

10. Write C program to print inverted triangle number pattern.


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
for(c = 1; c <=r; c++){
printf("%d ",t-r+1);
}
printf("\n");
}
return 0;
}

6 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


11. Write C program to print triangle number pattern using 0 and 1.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <= r; c++){
if(r%2 == 1) printf("1 ");
else printf("0 ");
}
printf("\n");
}
return 0;
}

12. Write C program to print Floyd's Triangle.


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
int count = 1;
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <= r; c++){
printf("%d ",count);
count++;
}
printf("\n");
}
return 0;
}

7 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


13. Write C program to print triangle number pattern.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
int temp;
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
temp = r;
for(c = 1; c <= r; c++){
printf("%d ",temp);
temp++;
}
printf("\n");
}
return 0;
}

14. Write C program to print inverted triangle number pattern.


Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
int temp;
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = t; r >= 1; r--){
temp = r;
for(c = 1; c <= r; c++){
printf("%d ",temp);
temp++;
}
printf("\n");
}
return 0;
}

8 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com


15. Write C program to print hollow square star pattern.
Source Code Output
#include<stdio.h>
int main()
{
int t,r,c; //t=totalRows,r=rows,c=columns
printf("No. of rows you want to display: ");
scanf("%d",&t);
for(r = 1; r <= t; r++){
for(c = 1; c <= t; c++){
if(r == 1 || c == 1 || r == t || c == t)
printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}

17. Write C program to print Pascal's triangle.


Source Code Output
#include<stdio.h>
long factorial(int n);
int main()
{
int n,rows,cols,result,space;
printf("No of rows you want to display: ");
scanf("%d",&n);
for(rows = 0; rows < n; rows++) {
for(space = 0; space <= (n-rows-2); space++) {
printf(" ");
}
for(cols = 0; cols <= rows; cols++){
result = factorial(rows)/(factorial(cols)*factorial(rows-cols));
printf("%d ",result);
}
printf("\n");
}
return 0;
}
long factorial(int n){
if(n == 0) return 1;
return n*factorial(n-1);
}
…………….……….

9 Bulbul Ahamed, Associate Professor of CSE, SU www.bulbulcse.com

Powered by TCPDF (www.tcpdf.org)

You might also like