0% found this document useful (0 votes)
10 views42 pages

C++ Recursion and Struct Examples

The document provides various C++ programming examples focusing on recursion, structures, and nested loops. It includes implementations for factorial calculation, Fibonacci sequence, and drawing shapes using loops, as well as defining and using structures to store related data. Additionally, it discusses the syntax for defining structures and accessing their members, along with examples of initializing and using structure variables.

Uploaded by

Arabi Keshk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views42 pages

C++ Recursion and Struct Examples

The document provides various C++ programming examples focusing on recursion, structures, and nested loops. It includes implementations for factorial calculation, Fibonacci sequence, and drawing shapes using loops, as well as defining and using structures to store related data. Additionally, it discusses the syntax for defining structures and accessing their members, along with examples of initializing and using structure variables.

Uploaded by

Arabi Keshk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C++

Recursion & Struct


Recursion Function
# include <iostream>
using namespace std;
void fun (int n) {
if (n<1);
return; \\ base condition
else
cout <<“round:”<< n <<endl;\\ logic output
fun (n-1); } \\ sub problem
int main () {
fun (5) ;
return 0;}
Recursion without condition
• # include <iostream>
• using namespace std;
• void fun (int n) {
• \\ if (n<1);
• \\ return; \\ base condition
• \\ else
• cout <<“round:”<< n <<endl;\\ logic output
• fun (n-1); } \\ sub problem
• int main () {
• fun (5) ;
• return 0;}
4
C++ Programming Code to Find Factorial of Number
Following C++ program ask to the user to enter a
number to find its factorial, then display the result on
the screen :
#include<iostream.h>
using namespace std;
int main() {
int num, i, fact=1;
cout<<"Enter a number : ";
cin>>num;
for(i=num; i>0; i--) {
fact=fact*i;
}
cout <<"Factorial of "<<num<<" is "<<fact;
return 0;
}
Factorial Recursion Function

Computing Factorial

factorial(0) = 1;
factorial(n) = n*factorial(n-1);

Factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) =


3 * ( 2 * (1 * factorial(0))) =
3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 = 6

5
\\ Factorial recursion function
#include<iostream>
using namespace std;
int fact (int n) {
if (n == 0 || n == 1)
return 1;
else
return n * fact (n - 1);
}
int main() {
cout << fact (5);
return 0;
}
\\ Fibonacci recursion function
#include<iostream>
using namespace std;
\\ 0 1 2 3 4 5 6 7………….
\\ 0 1 1 2 3 5 8 13………….
int fib (int n) {
if (n == 0 || n == 1)
return n;
else
return fib (n - 1) + fib (n - 2);
}
int main() {
cout << fib (3);
return 0;
Recursion function to calculate the sum of the
first n natural numbers.
The first n natural numbersare the numbers
from 1 to n.

#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) return 1;
else return n + sum(n - 1);
}
int main() {
cout << sum(5) << endl;
return 0; }
Drawing rectangle shape (*) using
Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 6 ; j++)
{
cout << "*";
}
cout << endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i ; j++)
{
cout << "*";
}
cout << endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 1; i <= 5; i++)
{
for (int j = 4; j >= i ; j--)
{
cout << “ ";
}
for (int k = 1; i <= i; k++) {
cout << “*” ; }
cout <<endl;}}
Drawing triangle shape using Nested loop
#include<iostream>
using namespace std;
int main(){
for (int i = 5; i >= 1; i--)
{
for (int j = 4; j >= i ; j--)
{
cout << “ ";
}
for (int k = 1; i <= i; k++) {
cout << “*” ; }
cout <<endl;}}
#include <iostream>
using namespace std;
void f(int n)
{
if (n < 0)
return;
else for (i = 0; i < n; i++) {
cout << "*";
}
cout << endl;
f(n - 1); }
int main() {
f(5);
return 0; }
Inbuilt C++ functions
#include <iostream>
int main(){
int a,b,c;
cout<<"Enter Three Integers: ";
cin>>a>>b>>c;
cout<<"Maximum is: "<<maximum(a,b,c)<<endl;
return 0;}
int maximum (int a, int b, int c) { //maximum should have type int.
if(a>b) {
if(a>c) {
return a; } }
else
if(b>a) {
if(b>c) {
return b; } }
else if(c>b) {
if(c>a) {
return c; } } }
function max (i, j, k) {
if(i > j && i > k(
{
return i;
}
else if (j > k ( {
return j ;
{
else}
return k ;}}
Structure
• Structure is a collection of variables of
different data types under a single name.
– It is similar to a class in that, both holds a
collection of data of different data types.
• For example: You want to store some
information about a student: his/her name,
student_no and …….
• You can easily create different
variables name, student_no, …. to store
these information separately.
– For Example : to store a student record which
includes different data items like (student_no , Fname,
Lname , Total_Marks , GPA , …….).
– Syntax for Defining Struct is :

Struct struct_name
{
Datatype identifier 1;
Datatype identifier 2;
.
.
.
Datatype identifier n;
}
Syntax of the structure definition
Declare Structure in C++
• The struct keyword defines a structure type followed by an
identifier (name of the structure).
• Declare one or more members (declare variables inside
curly braces) of that structure.
For example:
struct Person
{
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members:
Define A Structure Variable
• Once you declare a structure person as
above. You can define a structure variable
as:

Person bill;

• Here, a structure variable bill is defined


which is of type structure Person.
Access Members of A Structure
• The members of structure variable is
accessed using a dot (.) operator.

• Suppose, you want to access age of


structure variable bill and assign it 50 to it.

[Link] = 50;
Once , a new struct is defined , we can use it as
any other data type.
Example: C++ Structure
Output

Enter Full name: Mohamed Aly


Enter age: 27
Enter salary: 3024.4

Displaying Information.
Name: Mohamed Aly
Age: 27
Salary: 3024.4
A Simple Structure
• The structure is a kind of blueprint
specifying what information is necessary
for a single part.

• The program PARTS defines the structure


part, defines a structure variable of that
type called part1, assigns values to its
members, and then displays these values.
A Simple Structure
// [Link]
// uses parts inventory to demonstrate structures
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct part //declare a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
////////////////////////////////////////////////////////////////
A Simple Structure
int main()
{
part part1; //define a structure variable
[Link] = 6244; //give values to
// structure members
[Link] = 373;
[Link] = 217.55F;
//display structure members
cout << “Model “ << [Link];
cout << “, part “ << [Link];
cout << “, costs $” << [Link] << endl;
return 0;
} The program’s output looks like this:
Model 6244, part 373, costs $217.55
Defining a Structure Variable
The first statement in main()
part part1;
• defines a variable, called part1, of type structure
part.
• This definition reserves space in memory for
part1. How much space? Enough to hold all the
members of part1—namely modelnumber,
partnumber, and cost.
– In this case there will be 4 bytes for each of the two
ints (assuming a 32-bit system), and 4 bytes for the
float.
Accessing Structure Members
• Once a structure variable has been defined,
its members can be accessed using
something called the dot operator. Here’s
how the first member is given a value:
[Link] = 6244;
• The structure member is written in three parts:
the name of the structure variable (part1);
– the dot operator, which consists of a period (.);
and the member name (modelnumber). This
means “the modelnumber member of part1.”
Example
// [Link]
// shows initialization of structure variables
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct part //specify a structure
{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};
////////////////////////////////////////////////////////////////
Cont., Example
int main() {
//initialize variable
part part1 = { 6244, 373, 217.55F };
part part2; //define variable
//display first variable
cout << “Model “ << [Link];
cout << “, part “ << [Link];
cout << “, costs $” << [Link] << endl;
part2 = part1; //assign first variable to second
//display second variable
cout << “Model “ << [Link];
cout << “, part “ << [Link];
cout << “, costs $” << [Link] << endl;
return 0; Here’s the output:
} Model 6244, part 373, costs $217.55
Model 6244, part 373, costs $217.55
Example:
A phone number, such as (048) 767-8900, can be having
three parts: the area code (048), the exchange (767), and the
number (8900). Write a program that uses a structure to
store these three parts of a phone number separately. Call
the structure phone. Create two structure variables of type
phone. Initialize one, and have the user input a number for
the other one. Then display both numbers.
The interchange might look like this:
Enter your area code, exchange, and number: 415 555 1212
My number is (048) 767-8900
Your number is (013) 555-1212
#include <iostream>
using namespace std;
struct phone { int area; //area code (3 digits)
int exchange; //exchange (3 digits)
int number; //number (4 digits) };
int main() {
phone ph1 = { 048, 767, 8900 }; //initialize phone no.
phone ph2;
// get phone no. from user
cout << “\nEnter your area code, exchange, and
number”;
cin >> [Link] >> [Link] >> [Link];
cout << “\nMy number is “ << “(“ << [Link] << “) “
<< [Link] << “-‟ << [Link];
cout << “\nYour number is “<< “(“ << [Link] << “)
“<< [Link] << “-‟ << [Link] << endl;
return 0;
}
Example 2
Create a structure called Volume that uses three
variables of type Distance to model the volume of
a room. Initialize a variable of type Volume to
specific dimensions, then calculate the volume it
represents, and print out the result. To calculate
the volume, convert each dimension from a
Distance variable to a variable of type float
representing feet and fractions of a foot, and then
multiply the resulting three numbers.
#include <iostream>
struct Volume
using namespace std;
{
struct Distance
Distance length;
{
Distance width;
int feet;
Distance height; };
float inches; };
int main() {
float l, w, h;
Volume room1 = { { 16, 3.5 }, { 12, 6.25 }, { 8, 1.75 } };
l = [Link] + [Link]/12.0;
w = [Link] + [Link] /12.0;
h = [Link] + [Link]/12.0;
cout << “Volume = “ << l*w*h << “ cubic feet\n”;
return 0;
}
struct Member}
string FirstName;
string LastName;
int BirthYear ;
{ ;

Does Java support structs?


class Member }
public String FirstName ;
public String LastName ;
public int BirthYear ;
{ ;

You might also like