Aop Unit-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

UNIT-2

C programming

 VARIABLE:
In C programming, variables are used to store data that can be manipulated and
processed by the program. Each variable has a specific data type, which determines the
size and format of the data it can hold. Variables must be declared before they can be
used, specifying their data type and optionally, an initial value.

Syntax for declaring and initializing a variable in C:


data_type variable_name = value;

Types of Variables in C:
 Local variables
 Global variables
 Static variables
 External variables
 Automatic variables

1. Local Variables:
Variables that are declared inside the functions with the keyword local are called local variables.
The scope of local variable is within the defined function only. We cannot use local variable
outside the function.Once the function is exited, the local variable is destroyed and its memory
is released.
Example:
#include<stdio.h>
void main()
{
Int a=5; // local variable
printf(“value of the local variable a is = %d”,a);
}
Output:
value of the local variable a is = 5.

2. Global Variables:
Variables declared outside the functions with the keyword global are called global variables. Global
variables can be accessed by multiple functions defined in the program. The scope of the global
variable is the entire program.
Example:
#include<stdio.h>
float pi = 3.14 //global variable
int circle()
{
Int r=5; // local variable
double area;
area = pi*r*r;
return area;
}
void main()
{
printf(“area of the circle is = %d”,circle());
}

Output:
area of the circle is = 78.
3. Static Variables:
Variables declared with a keyword static are static variables, whose lifetime is throughout the
program run time. Its scope depends on the area of its declaration.
Example:
#include<stdio.h>
Int calc()
{
static int sum = 0; //static variable
sum++;
return sum;
}
void main()
{
Printf( “sum = %d \n”,calc());
Printf( “sum = %d \n”,calc());
}
Output:
Sum = 1
Sum = 2

4. External Variables:
External variables share the variables among the multiple C files. The extern keyword is used in the
C programming language to declare external variables.It is not necessary to initialize the variable at
the time of its declaration.
Example:
Declare external variables in a file with .h a header file.
extern int x =10, y=20;
Now,
access external variables x and y to perform addition operations by including the header file.
#include<demo.h>
#include<stdio.h>
void main()
{
Int add;
Printf(“the value of x is %d \n”, x);
Printf(“the value of y is %d \n”, y);
add = x+y;
printf(“x+y = %d \n”,add);
}
Output:
The value of x is 10
The value of y is 20
X+y = 30

5. Automatic Variables:
All variables declared in C programming are automatic by default. Variables declared with auto
keywords are known as automatic variables. The variables declared inside the block of functions
are automatic variables by default.
Example:
#include<stdio.h>
void main()
{
Int a = 10; //automatic variable by default
auto int b = 20; //explicitly declaring automatic variable.
printf(“a = %d \n”,a);
printf(“b = %d \n”,b);
}
Output:
a = 10
b = 20

INPUT AND OUTPUT:


 Prinf() :
The printf() function is used to produce formatted outputs or standard output based on a
format specification. The output data and the format specification string serves as the
parameters of the printf() function.

Syntax:
Printf() (formt-specifiers, variable a, variable b, - - - -);

Example:

#include <stdio.h>

int main() {
int num = 10;
float f = 3.14;
char ch = 'A';

printf("Integer: %d\n", num);


printf("Float: %.2f\n", f);
printf("Character: %c\n", ch);

return 0;
}

 Scanf():
The scanf() function is utilized for accepting formatted input or standard input, there by
providing the printf() function with multiple conversion options.

Syntax:
scanf() (formt-specifiers, variable a, variable b, - - - -);
example:

#include <stdio.h>

int main() {
int num;
float f;

printf("Enter an integer: ");


scanf("%d", &num);

printf("Enter a float: ");


scanf("%f", &f);

printf("Integer: %d\n", num);


printf("Float: %.2f\n", f);

return 0;
}

CONTROL FLOW:
Control flow in a C program determines the order in which statements are executed based on
certain conditions
1.If statement: The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}

Example:
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15)
{
printf("10 is greater than 15");
}
printf("I am Not in if");
}
2.If-else statement: The if-else statement allows you to execute one block of code if the
condition is true and another block if it is false.

Syntax:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Example:
int x = 3;
if (x % 2 == 0) {
printf("x is even\n");
} else {
printf("x is odd\n");
}

3.Nested if statement: A nested if in C is an if statement that is the target of another if


statement. Nested if statements mean an if statement inside another if statement.
Syntax :
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

Example: #include <stdio.h>

int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}

return 0;
}

4.If-else-if statement: The if else if statements are used when the user has to decide
among multiple options. The C if statements are executed from the top down. As soon
as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed. if-else-if ladder is similar to the
switch statement.

Syntax :
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
5.Switch statement: The switch statement allows you to select one of many blocks of code to
be executed based on the value of an expression. The switch block consists of cases to be
executed based on the value of the switch variable.

Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
default:
// code to be executed if expression doesn't match any case
}

Example:
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent\n");
break;
case 'B':
printf("Good\n");
break;
case 'C':
printf("Fair\n");
break;
default:
printf("Invalid grade\n");
}

LOOPING STATEMENTS:-

1. for loop: The for loop allows us to repeatedly execute a block of code a specified number of
times.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
#include <stdio.h>

// Driver code
int main()
{
int i = 0;

for (i = 1; i <= 10; i++)


{
printf( "Hello World\n");
}
return 0;
}
2. while loop: The while loop repeatedly executes a block of code as long as a specified condition
is true. It checks the condition first, then execute the statements.While loop does not depend
upon the number of iterations.
Syntax:
while (condition) {
// code to be executed
}

Example:
#include <stdio.h>
Int void()
{
int i = 0;
while (i < 5) {
printf("Iteration %d\n", i);
i++;
}
}
3. do-while loop: The do-while loop is similar to the while loop, except that it always executes the
block of code at least once, even if the condition is false. In this loop it executes statements first
and then checks condition.

Syntax:
do {
// code to be executed
} while (condition);

Example:
#include<stdio.h>
Int void()
{
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
} while (i < 5);
}
Branching Statements:

1.Break statement:
The break statement is used to terminate the innermost loop or switch statement in which it
appears.When the break statement is encountered, the control exits the loop or switch statement,
and the program continue with the next statement after the loop or switch.

Syntax:
Break;

Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}

2.Continue statement:
The continue statement is used to skip the rest of the statements inside a loop for the current
iteration and continue with the next iteration of the loop.
When the continue statement is encountered, the control goes back to the beginning of the loop for
the next iteration.

Syntax:
Continue;
Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
printf("%d ", i);
}
4. goto Statement:

In C programming, goto is a keyword that allows you to transfer control to a labeled statement within
the same function.

Syntax:
goto label;
label: statement;
example:
#include <stdio.h>
int main() {
int i = 0;
start:
printf("i = %d\n", i);
i++;
if (i < 5)
goto start;
return 0;
}

Disadvantages of Using goto Statement


 The use of the goto statement is highly discouraged as it makes the program logic very
complex.
 The use of goto makes tracing the flow of the program very difficult.
 The use of goto makes the task of analyzing and verifying the correctness of programs
(particularly those involving loops) very difficult.
 The use of goto can be simply avoided by using break and continue statements.

POINTERS AND ARRAYS:


POINTERS AND ADDRESS:

 Pointer: A pointer is a variable that stores the memory address of another variable. It is
declared using the * operator. For example, int *ptr; declares a pointer ptr that can point to
an integer variable.
 Address: Every variable in C is stored in a specific memory location, which has a unique
address. The address of a variable can be obtained using the & operator. For example,
&variable gives the address of variables.

Assigning Address to Pointer: You can assign the address of a variable to a pointer using the
& operator. For example, ptr = &variable; assigns the address of variable to the pointer ptr.

Accessing Value at Address: You can access the value stored at a memory address using the
dereference operator *. For example, int value = *ptr; assigns the value at the address
pointed to by ptr to the variable value.

Null Pointer: A null pointer is a pointer that does not point to any valid memory address. It
is often used to indicate that the pointer is not currently pointing to a valid object.

Example:
#include <stdio.h>

int main() {
int num = 10; // Declares an integer variable num and initializes it to 10
int *ptr; // Declares a pointer variable ptr that can store the address of an integer

ptr = &num; // Assigns the address of num to ptr

printf("Address of num: %p\n", &num);


printf("Value of num: %d\n", num);
printf("Value of num using pointer: %d\n", *ptr);

return 0;
}

Pointers and function arguments:


In C, pointers are often used in function arguments to allow the function to modify the original values
of variables or to work with large data structures efficiently. When you pass a variable to a function by
pointer, you are passing the memory address of the variable, allowing the function to access and
modify the value stored at that address.

Example:
#include <stdio.h>

// Function prototype that takes a pointer to an integer as an argument


void increment(int *numPtr) {
(*numPtr)++; // Increment the value at the memory address stored in numPtr
}

int main() {
int num = 10;
printf("Before increment: %d\n", num);

// Pass the address of num to the increment function


increment(&num);

printf("After increment: %d\n", num);

return 0;
}

Multidimensional array:
In C programming, a multidimensional array is an array that holds arrays as its elements. This allows
you to create a table-like structure with rows and columns.
Syntax:
data_type array_name[size1][size2]....[sizeN];
 data_type: Type of data to be stored in the array.
 array_name: Name of the array.
 size1, size2,…, sizeN: Size of each dimension.

Examples:

Two dimensional array: int two_d[10][20];

Three dimensional array: int three_d[10][20][30];

The most commonly used forms of the multidimensional array are:


1. Two Dimensional Array
2. Three Dimensional Array

Two-Dimensional Array :
The Two-dimensional array is nothing but a table with rows and columns. A two-dimensional array can
be expressed as a contiguous and tabular block in memory where the data can be stored in a table
structure.
Syntax: datatype arrayName [ rowSize ] [ columnSize ];
Example:
int x[3][4];

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


for(int j = 0; j < 4; j++){
x[i][j] = i + j;
}
}

Three Dimensional Array:


A 3D array is a collection of 2D arrays. It is specified by using three subscripts:Block size, row size and
column size. More dimensions in an array means more data can be stored in that array.

Syntax: data_type array_name[block_size][row_size][column_size];


Example:
int x[2][3][4];

for (int i=0; i<2; i++) {


for (int j=0; j<3; j++) {
for (int k=0; k<4; k++) {
x[i][j][k] = (some_value);
}
}
}

Initialization of pointer arrays:

 In C programming, an array of pointers is an array where each element is a pointer to another


data type.
 This can be useful for storing arrays of strings, creating arrays of structures, or implementing
dynamic arrays.
 Initializing an array of pointers involves assigning the memory addresses of other variables or
objects to the elements of the array
 Keep in mind that when you initialize an array of pointers, each pointer in the array should
point to a valid memory location, either to a dynamically allocated memory or to an existing
variable.

Syntax for initializing an array of pointers:


<type> *array_name[size] = {pointer1, pointer2, ..., pointerN};

Example:
#include <stdio.h>
int main() {
int num1 = 10, num2 = 20, num3 = 30;
// Array of pointers to integers
int *ptrArray[3] = {&num1, &num2, &num3};

// Accessing values using the array of pointers


for (int i = 0; i < 3; i++) {
printf("Value at ptrArray[%d]: %d\n", i, *ptrArray[i]);
}

return 0;
}

Difference between Pointers and Array:

Command line arguments:


In C programming, command line arguments allow you to pass arguments to a program when it is
run from the command line.
The most important function of C is the main() function. It is mostly defined with a return type of
int and without parameters.
int main() {
...
}
syntax for the main function with command line arguments:

int main(int argc, char *argv[])

 argc (argument count) is an integer that represents the number of command line
arguments passed to the program, including the name of the program itself.
 argv (argument vector) is an array of strings (char *argv[]) where each element is a
pointer to a string that represents a command line argument.

Example:

#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Number of arguments: %d\n", argc);

for (int i = 0; i <argc; i++) {


printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}

Output:
Number of arguments: 4
Argument 0: ./a.out
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

You might also like