CHAPTER 2 Strings Number and DateTime

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

CHAPTER I.

ARRAY

CHAPTER II
STRINGS, NUMBER AND
DATE/TIME
Learning Content:
 Number
o Math Operations in C++
o Random Numbers in C++
 String
o C-Style Character String
o Functions that manipulate null-terminated strings
 Date/Time
o C++ standard library for date and time
o four time-related types: clock_t, time_t, size_t, and tm
o Date Time Functions
o Format Time using struct tm

Intended Learning Outcomes


At the end of the lesson, the student should be able to:
1. Enumerate
2.

1
CHAPTER I. ARRAY

Name : __________________________________________________ Date : ______________


Course/Year/Section : ______________________________________ Score: ______________

Let us determine how much you already know about the INTRODUCTION TO DISCRETE
STRUTURES

Pre-assessment 1 for LO1, LO2, to LO7

Identification:

1. _______________It is a branch of mathematics involving discrete elements that uses


algebra and arithmetic.
2. _______________It is based upon continuous number line or the real numbers.
3. _______________Is an art and there are no universal approaches to solving problems

Enumeration:

1. What are the The traditional “GUESS” method (Heller and Heller, Univ. of Minnesota)
_______________
_______________
_______________
_______________
_______________
2. What are the Framework for Problem Solving (Polya)
_______________
_______________
_______________
_______________

2
CHAPTER I. ARRAY

INFORMATION SHEET
STRINGS, NUMBER , DATE/TIME
A. STRINGS

C++ provides following two types of string representations −


 The C-style character string.
 The string class type introduced with Standard C++.

The C-Style Character String


The C-style character string originated within the C language and
continues to be supported within C++. This string is actually a one-
dimensional array of characters which is terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string −

3
CHAPTER I. ARRAY

#include <iostream>

using namespace std;

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

C++ supports a wide range of functions that manipulate null-terminated strings –


Sr.No Function Purpose
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2);Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
4 strcmp(s1, s2); than 0 if s1>s2.
Returns a pointer to the first occurrence of character ch in string
5 strchr(s1, ch); s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
Following example makes use of few of the above-mentioned functions –

4
CHAPTER I. ARRAY

#include <iostream>
#include <cstring>

using namespace std;

int main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

5
CHAPTER I. ARRAY

The String Class in C++


The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality. Let us check the following example –
#include <iostream>
#include <string>

using namespace std;

int main () {

string str1 = "Hello";


string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

String Length
To get the length of a string, use the length() function:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();

Tip: You might see some C++ programs that use the size() function to get the length of a string.
This is just an alias of length(). It is completely up to you if you want to use length() or size():
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();

6
CHAPTER I. ARRAY

B. NUMBER

Normally, when we work with Numbers, we use primitive data types such as int, short, long, float
and double, etc. The number data types, their possible values and number ranges have been
explained while discussing C++ Data Types.

Defining Numbers in C++


You have already defined numbers in various examples given in previous chapters. Here is another
consolidated example to define various types of numbers in C++ −
#include <iostream>
using namespace std;

int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;

// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;

// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;

return 0;
}

Math Operations in C++


In addition to the various functions you can create, C++ also includes some useful functions you
can use. These functions are available in standard C and C++ libraries and called built-in functions.
These are functions that can be included in your program and then use.

7
CHAPTER I. ARRAY

C++ has a rich set of mathematical operations, which can be performed on various numbers.
Following table lists down some useful built-in mathematical functions available in C++.

To utilize these functions you need to include the math header file <cmath>.

Sr.N
o Function Purpose
1 double cos(double); This function takes an angle (as a double) and returns the cosine.
2 double sin(double); This function takes an angle (as a double) and returns the sine.
3 double tan(double); This function takes an angle (as a double) and returns the tangent.
This function takes a number and returns the natural log of that
4 double log(double); number.
double pow(double, The first is a number you wish to raise and the second is the power
5 double); you wish to raise it t
double hypot(double, If you pass this function the length of two sides of a right triangle, it
6 double); will return you the length of the hypotenuse.
7 double sqrt(double); You pass this function a number and it gives you the square root.
This function returns the absolute value of an integer that is passed
8 int abs(int); to it.
This function returns the absolute value of any decimal number
9 double fabs(double); passed to it.
Finds the integer which is less than or equal to the argument passed
10 double floor(double); to it.

Following is a simple example to show few of the mathematical operations –

#include <iostream>
#include <cmath>
using namespace std;

int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;

// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;

return 0;
}

8
CHAPTER I. ARRAY

Random Numbers in C++


There are many cases where you will wish to generate a random number. There are actually two
functions you will need to know about random number generation. The first is rand(), this
function will only return a pseudo random number. The way to fix this is to first call the srand()
function.

Following is a simple example to generate few random numbers. This example makes use of
time() function to get the number of seconds on your system time, to randomly seed the rand()
function –
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main () {
int i,j;

// set the seed


srand( (unsigned)time( NULL ) );

/* generate 10 random numbers. */


for( i = 0; i < 10; i++ ) {
// generate actual random number
j = rand();
cout <<" Random Number : " << j << endl;
}

return 0;
}

9
CHAPTER I. ARRAY

C. DATE/TIME

The C++ standard library does not provide a proper date type. C++ inherits the structs and
functions for date and time manipulation from C. To access date and time related functions and
structures, you would need to include <ctime> header file in your C++ program.

There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and
time_t are capable of representing the system time and date as some sort of integer.

The structure type tm holds the date and time in the form of a C structure having the following
elements –

struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}

Following are the important functions, which we use while working with date and time in C or C+
+. All these functions are part of standard C and C++ library and you can check their detail using
reference to C++ standard library given below.

Sr.No Function Purpose


This returns the current calendar time of the
system in number of seconds elapsed since
January 1, 1970. If the system has no time, .1 is
1 time_t time(time_t *time); returned.
This returns a pointer to a string of the form day
2 char *ctime(const time_t *time); month year hours:minutes:seconds year\n\0.
This returns a pointer to the tm structure
3 struct tm *localtime(const time_t *time); representing local time.
This returns a value that approximates the
amount of time the calling program has been
running. A value of .1 is returned if the time is
4 clock_t clock(void); not available.
This returns a pointer to a string that contains
the information stored in the structure pointed
to by time converted into the form: day month
5 char * asctime ( const struct tm * time ); date hours:minutes:seconds year\n\0
6 struct tm *gmtime(const time_t *time); This returns a pointer to the time in the form of
a tm structure. The time is represented in

10
CHAPTER I. ARRAY

Coordinated Universal Time (UTC), which is


essentially Greenwich Mean Time (GMT).
This returns the calendar-time equivalent of the
7 time_t mktime(struct tm *time); time found in the structure pointed to by time.
This function calculates the difference in
8 double difftime ( time_t time2, time_t time1 ); seconds between time1 and time2.
This function can be used to format date and
9 size_t strftime(); time in a specific format.

Current Date and Time


Suppose you want to retrieve the current system date and time, either as a local time or as a
Coordinated Universal Time (UTC). Following is the example to achieve the same −

#include <iostream>
#include <ctime>

using namespace std;

int main() {
// current date/time based on current system
time_t now = time(0);

// convert now to string form


char* dt = ctime(&now);

cout << "The local date and time is: " << dt << endl;

// convert now to tm struct for UTC


tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}

11
CHAPTER I. ARRAY

Format Time using struct tm


The tm structure is very important while working with date and time in either C or C++. This
structure holds the date and time in the form of a C structure as mentioned above. Most of the
time related functions makes use of tm structure. Following is an example which makes use of
various date and time related functions and tm structure −

While using structure in this chapter, I'm making an assumption that you have basic
understanding on C structure and how to access structure members using arrow -> operator.

#include <iostream>
#include <ctime>

using namespace std;

int main() {
// current date/time based on current system
time_t now = time(0);

cout << "Number of sec since January 1,1970 is:: " << now << endl;

tm *ltm = localtime(&now);

// print various components of tm structure.


cout << "Year:" << 1900 + ltm->tm_year<<endl;
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< 5+ltm->tm_hour << ":";
cout << 30+ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
}

12
CHAPTER I. ARRAY

Name : __________________________________________________ Date : ______________


Course/Year/Section : ______________________________________ Score: ______________

Let us determine how much you already know about the INTRODUCTION TO DISCRETE
STRUTURES

Self-Check 1 for LO1, LO2, to LO7

Identification:

1. _______________It is a branch of mathematics involving discrete elements that uses


algebra and arithmetic.
2. _______________It is based upon continuous number line or the real numbers.
3. _______________Is an art and there are no universal approaches to solving problems

Enumeration:

2. What are the The traditional “GUESS” method (Heller and Heller, Univ. of Minnesota)
_______________
_______________
_______________
_______________
_______________
2. What are the Framework for Problem Solving (Polya)
_______________
_______________
_______________
_______________

Answer Key

IDENTIFICATION:
1. Discrete Mathematics It is a branch of mathematics involving discrete elements that uses
algebra and arithmetic.
2. Continuous Mathematics It is based upon continuous number line or the real numbers.

13
CHAPTER I. ARRAY

3. Problem solving is an art and there are no universal approaches to solving problems

ENUMERATION:
1. What are the The traditional “GUESS” method (Heller and Heller, Univ. of Minnesota)
a. Givens - Identify the “given” information
b. Unknown - Identify what is wanted
c. Equation - Select equation for solution
d. Solution - Solve equation for unknown
e. Survey - Make certain solution is realistic
2. What are the Framework for Problem Solving (Polya)
a. Understanding the problem
b. Devising a Solution Plan
c. Carrying out the plan
d. Looking back i.e. verifying

14

You might also like