SlideShare a Scribd company logo
1 of 81
#include <stdio.h>
int main() { /* my first program in C */
printf("Hello, World! n");
return 0;
}
Various parts of the above program −
• The first line of the program #include <stdio.h> is a preprocessor command, which tells a
C compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
Structure of C Program
Data Types in C
• Data types refer to the type of data that we are using in a C program.
• we must specify the type of data that is in use, so that the compiler knows exactly what
type of data it must expect from the given program.
Types of Data Types in C
Data Type Example of Data Type
Basic Data Type Floating-point, integer, double, character.
Derived Data Type Union, structure, array, etc.
Enumerated Data Type Enums
Void Data Type Empty Value
Bool Type True or False
Primary Data Types in C
Here are the five primitive or primary data types:
1. Integer (int) – We use these for storing various whole numbers, such as 5, 8, 67, 2390,
etc.
2. Character (char)– It refers to all ASCII character sets as well as the single alphabets, such
as ‘x’, ‘Y’, etc.
3. Double (double)– These include all large types of numeric values that do not come under
either floating-point data type or integer data type. Visit Double Data Type in C to know
more.
4. Floating-point(float) – These refer to all the real number values or decimal points, such as
40.1, 820.673, 5.9, etc.
5. Void (void) – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
The size of every data type gets defined in bytes/ bits. Also, these data types are capable of
holding a very wide range of values.
Keyword
Used
Data Type Size
int Integer 2 bytes or 16 bits: 16-bit Machine
4 bytes or 32 bits: 32-bit Machine
float Floating-point 32 bits or 4 bytes.
char Character 8 bits or 1 byte
double Double 64 bits or 8 bytes
• 1 bit for the sake of sign representation,
• exponent uses 11 bits,
• remaining 52 bits for the mantissa
void Void 0 bytes
Data Type Modifiers
• short
• long
• unsigned
• signed
Range of Values of C Data Type
Data Type Format
Specifier
Minimal Range Typical Bit Size
unsigned char %c 0 to 255 8
char %c -127 to 127 8
signed char %c -127 to 127 8
int %d, %i -32,767 to 32,767 16 or 32
unsigned int %u 0 to 65,535 16 or 32
signed int %d, %i Same as int Same as int
16 or 32
short int %hd -32,767 to 32,767 16
unsigned short int %hu 0 to 65,535 16
signed short int %hd Same as short int 16
long int %ld, %li -2,147,483,647 to 2,147,483,647 32
long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the C99 standard) 64
signed long int %ld, %li Same as long int 32
unsigned long int %lu 0 to 4,294,967,295 32
unsigned long
long int
%llu 264 – 1 (It will be added by the C99 standard) 64
float %f 1E-37 to 1E+37 along with six digits of the precisions here 32
double %lf 1E-37 to 1E+37 along with six digits of the precisions here 64
long double %Lf 1E-37 to 1E+37 along with six digits of the precisions here 80
Derived data types
The derived data types to represent multiple values as well as single values in a program.
Types of Derived Data Types in C
The C language supports a few derived data types. These are:
1. Arrays – The array basically refers to a sequence (ordered sequence) of a finite number
of data items from the same data type sharing one common name.
2. Function – A Function in C refers to a self-contained block of single or multiple
statements. It has its own specified name.
3. Pointers – The Pointers in C language refer to some special form of variables that one
can use for holding other variables’ addresses.
4. Unions – The unions are very similar to the structures. But here, the memory that we
allocate to the largest data type gets reused for all the other types present in the group.
5. Structures – A collection of various different types of data type items that get stored in a
contagious type of memory allocation is known as structure in C.
Input-Output Statements
The printf() is a library function to send formatted output to the screen. The function prints
the string inside quotations.
scanf() is one of the commonly used function to take input from the user.
The scanf() function reads formatted input from the standard input such as keyboards.
#include <stdio.h>
int main()
{
int a,b;
printf("Enter integer values for a & b: ");
scanf("%d%d", &a, &b);
If(a>b)
printf("%d is big", a);
else
printf("%d is big", b);
return 0;
}
Start
Input a & b
Display a
Display b
a>b
Stop
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
%
remainder after division (modulo
division)
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc
on numerical values (constants and variables).
C Increment and Decrement Operators
C programming has two operators
• increment ++
• decrement --
Increment ++ increases the value by 1
whereas decrement -- decreases the value by 1.
These two operators are unary operators, meaning they only
operate on a single operand.
#include <stdio.h>
int main() {
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d n", ++a);
printf("--b = %d n", --b);
printf("++c = %f n", ++c);
printf("--d = %f n", --d);
return 0;
}
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
#include <stdio.h>
int main(){
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d n", ++a);
printf("--b = %d n", --b);
printf("c++ = %f n", c++);
printf("d-- = %f n", d--);
printf("c++ = %f n", c++);
printf("d-- = %f n", d--);
return 0;
}
Output:
++a = 11
--b = 99
c++ = 10.500000
d-- = 100.500000
c++ = 11.500000
d-- = 99.500000
Operator Example Same as
= a = b a = b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
C Assignment Operators
An assignment operator is used for assigning a value to a variable.
The most common assignment operator is =
// Working of assignment operators
#include <stdio.h>
int main() {
int a = 5, c;
c = a; // c is 5 printf("c = %dn", c);
c += a; // c is 10 printf("c = %dn", c);
c -= a; // c is 5 printf("c = %dn", c);
c *= a; // c is 25 printf("c = %dn", c);
c /= a; // c is 5 printf("c = %dn", c);
c %= a; // c = 0 printf("c = %dn", c);
return 0;
}
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
Operator Meaning Example
&&
Logical AND. True only if all
operands are true
If c = 5 and d = 2 then,
expression ((c==5) &&
(d>5)) equals to 0.
||
Logical OR. True only if
either one operand is true
If c = 5 and d = 2 then,
expression ((c==5) ||
(d>5)) equals to 1.
!
Logical NOT. True only if the
operand is 0
If c = 5 then, expression
!(c==5) equals to 0.
C 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.
Decision making statement
Decision making structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed
if the condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.
Decision making with if statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
#include <stdio.h>
int main () {
int a = 10;
if( a < 20 ) {
printf("a is less than 20n" );
}
printf("value of a is : %dn", a);
return 0;
}
if...else Statement
The if statement may have an optional else block.
Syntax: if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
How if...else statement works?
• If the test expression is evaluated to true,
• statements inside the body of if are executed.
• statements inside the body of else are skipped from execution.
• If the test expression is evaluated to false,
• statements inside the body of else are executed
• statements inside the body of if are skipped from execution.
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
if...else if or if...else Ladder
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
The if...else ladder allows you to check between multiple test expressions and execute
different statements.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
} . .
else {
// statement(s)
}
Syntax of if...else Ladder
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
} //checks if number1 is greater than number2.
else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
} //checks if both test expressions are false
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Nested if...else
It is possible to include an if...else statement inside the body of another if...else statement.
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2) {
if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable.
Here, We can define various statements in the multiple cases for the different values of a
single variable.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Rules for switch statement in C language
1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched case.
Valid Switch Invalid Switch Valid Case Invalid Case
switch(x) switch(f) case 3; case 2.5;
switch(x>y) switch(x+2.5) case 'a'; case x;
switch(a+b-2) case 1+2; case x+2;
switch(func(x,y)) case 'x'>'y'; case 1,2,3;
int x,y,z;
char a,b;
float f;
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
} enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}
}
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equal to 10n");
case 50:
printf("number is equal to 50n");
case 100:
printf("number is equal to 100n");
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
Nested switch case statement
We can use as many switch statement as we want inside a switch statement. Such type of
statements is called nested switch case statements.
#include <stdio.h>
int main () {
int i = 10;
int j = 20;
switch(i) {
case 10:
printf("the value of i evaluated in outer switch: %dn",i);
case 20:
switch(j) {
case 20:
printf("The value of j evaluated in nested switch: %dn",j);
}
}
printf("Exact value of i is : %dn", i );
printf("Exact value of j is : %dn", j );
return 0;
}
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20
In programming, loops are used to
repeat a block of code until a specified
condition is met.
C programming has three types of
loops.
1.while loop
2.do...while loop
3.for loop
A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
Syntax: while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any nonzero value.
The loop iterates while the condition is true.
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
while( a < 20 ) /* while loop execution */
{
printf("value of a: %dn", a);
a++;
}
return 0;
}
#include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
do...while
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming checks its condition at the bottom of the loop.
Syntax: do {
statement(s);
} while( condition );
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
/* do loop execution */
do {
printf("value of a: %dn", a);
a = a + 1;
}while( a < 20 );
return 0;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include <stdio.h>
int main()
{
double number, sum = 0; // the body of the loop is executed at least once
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
} while(number != 0.0);
printf("Sum = %.4f",sum);
return 0;
}
Enter a number: 6
Enter a number: 2
Enter a number: 0
Sum = 8.0000
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice, dummy;
do{
printf("n1. Print Hellon2. Print Javatpointn3. Exitn");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("Hello");
break;
case 2: printf("Javatpoint");
break;
case 3: exit(0);
break;
default: printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
0
please enter valid choice
do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
3
For loop
A for loop is a more efficient loop structure in ‘C’ programming.
• The initial value of the for loop is performed only once.
• The condition is a Boolean expression that tests and compares the counter to a
fixed value after each iteration, stopping the for loop when false is returned.
• The incrementation/decrementation increases (or decreases) the counter by a set
value.
Syntax :
for (initial value; condition; incrementation or decrementation )
{
statements;
}
#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++)
{
printf("%dn",number);
}
return 0;
}
for (x = 0, y = num; x < y; i++, y--)
{
statements;
}
int i=0; int max = 10;
for (; i < max; i++)
{
printf("%dn", i);
}
Other methods
Nested Loops in C
C supports nesting of loops in C.
Nesting of loops is the feature in C that allows the looping of statements inside
another loop.
Syntax of Nested loop
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop
or 'do-while' loop.
Nested for loop
The nested for loop means any type of loop which is defined inside the 'for' loop.
Syntax:
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}
Nested while loop
The nested while loop means any type of loop which is defined inside the 'while' loop.
Syntax:
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
#include <stdio.h>
int main()
{
int rows;
int columns;
int k=1;
printf("Enter the number of rows :"); .
scanf("%d",&rows);
printf("nEnter the number of columns :");
scanf("%d",&columns);
int a[rows][columns];
int i=1;
while(i<=rows)
{
int j=1;
while(j<=columns)
{
printf("%dt",k);
k++;
j++;
}
i++;
printf("n");
}
}
Nested do..while loop
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
Syntax:
do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);
#include <stdio.h>
int main()
{
int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("n");
i++;
}while(i<=4);
}
C Array
• An array is defined as the collection of similar type of data items stored at contiguous
memory locations.
• Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
• It also has the capability to store the collection of derived data types, such as pointers,
structure, etc.
• The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
• By using the array, we can access the elements easily.
Properties of Array
1. Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
2. Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.
Declaration of C Array
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[array_size];
Example:
int marks[5];
• Arrays have 0 as the first index, not 1.
• In this example, mark[0] is the first element.
• If the size of an array is n, to access the last element, the n-1 index is used.
• Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1] will
be 2122d. Similarly, the address of mark[2] will be 2124d and so on.
• This is because the size of a int is 2 bytes.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element.
We can initialize each element of the array by using the index.
Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
for(i=0;i<5;i++)
{
printf("%d n",marks[i]);
}
return 0;
}
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size.
So it may also be written as the following code.
int marks[]={20,30,40,50,60};
Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Change Value of Array elements
int mark[5] = {19, 10, 8, 17, 9}
// make the value of the third element to -1
mark[2] = -1;
// make the value of the fifth element to 0
mark[4] = 0;
#include <stdio.h>
int main() {
int mark[5] = {19, 10, 8, 17, 9};
mark[2] = -1;
mark[4] = 0;
for(int i = 0; i < 5; i++) {
printf("Array values are: %dn", mark[i]);
}
return 0;
}
Array values are: 19
Array values are: 10
Array values are: -1
Array values are: 17
Array values are: 0
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60}; //Declaration with Initialization
for(i=0;i<5;i++)
{
printf("%d n",marks[i]);
}
return 0;
}
#include <stdio.h>
int main ()
{
int a[5];
int n,i,sum=0;
printf( "Enter the size of arrayt");
scanf("%d",&n);
printf( "Enter the elements of arrayn");
for (i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
for (i = 0; i < n; ++i)
{
sum += a[i];
printf( "Sum of Array elements is: %dn ", sum);
}
printf( "nSum of Array elements is: %d ", sum);
}
#include <stdio.h>
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50};
printf( "Sum of Array elements is: %d ", getsum( balance, 5 ));
return 0;
}
int getsum(int arr[], int size)
{
int i;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
return sum;
}
One Dimensional Array
A one-dimensional array has one subscript. One Dimensional (1D) array is an array
which is represented either in one row or in one column.
The one-dimensional arrays are known as vectors.
In other words, it can be represented as in a single dimension-width or height as
shown in the below figure:
Two Dimensional Array
Two Dimensional (2D) array is a fixed-length, homogeneous data type, row and column-
based data structure which is used to store similar data type element in a row and column-
based structure.
A two-dimensional array is referred to as a matrix or a table.
A matrix has two subscripts, one denotes the row and another denotes the column.
In other words, a two-dimensional array is an array of a one-dimensional array.
The general syntax for declaration of a 2D array is given below:
data_type array_name[row] [column];
where data_type specifies the data type of the array. array_name specifies the name of the
array, row specifies the number of rows in the array and column specifies the number of
columns in the array.
The total number of elements that can be stored in a two array can be calculated by
multiplying the size of all the dimensions.
#include <stdio.h>
int main() {
float a[2][2], b[2][2], result[2][2];
printf("Enter elements of 1st matrixn");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
printf("Enter elements of 2nd matrixn");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
result[i][j] = a[i][j] + b[i][j];
}
printf("nSum Of Matrix:");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
printf("%.1ft", result[i][j]);
if (j == 1) printf("n");
}
return 0;
}
Enter elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Structure
• Arrays allow to define type of variables that can hold several data items of the
same kind.
• structure is another user defined data type available in C that allows to combine
data items of different kinds.
• Structures are used to represent a record.
Defining a Structure
To define a structure, you must use the struct statement.
The struct statement defines a new data type, with more than one member.
The format of the struct statement is as follows −
Syntax:
struct [structure tag]
{
member definition; or
member definition; ...
member definition;
} [one or more structure variables];
datatype member;
struct [tagname] {
datatype member;
datatype member ;
};
1. struct is a keyword.
2. tagname specifies the name of structure.
3. member, member specifies the data items that make up structure.
Example: 1
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book1,book2;
Example: 2
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
Int main() {
struct Books book1,book2;
}
Example: 3
typedef struct Distance {
int feet;
float inch;
} distances;
int main()
{
distances d1, d2;
}
1. By . (member or dot operator)
2. By -> (structure pointer operator)
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
printf( "Book 1 author : %sn", Book1.author);
printf( "Book 1 subject : %sn", Book1.subject);
printf( "Book 1 book_id : %dn", Book1.book_id);
printf( "Book 2 author : %sn", Book2.author);
printf( "Book 2 subject : %sn", Book2.subject);
printf( "Book 2 book_id : %dn", Book2.book_id);
return 0;
}
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
#include <stdio.h>
#include <string.h>
struct Books{
char title[50];
char author[50];
int id;}book1, book2;
void printBook(struct Books book);
void main(){
strcpy(book1.title,"C Langauage");
strcpy(book1.author,"Bell");
book1.id=1234;
strcpy(book2.title,"Java Programming");
strcpy(book2.author,"Sun solaris");
book2.id=2345;
printBook(book1);
printBook(book2);
}
void printBook(struct Books book)
{
printf("Book1:%sn",book.title);
printf("Author:%sn",book.author);
printf("id:%dnn",book.id);
}
copying structure variables
A structure is treated like a value that occupies a given number of bytes.
struct PairOfInts
{
int a;
int b;
};
PairOfInts x, y;
x.a = 20;
x.b = 40;
y = x;
create two variables, x and y, of type PairOfInts. The next two statements initialize structure x.
The last statement,
y = x;
copies the structured value in x into y. You get an exact copy.
Structure copies are done the same way no matter how you indicate the structures.
PairOfInts *p, *q;
p = new PairOfInts;
q = new PairOfInts;
p->a = 20;
p->b = 40;
*q = *p;
#include <stdio.h>
struct class{ int number; char name[20];
float marks;};
main(){
int x;
struct class student1 = {001,"Hari",172.50};
struct class student2 = {002,"Bobby", 167.00};
struct class student3; student3 = student2;
x = ((student3.number == student2.number) && (student3.marks == student2.marks)) ? 1 : 0;
if(x == 1){
printf("nstudent2 and student3 are samenn");
printf("%d %s %fn", student3.number, student3.name, student3.marks);
}
else
printf("nstudent2 and student3 are differentnn");
}
comparing structure variables
Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any other
variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable.
To find the address of a structure variable, place the '&'; operator before the structure's
name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the →
operator as follows −
struct_pointer->title;
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book1, Book2 ;
void printBook( struct Books *book );
int main( ) {
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book ) {
printf( "Book title : %sn", book->title);
printf( "Book author : %sn", book->author);
printf( "Book subject : %sn", book->subject);
printf( "Book book_id : %dn", book->book_id);
}
Nested Structures
struct student_college_detail {
int college_id;
char college_name[50];
};
struct office_detail {
int cl_id;
char cl_name[50];
};
struct student_detail {
int id;
char name[20];
float percentage;
struct student_college_detail clg_data;
struct office_detail off_data;
} stu_data,stu_data1;
void data(struct student_detail stud);
void main() {
struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Anna University",121,"Rajesh"};
struct student_detail stu_data1 = {2, "Poorvik", 94.0, 6458,"Reva University",654,"Sarvesh"};
data(stu_data);
data(stu_data1);
}
void data(struct student_detail stud){
printf(" Id is : %d n", stud.id);
printf(" Name is : %s n", stud.name);
printf(" Percentage is : %f n", stud.percentage);
printf(" College Id is : %d n", stud.clg_data.college_id);
printf(" College Name is : %s n", stud.clg_data.college_name);
printf(" College Id is : %d n", stud.off_data.cl_id);
printf(" College Name is : %s nnn", stud.off_data.cl_name);
}
A union
• is a special data type available in C that allows to store different data types in the same
memory location.
• User can define a union with many members, but only one member can contain a value
at any given time.
• Unions provide an efficient way of using the same memory location for multiple-
purpose.
The format of the union statement is as follows −
union [union tag] {
member definition;
member definition; ...
member definition;
} [one or more union variables];
• The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition.
• At the end of the union's definition, before the final semicolon, you can specify one or
more union variables but it is optional.
union Data {
int i;
float f;
char str[20];
} data;
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data :
%dn", sizeof(data));
return 0;
}
Output: Memory size occupied by data : 20
Accessing Union Members
• To access any member of a union, we use the member access operator (.).
• The member access operator is coded as a period between the union variable name and
the union member that we wish to access.
• You would use the keyword union to define variables of union type.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
return 0;
}
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
#include <stdio.h>
struct store
{
double price;
union
{
struct{
char *title;
char *author;
int number_pages;
} book;
struct {
int color;
int size;
char *design;
} shirt;
}item;
} s;
int main() {
s.item.book.title = "C programming";
s.item.book.author = "John";
s.item.book.number_pages = 189;
s.item.shirt.design = "white";
printf( "Book 1 author : %sn", s.item.book.title);
printf( "Book 1 author : %sn", s.item.book.author);
printf( "Book 1 author : %dn", s.item.book.number_pages);
printf( "Book 1 author : %sn", s.item.shirt.design);
return 0;
}
Struct Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, the compiler
allocates memory to each variables member. The size of a
structure is equal or greater to the sum of the sizes of each
data member.
When the variable is declared in the union, the compiler
allocates memory to the largest size variable member. The
size of a union is equal to the size of its largest data member
size.
Each variable member occupied a unique memory space. Variables members share the memory space of the largest
size variable.
Changing the value of a member will not affect other variables
members.
Changing the value of one member will also affect other
variables members.
Each variable member will be assessed at a time. Only one variable member will be assessed at a time.
We can initialize multiple variables of a structure at a time. In union, only the first data member can be initialized.
All variable members store some value at any point in the
program.
Exactly only one data member stores a value at any particular
instance in the program.
The structure allows initializing multiple variable members at
once.
Union allows initializing only one variable member at once.
It is used to store different data type values. It is used for storing one at a time from different data type
values.
It allows accessing and retrieving any data member at a time. It allows accessing and retrieving any one data member at a
time.
Difference between Structure and Union
Advantages of Structure
•Structure stores more than one data type of the same object together.
•It is helpful when you want to store data of different or similar data types such as name, address, phone, etc.,
•It makes it very easy to maintain the entire record as we represent complete records using a single name.
•The structure allows passing a whole set of records to any function with the help of a single parameter.
•An array of structures can also be created to store multiple data of similar data types.
Disadvantages of Structure
•If the complexity of the project goes increases, it becomes hard to manage all your data members.
•Making changes to one data structure in a program makes it necessary to change at several other places.
So it becomes difficult to track all changes.
•The structure requires more storage space as it allocates memory to all the data members, & even it is
slower.
•The structure takes more storage space as it gives memory to all the different data members, whereas union
takes only the memory size required by the largest data size parameters, and the same memory is shared
with other data members.
Advantages of Union
•Union takes less memory space as compared to the structure.
•Only the largest size data member can be directly accessed while using a union.
•It is used when you want to use less (same) memory for different data members.
•It allocates memory size to all its data members to the size of its largest data member.
Disadvantages of Union
•It allows access to only one data member at a time.
•Union allocates one single common memory space to all its data members, which are shared between all of
them.
•Not all the union data members are initialized, and they are used by interchanging values at a time.
C Pointers
• The pointer in C language is a variable which stores the address of another variable.
• This variable can be of type int, char, array, function, or any other pointer.
• The size of the pointer depends on the architecture.
• However, in 32-bit architecture the size of a pointer is 2 byte.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol).
It is also known as indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Example:
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx

More Related Content

Similar to the refernce of programming C notes ppt.pptx

Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSivakumar R D .
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02CIMAP
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures Pradipta Mishra
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structuresPradipta Mishra
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 

Similar to the refernce of programming C notes ppt.pptx (20)

First c program
First c programFirst c program
First c program
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Ch02
Ch02Ch02
Ch02
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C Basics
C BasicsC Basics
C Basics
 
C Programming
C ProgrammingC Programming
C Programming
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Unit 2- Module 2.pptx
Unit 2- Module 2.pptxUnit 2- Module 2.pptx
Unit 2- Module 2.pptx
 
C tutorial
C tutorialC tutorial
C tutorial
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 

More from AnkitaVerma776806

the reference of book detail Hospital Booking.pptx
the reference of book detail Hospital Booking.pptxthe reference of book detail Hospital Booking.pptx
the reference of book detail Hospital Booking.pptxAnkitaVerma776806
 
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptx
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptxARTIFICIAL INTELLLLIGENCEE modul11_AI.pptx
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptxAnkitaVerma776806
 
voicecontrolhomeautomation-130627021245-phpapp01 (1).ppt
voicecontrolhomeautomation-130627021245-phpapp01 (1).pptvoicecontrolhomeautomation-130627021245-phpapp01 (1).ppt
voicecontrolhomeautomation-130627021245-phpapp01 (1).pptAnkitaVerma776806
 
detail the reference of Hospital Booking.pptx
detail the reference of Hospital Booking.pptxdetail the reference of Hospital Booking.pptx
detail the reference of Hospital Booking.pptxAnkitaVerma776806
 
Advances in ML learning process require. ppt.pptx
Advances in ML learning process require. ppt.pptxAdvances in ML learning process require. ppt.pptx
Advances in ML learning process require. ppt.pptxAnkitaVerma776806
 
Reasesrty djhjan S - explanation required.pptx
Reasesrty djhjan S - explanation required.pptxReasesrty djhjan S - explanation required.pptx
Reasesrty djhjan S - explanation required.pptxAnkitaVerma776806
 
SEMINAR_BIOMETRIC of hand fingerprint,voice bsed biometric ,eye based biometric
SEMINAR_BIOMETRIC  of hand fingerprint,voice bsed biometric ,eye based biometricSEMINAR_BIOMETRIC  of hand fingerprint,voice bsed biometric ,eye based biometric
SEMINAR_BIOMETRIC of hand fingerprint,voice bsed biometric ,eye based biometricAnkitaVerma776806
 
SE Complete notes mod 4 &5.pdf
SE Complete notes mod 4 &5.pdfSE Complete notes mod 4 &5.pdf
SE Complete notes mod 4 &5.pdfAnkitaVerma776806
 

More from AnkitaVerma776806 (15)

the reference of book detail Hospital Booking.pptx
the reference of book detail Hospital Booking.pptxthe reference of book detail Hospital Booking.pptx
the reference of book detail Hospital Booking.pptx
 
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptx
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptxARTIFICIAL INTELLLLIGENCEE modul11_AI.pptx
ARTIFICIAL INTELLLLIGENCEE modul11_AI.pptx
 
voicecontrolhomeautomation-130627021245-phpapp01 (1).ppt
voicecontrolhomeautomation-130627021245-phpapp01 (1).pptvoicecontrolhomeautomation-130627021245-phpapp01 (1).ppt
voicecontrolhomeautomation-130627021245-phpapp01 (1).ppt
 
detail the reference of Hospital Booking.pptx
detail the reference of Hospital Booking.pptxdetail the reference of Hospital Booking.pptx
detail the reference of Hospital Booking.pptx
 
Advances in ML learning process require. ppt.pptx
Advances in ML learning process require. ppt.pptxAdvances in ML learning process require. ppt.pptx
Advances in ML learning process require. ppt.pptx
 
Reasesrty djhjan S - explanation required.pptx
Reasesrty djhjan S - explanation required.pptxReasesrty djhjan S - explanation required.pptx
Reasesrty djhjan S - explanation required.pptx
 
SEMINAR_BIOMETRIC of hand fingerprint,voice bsed biometric ,eye based biometric
SEMINAR_BIOMETRIC  of hand fingerprint,voice bsed biometric ,eye based biometricSEMINAR_BIOMETRIC  of hand fingerprint,voice bsed biometric ,eye based biometric
SEMINAR_BIOMETRIC of hand fingerprint,voice bsed biometric ,eye based biometric
 
ch8.pptx
ch8.pptxch8.pptx
ch8.pptx
 
AI(Module1).pptx
AI(Module1).pptxAI(Module1).pptx
AI(Module1).pptx
 
continuity of module 2.pptx
continuity of module 2.pptxcontinuity of module 2.pptx
continuity of module 2.pptx
 
Advances in ML. ppt.pptx
Advances in ML. ppt.pptxAdvances in ML. ppt.pptx
Advances in ML. ppt.pptx
 
Module 3_DAA (2).pptx
Module 3_DAA (2).pptxModule 3_DAA (2).pptx
Module 3_DAA (2).pptx
 
SE Complete notes mod 4 &5.pdf
SE Complete notes mod 4 &5.pdfSE Complete notes mod 4 &5.pdf
SE Complete notes mod 4 &5.pdf
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
IOT VIVA QUESTION.pdf
IOT VIVA QUESTION.pdfIOT VIVA QUESTION.pdf
IOT VIVA QUESTION.pdf
 

Recently uploaded

High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

the refernce of programming C notes ppt.pptx

  • 1. #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! n"); return 0; } Various parts of the above program − • The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. • The next line int main() is the main function where the program execution begins. • The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. • The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. • The next line return 0; terminates the main() function and returns the value 0. Structure of C Program
  • 2. Data Types in C • Data types refer to the type of data that we are using in a C program. • we must specify the type of data that is in use, so that the compiler knows exactly what type of data it must expect from the given program. Types of Data Types in C Data Type Example of Data Type Basic Data Type Floating-point, integer, double, character. Derived Data Type Union, structure, array, etc. Enumerated Data Type Enums Void Data Type Empty Value Bool Type True or False
  • 3. Primary Data Types in C Here are the five primitive or primary data types: 1. Integer (int) – We use these for storing various whole numbers, such as 5, 8, 67, 2390, etc. 2. Character (char)– It refers to all ASCII character sets as well as the single alphabets, such as ‘x’, ‘Y’, etc. 3. Double (double)– These include all large types of numeric values that do not come under either floating-point data type or integer data type. Visit Double Data Type in C to know more. 4. Floating-point(float) – These refer to all the real number values or decimal points, such as 40.1, 820.673, 5.9, etc. 5. Void (void) – This term refers to no values at all. We mostly use this data type when defining the functions in a program. The size of every data type gets defined in bytes/ bits. Also, these data types are capable of holding a very wide range of values.
  • 4. Keyword Used Data Type Size int Integer 2 bytes or 16 bits: 16-bit Machine 4 bytes or 32 bits: 32-bit Machine float Floating-point 32 bits or 4 bytes. char Character 8 bits or 1 byte double Double 64 bits or 8 bytes • 1 bit for the sake of sign representation, • exponent uses 11 bits, • remaining 52 bits for the mantissa void Void 0 bytes Data Type Modifiers • short • long • unsigned • signed
  • 5. Range of Values of C Data Type Data Type Format Specifier Minimal Range Typical Bit Size unsigned char %c 0 to 255 8 char %c -127 to 127 8 signed char %c -127 to 127 8 int %d, %i -32,767 to 32,767 16 or 32 unsigned int %u 0 to 65,535 16 or 32 signed int %d, %i Same as int Same as int 16 or 32 short int %hd -32,767 to 32,767 16 unsigned short int %hu 0 to 65,535 16 signed short int %hd Same as short int 16 long int %ld, %li -2,147,483,647 to 2,147,483,647 32 long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the C99 standard) 64 signed long int %ld, %li Same as long int 32 unsigned long int %lu 0 to 4,294,967,295 32 unsigned long long int %llu 264 – 1 (It will be added by the C99 standard) 64 float %f 1E-37 to 1E+37 along with six digits of the precisions here 32 double %lf 1E-37 to 1E+37 along with six digits of the precisions here 64 long double %Lf 1E-37 to 1E+37 along with six digits of the precisions here 80
  • 6. Derived data types The derived data types to represent multiple values as well as single values in a program. Types of Derived Data Types in C The C language supports a few derived data types. These are: 1. Arrays – The array basically refers to a sequence (ordered sequence) of a finite number of data items from the same data type sharing one common name. 2. Function – A Function in C refers to a self-contained block of single or multiple statements. It has its own specified name. 3. Pointers – The Pointers in C language refer to some special form of variables that one can use for holding other variables’ addresses. 4. Unions – The unions are very similar to the structures. But here, the memory that we allocate to the largest data type gets reused for all the other types present in the group. 5. Structures – A collection of various different types of data type items that get stored in a contagious type of memory allocation is known as structure in C.
  • 7.
  • 8. Input-Output Statements The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations. scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. #include <stdio.h> int main() { int a,b; printf("Enter integer values for a & b: "); scanf("%d%d", &a, &b); If(a>b) printf("%d is big", a); else printf("%d is big", b); return 0; } Start Input a & b Display a Display b a>b Stop
  • 9.
  • 10. Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division) C Arithmetic Operators An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).
  • 11. C Increment and Decrement Operators C programming has two operators • increment ++ • decrement -- Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
  • 12. #include <stdio.h> int main() { int a = 10, b = 100; float c = 10.5, d = 100.5; printf("++a = %d n", ++a); printf("--b = %d n", --b); printf("++c = %f n", ++c); printf("--d = %f n", --d); return 0; } ++a = 11 --b = 99 ++c = 11.500000 --d = 99.500000
  • 13. #include <stdio.h> int main(){ int a = 10, b = 100; float c = 10.5, d = 100.5; printf("++a = %d n", ++a); printf("--b = %d n", --b); printf("c++ = %f n", c++); printf("d-- = %f n", d--); printf("c++ = %f n", c++); printf("d-- = %f n", d--); return 0; } Output: ++a = 11 --b = 99 c++ = 10.500000 d-- = 100.500000 c++ = 11.500000 d-- = 99.500000
  • 14. Operator Example Same as = a = b a = b += a += b a = a+b -= a -= b a = a-b *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b C Assignment Operators An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
  • 15. // Working of assignment operators #include <stdio.h> int main() { int a = 5, c; c = a; // c is 5 printf("c = %dn", c); c += a; // c is 10 printf("c = %dn", c); c -= a; // c is 5 printf("c = %dn", c); c *= a; // c is 25 printf("c = %dn", c); c /= a; // c is 5 printf("c = %dn", c); c %= a; // c = 0 printf("c = %dn", c); return 0; } c = 5 c = 10 c = 5 c = 25 c = 5 c = 0
  • 16. Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0. C 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.
  • 17. Decision making statement Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
  • 18. Decision making with if statement An if statement consists of a Boolean expression followed by one or more statements. Syntax: if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } #include <stdio.h> int main () { int a = 10; if( a < 20 ) { printf("a is less than 20n" ); } printf("value of a is : %dn", a); return 0; }
  • 19. if...else Statement The if statement may have an optional else block. Syntax: if (test expression) { // run code if test expression is true } else { // run code if test expression is false } How if...else statement works? • If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. • If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
  • 20. #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
  • 21. if...else if or if...else Ladder The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. if (test expression1) { // statement(s) } else if(test expression2) { // statement(s) } else if (test expression3) { // statement(s) } . . else { // statement(s) } Syntax of if...else Ladder
  • 22.
  • 23. #include <stdio.h> int main() { int number1, number2; printf("Enter two integers: "); scanf("%d %d", &number1, &number2); //checks if the two integers are equal. if(number1 == number2) { printf("Result: %d = %d",number1,number2); } //checks if number1 is greater than number2. else if (number1 > number2) { printf("Result: %d > %d", number1, number2); } //checks if both test expressions are false else { printf("Result: %d < %d",number1, number2); } return 0; }
  • 24. Nested if...else It is possible to include an if...else statement inside the body of another if...else statement. #include <stdio.h> int main() { int number1, number2; printf("Enter two integers: "); scanf("%d %d", &number1, &number2); if (number1 >= number2) { if (number1 == number2) { printf("Result: %d = %d",number1,number2); } else { printf("Result: %d > %d", number1, number2); } } else { printf("Result: %d < %d",number1, number2); } return 0; }
  • 25. Switch Statement The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable. Syntax: switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }
  • 26. Rules for switch statement in C language 1) The switch expression must be of an integer or character type. 2) The case value must be an integer or character constant. 3) The case value can be used only inside the switch statement. 4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. Valid Switch Invalid Switch Valid Case Invalid Case switch(x) switch(f) case 3; case 2.5; switch(x>y) switch(x+2.5) case 'a'; case x; switch(a+b-2) case 1+2; case x+2; switch(func(x,y)) case 'x'>'y'; case 1,2,3; int x,y,z; char a,b; float f;
  • 27.
  • 28. #include<stdio.h> int main(){ int number=0; printf("enter a number:"); scanf("%d",&number); switch(number){ case 10: printf("number is equals to 10"); break; case 50: printf("number is equal to 50"); break; case 100: printf("number is equal to 100"); break; default: printf("number is not equal to 10, 50 or 100"); } return 0; } enter a number:4 number is not equal to 10, 50 or 100 enter a number:50 number is equal to 50
  • 29. #include <stdio.h> int main() { int x = 10, y = 5; switch(x>y && x+y>0) { case 1: printf("hi"); break; case 0: printf("bye"); break; default: printf(" Hello bye "); } }
  • 30. #include<stdio.h> int main(){ int number=0; printf("enter a number:"); scanf("%d",&number); switch(number){ case 10: printf("number is equal to 10n"); case 50: printf("number is equal to 50n"); case 100: printf("number is equal to 100n"); default: printf("number is not equal to 10, 50 or 100"); } return 0; } Output enter a number:10 number is equal to 10 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100 enter a number:50 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100
  • 31. Nested switch case statement We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. #include <stdio.h> int main () { int i = 10; int j = 20; switch(i) { case 10: printf("the value of i evaluated in outer switch: %dn",i); case 20: switch(j) { case 20: printf("The value of j evaluated in nested switch: %dn",j); } } printf("Exact value of i is : %dn", i ); printf("Exact value of j is : %dn", j ); return 0; } the value of i evaluated in outer switch: 10 The value of j evaluated in nested switch: 20 Exact value of i is : 10 Exact value of j is : 20
  • 32. In programming, loops are used to repeat a block of code until a specified condition is met. C programming has three types of loops. 1.while loop 2.do...while loop 3.for loop
  • 33. A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Syntax: while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. #include <stdio.h> int main () { int a = 10; /* local variable definition */ while( a < 20 ) /* while loop execution */ { printf("value of a: %dn", a); a++; } return 0; }
  • 34. #include<stdio.h> void main () { int j = 1; while(j+=2,j<=10) { printf("%d ",j); } printf("%d",j); }
  • 35. do...while Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. Syntax: do { statement(s); } while( condition ); #include <stdio.h> int main () { int a = 10; /* local variable definition */ /* do loop execution */ do { printf("value of a: %dn", a); a = a + 1; }while( a < 20 ); return 0; } value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 36. #include <stdio.h> int main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.4f",sum); return 0; } Enter a number: 6 Enter a number: 2 Enter a number: 0 Sum = 8.0000
  • 37. #include<stdio.h> #include<stdlib.h> void main () { char c; int choice, dummy; do{ printf("n1. Print Hellon2. Print Javatpointn3. Exitn"); scanf("%d",&choice); switch(choice) { case 1 : printf("Hello"); break; case 2: printf("Javatpoint"); break; case 3: exit(0); break; default: printf("please enter valid choice"); } printf("do you want to enter more?"); scanf("%d",&dummy); scanf("%c",&c); }while(c=='y'); } 1. Print Hello 2. Print Javatpoint 3. Exit 1 Hello do you want to enter more? y 1. Print Hello 2. Print Javatpoint 3. Exit 2 Javatpoint do you want to enter more? y 1. Print Hello 2. Print Javatpoint 3. Exit 0 please enter valid choice do you want to enter more? y 1. Print Hello 2. Print Javatpoint 3. Exit 3
  • 38. For loop A for loop is a more efficient loop structure in ‘C’ programming. • The initial value of the for loop is performed only once. • The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned. • The incrementation/decrementation increases (or decreases) the counter by a set value. Syntax : for (initial value; condition; incrementation or decrementation ) { statements; } #include<stdio.h> int main() { int number; for(number=1;number<=10;number++) { printf("%dn",number); } return 0; }
  • 39. for (x = 0, y = num; x < y; i++, y--) { statements; } int i=0; int max = 10; for (; i < max; i++) { printf("%dn", i); } Other methods
  • 40. Nested Loops in C C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Syntax of Nested loop Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. } Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
  • 41. Nested for loop The nested for loop means any type of loop which is defined inside the 'for' loop. Syntax: for (initialization; condition; update) { for(initialization; condition; update) { // inner loop statements. } // outer loop statements. }
  • 42.
  • 43. Nested while loop The nested while loop means any type of loop which is defined inside the 'while' loop. Syntax: while(condition) { while(condition) { // inner loop statements. } // outer loop statements. }
  • 44. #include <stdio.h> int main() { int rows; int columns; int k=1; printf("Enter the number of rows :"); . scanf("%d",&rows); printf("nEnter the number of columns :"); scanf("%d",&columns); int a[rows][columns]; int i=1; while(i<=rows) { int j=1; while(j<=columns) { printf("%dt",k); k++; j++; } i++; printf("n"); } }
  • 45. Nested do..while loop The nested do..while loop means any type of loop which is defined inside the 'do..while' loop. Syntax: do { do { // inner loop statements. }while(condition); // outer loop statements. }while(condition);
  • 46. #include <stdio.h> int main() { int i=1; do // outer loop { int j=1; do // inner loop { printf("*"); j++; }while(j<=8); printf("n"); i++; }while(i<=4); }
  • 47. C Array • An array is defined as the collection of similar type of data items stored at contiguous memory locations. • Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. • It also has the capability to store the collection of derived data types, such as pointers, structure, etc. • The array is the simplest data structure where each data element can be randomly accessed by using its index number. • By using the array, we can access the elements easily. Properties of Array 1. Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. 2. Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. 3. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
  • 48. Advantage of C Array 1) Code Optimization: Less code to the access the data. 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array. Disadvantage of C Array 1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
  • 49. Declaration of C Array We can declare an array in the c language in the following way. Syntax: data_type array_name[array_size]; Example: int marks[5]; • Arrays have 0 as the first index, not 1. • In this example, mark[0] is the first element. • If the size of an array is n, to access the last element, the n-1 index is used. • Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1] will be 2122d. Similarly, the address of mark[2] will be 2124d and so on. • This is because the size of a int is 2 bytes.
  • 50. Initialization of C Array The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example. marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; #include<stdio.h> int main(){ int i=0; int marks[5];//declaration of array marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; for(i=0;i<5;i++) { printf("%d n",marks[i]); } return 0; }
  • 51. C Array: Declaration with Initialization We can initialize the c array at the time of declaration. int marks[5]={20,30,40,50,60}; In such case, there is no requirement to define the size. So it may also be written as the following code. int marks[]={20,30,40,50,60}; Initialization of a 2d array // Different ways to initialize two-dimensional array int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[2][3] = {1, 3, 0, -1, 5, 9};
  • 52. Change Value of Array elements int mark[5] = {19, 10, 8, 17, 9} // make the value of the third element to -1 mark[2] = -1; // make the value of the fifth element to 0 mark[4] = 0; #include <stdio.h> int main() { int mark[5] = {19, 10, 8, 17, 9}; mark[2] = -1; mark[4] = 0; for(int i = 0; i < 5; i++) { printf("Array values are: %dn", mark[i]); } return 0; } Array values are: 19 Array values are: 10 Array values are: -1 Array values are: 17 Array values are: 0
  • 53. #include<stdio.h> int main() { int i=0; int marks[5]={20,30,40,50,60}; //Declaration with Initialization for(i=0;i<5;i++) { printf("%d n",marks[i]); } return 0; }
  • 54. #include <stdio.h> int main () { int a[5]; int n,i,sum=0; printf( "Enter the size of arrayt"); scanf("%d",&n); printf( "Enter the elements of arrayn"); for (i = 0; i < n; ++i) { scanf("%d",&a[i]); } for (i = 0; i < n; ++i) { sum += a[i]; printf( "Sum of Array elements is: %dn ", sum); } printf( "nSum of Array elements is: %d ", sum); }
  • 55. #include <stdio.h> int main () { int balance[5] = {1000, 2, 3, 17, 50}; printf( "Sum of Array elements is: %d ", getsum( balance, 5 )); return 0; } int getsum(int arr[], int size) { int i; int sum = 0; for (i = 0; i < size; ++i) { sum += arr[i]; } return sum; }
  • 56. One Dimensional Array A one-dimensional array has one subscript. One Dimensional (1D) array is an array which is represented either in one row or in one column. The one-dimensional arrays are known as vectors. In other words, it can be represented as in a single dimension-width or height as shown in the below figure:
  • 57. Two Dimensional Array Two Dimensional (2D) array is a fixed-length, homogeneous data type, row and column- based data structure which is used to store similar data type element in a row and column- based structure. A two-dimensional array is referred to as a matrix or a table. A matrix has two subscripts, one denotes the row and another denotes the column. In other words, a two-dimensional array is an array of a one-dimensional array. The general syntax for declaration of a 2D array is given below: data_type array_name[row] [column]; where data_type specifies the data type of the array. array_name specifies the name of the array, row specifies the number of rows in the array and column specifies the number of columns in the array. The total number of elements that can be stored in a two array can be calculated by multiplying the size of all the dimensions.
  • 58.
  • 59. #include <stdio.h> int main() { float a[2][2], b[2][2], result[2][2]; printf("Enter elements of 1st matrixn"); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { printf("Enter a%d%d: ", i + 1, j + 1); scanf("%f", &a[i][j]); } printf("Enter elements of 2nd matrixn"); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { printf("Enter b%d%d: ", i + 1, j + 1); scanf("%f", &b[i][j]); } for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { result[i][j] = a[i][j] + b[i][j]; } printf("nSum Of Matrix:"); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { printf("%.1ft", result[i][j]); if (j == 1) printf("n"); } return 0; } Enter elements of 1st matrix Enter a11: 2; Enter a12: 0.5; Enter a21: -1.1; Enter a22: 2; Enter elements of 2nd matrix Enter b11: 0.2; Enter b12: 0; Enter b21: 0.23; Enter b22: 23; Sum Of Matrix: 2.2 0.5 -0.9 25.0
  • 60. Structure • Arrays allow to define type of variables that can hold several data items of the same kind. • structure is another user defined data type available in C that allows to combine data items of different kinds. • Structures are used to represent a record. Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows − Syntax: struct [structure tag] { member definition; or member definition; ... member definition; } [one or more structure variables]; datatype member; struct [tagname] { datatype member; datatype member ; }; 1. struct is a keyword. 2. tagname specifies the name of structure. 3. member, member specifies the data items that make up structure.
  • 61. Example: 1 struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book1,book2; Example: 2 struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; Int main() { struct Books book1,book2; } Example: 3 typedef struct Distance { int feet; float inch; } distances; int main() { distances d1, d2; }
  • 62.
  • 63.
  • 64.
  • 65. 1. By . (member or dot operator) 2. By -> (structure pointer operator)
  • 66. #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; printf( "Book 1 author : %sn", Book1.author); printf( "Book 1 subject : %sn", Book1.subject); printf( "Book 1 book_id : %dn", Book1.book_id); printf( "Book 2 author : %sn", Book2.author); printf( "Book 2 subject : %sn", Book2.subject); printf( "Book 2 book_id : %dn", Book2.book_id); return 0; } Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700
  • 67. #include <stdio.h> #include <string.h> struct Books{ char title[50]; char author[50]; int id;}book1, book2; void printBook(struct Books book); void main(){ strcpy(book1.title,"C Langauage"); strcpy(book1.author,"Bell"); book1.id=1234; strcpy(book2.title,"Java Programming"); strcpy(book2.author,"Sun solaris"); book2.id=2345; printBook(book1); printBook(book2); } void printBook(struct Books book) { printf("Book1:%sn",book.title); printf("Author:%sn",book.author); printf("id:%dnn",book.id); }
  • 68. copying structure variables A structure is treated like a value that occupies a given number of bytes. struct PairOfInts { int a; int b; }; PairOfInts x, y; x.a = 20; x.b = 40; y = x; create two variables, x and y, of type PairOfInts. The next two statements initialize structure x. The last statement, y = x; copies the structured value in x into y. You get an exact copy. Structure copies are done the same way no matter how you indicate the structures. PairOfInts *p, *q; p = new PairOfInts; q = new PairOfInts; p->a = 20; p->b = 40; *q = *p;
  • 69. #include <stdio.h> struct class{ int number; char name[20]; float marks;}; main(){ int x; struct class student1 = {001,"Hari",172.50}; struct class student2 = {002,"Bobby", 167.00}; struct class student3; student3 = student2; x = ((student3.number == student2.number) && (student3.marks == student2.marks)) ? 1 : 0; if(x == 1){ printf("nstudent2 and student3 are samenn"); printf("%d %s %fn", student3.number, student3.name, student3.marks); } else printf("nstudent2 and student3 are differentnn"); } comparing structure variables
  • 70. Pointers to Structures You can define pointers to structures in the same way as you define pointer to any other variable − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the → operator as follows − struct_pointer->title;
  • 71. #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book1, Book2 ; void printBook( struct Books *book ); int main( ) { strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; printBook( &Book1 ); printBook( &Book2 ); return 0; } void printBook( struct Books *book ) { printf( "Book title : %sn", book->title); printf( "Book author : %sn", book->author); printf( "Book subject : %sn", book->subject); printf( "Book book_id : %dn", book->book_id); }
  • 72. Nested Structures struct student_college_detail { int college_id; char college_name[50]; }; struct office_detail { int cl_id; char cl_name[50]; }; struct student_detail { int id; char name[20]; float percentage; struct student_college_detail clg_data; struct office_detail off_data; } stu_data,stu_data1; void data(struct student_detail stud); void main() { struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Anna University",121,"Rajesh"}; struct student_detail stu_data1 = {2, "Poorvik", 94.0, 6458,"Reva University",654,"Sarvesh"}; data(stu_data); data(stu_data1); } void data(struct student_detail stud){ printf(" Id is : %d n", stud.id); printf(" Name is : %s n", stud.name); printf(" Percentage is : %f n", stud.percentage); printf(" College Id is : %d n", stud.clg_data.college_id); printf(" College Name is : %s n", stud.clg_data.college_name); printf(" College Id is : %d n", stud.off_data.cl_id); printf(" College Name is : %s nnn", stud.off_data.cl_name); }
  • 73. A union • is a special data type available in C that allows to store different data types in the same memory location. • User can define a union with many members, but only one member can contain a value at any given time. • Unions provide an efficient way of using the same memory location for multiple- purpose. The format of the union statement is as follows − union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; • The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. • At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional.
  • 74. union Data { int i; float f; char str[20]; } data; #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); return 0; } Output: Memory size occupied by data : 20
  • 75. Accessing Union Members • To access any member of a union, we use the member access operator (.). • The member access operator is coded as a period between the union variable name and the union member that we wish to access. • You would use the keyword union to define variables of union type. #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str); return 0; } #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; }
  • 76. #include <stdio.h> struct store { double price; union { struct{ char *title; char *author; int number_pages; } book; struct { int color; int size; char *design; } shirt; }item; } s; int main() { s.item.book.title = "C programming"; s.item.book.author = "John"; s.item.book.number_pages = 189; s.item.shirt.design = "white"; printf( "Book 1 author : %sn", s.item.book.title); printf( "Book 1 author : %sn", s.item.book.author); printf( "Book 1 author : %dn", s.item.book.number_pages); printf( "Book 1 author : %sn", s.item.shirt.design); return 0; }
  • 77. Struct Union The struct keyword is used to define a structure. The union keyword is used to define union. When the variables are declared in a structure, the compiler allocates memory to each variables member. The size of a structure is equal or greater to the sum of the sizes of each data member. When the variable is declared in the union, the compiler allocates memory to the largest size variable member. The size of a union is equal to the size of its largest data member size. Each variable member occupied a unique memory space. Variables members share the memory space of the largest size variable. Changing the value of a member will not affect other variables members. Changing the value of one member will also affect other variables members. Each variable member will be assessed at a time. Only one variable member will be assessed at a time. We can initialize multiple variables of a structure at a time. In union, only the first data member can be initialized. All variable members store some value at any point in the program. Exactly only one data member stores a value at any particular instance in the program. The structure allows initializing multiple variable members at once. Union allows initializing only one variable member at once. It is used to store different data type values. It is used for storing one at a time from different data type values. It allows accessing and retrieving any data member at a time. It allows accessing and retrieving any one data member at a time. Difference between Structure and Union
  • 78. Advantages of Structure •Structure stores more than one data type of the same object together. •It is helpful when you want to store data of different or similar data types such as name, address, phone, etc., •It makes it very easy to maintain the entire record as we represent complete records using a single name. •The structure allows passing a whole set of records to any function with the help of a single parameter. •An array of structures can also be created to store multiple data of similar data types. Disadvantages of Structure •If the complexity of the project goes increases, it becomes hard to manage all your data members. •Making changes to one data structure in a program makes it necessary to change at several other places. So it becomes difficult to track all changes. •The structure requires more storage space as it allocates memory to all the data members, & even it is slower. •The structure takes more storage space as it gives memory to all the different data members, whereas union takes only the memory size required by the largest data size parameters, and the same memory is shared with other data members. Advantages of Union •Union takes less memory space as compared to the structure. •Only the largest size data member can be directly accessed while using a union. •It is used when you want to use less (same) memory for different data members. •It allocates memory size to all its data members to the size of its largest data member. Disadvantages of Union •It allows access to only one data member at a time. •Union allocates one single common memory space to all its data members, which are shared between all of them. •Not all the union data members are initialized, and they are used by interchanging values at a time.
  • 79. C Pointers • The pointer in C language is a variable which stores the address of another variable. • This variable can be of type int, char, array, function, or any other pointer. • The size of the pointer depends on the architecture. • However, in 32-bit architecture the size of a pointer is 2 byte. Declaring a pointer The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer. int *a;//pointer to int char *c;//pointer to char Example: int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.