C++ Programming: Data Structure
C++ Programming: Data Structure
Data Structure
Objectives
• One-dimensional Array
Syntax: type var_name[size];
Example:
int x[20];
char letter[26];
double price[10];
Array
• Two-dimensional Array
Syntax: type var_name[rowsize]
[colsize];
Example:
int x[3][4];
double amount [10][50];
• Multi-dimensional Array
Examples:
int id[7]={1,2,3,4,5,6,7}
float f[] = {1.2. 14.3, 52.54 };
char vowel[5]={‘a’, ‘e’,’I’,’o’,’u’]};
char name=“rac”;
char vowel[6] = “aeiou”;
Pointer
Example:
char *p1, *p2;
int *p3;
double *p4, *p5;
Pointer
& Operator
• It is simply called the address operator.
• & operator is a unary operator that returns the
memory address of its operand.
• It produces a pointer that points to the variable
Example: p = &v
Pointer
* Operator
• It is called “dereferencing operator”
• * operator is a unary operator that returns the
value of the variable located at the address that
follows.
• It produces the variable it points to
Example: q = *m
Pointer
Example:
long *q;
q = q +1;
// value of q increased by 4
Pointer Comparison
int main(){
void max_min(int a, int b, int &max, int &min );
//function protrype
Int x,y,min, max;
cout<<“Enter 2 number : “;
cin>>x>>y;
max_min(x,y,max,min);
cout<<“MAX = “<<max<<endl;
cout<<“MIN = “<<min<<endl;
return 0;
}
Passing Arguments by Reference
Examples:
• The declaration for an int pointer array of size 20
int *arrayPtr[20]
• To assign the address of an integer variable var to the
3rd element of the array
*arrayPtr[2] = &var;
Arrays of Pointer
main(){
floatx[5];
void fn (float *);
fn(x);
return 0;
}
void fn() {
…
}
Structure
struct student{
struct student{
char id[5];
char id[5];
char name[25];
char name[25];
int age;
int age;
};
}stud1, stud2;
struct student stud1, stud21;
struct {
char id[5];
char name[25];
int age;
}stud1, stud2;
Referencing Structure Elements
Example : stud1.name=“Racquel”
Array of Structures
struct student{
struct student{
char id[5];
char id[5];
char
char
name[25];
name[25];
int age;
int age;
};
} stud[40];
Sturct stud[50]
Passing Structure to Functions
Examples:
Modify(stud[6].name);
// pass structure element to function modify
Modify(stud[6] name);
// pass entire structure to function modify
Structure within Structure
struct student{
char id[5];
char name[25];
int age;
}stud1, stud2;
struct detail {
struct student stud;
char course[10];
Int level;
} stud_detail1;
Student id = stud_detail1.stud.id;
Structure within Structure
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace td;
struct book{
char title[40];
char author[25];
double cost;
};
Structure within Structure
int main(){
struct book bk;
cout<<“ENTER TITLE : “
gets(details.title);
cout<<“ENTER AUTHOR : “
gets(details.author);
cout<<“ENTER COST : “
cin>>details.cost;
printf("%s by %s : P %.2f " ,
details.title, details.author, details.cost);
cout<<endl;
return 0;
}