C++ is a general-purpose programming language created by Bjarne
Stroustrup as an extension of the C programming language, or
"C with Classes".
//as you can also see to your right ---------------------->
C++ still qualifies as a high-level languge, yet the rise of
languages like Ruby and Java have given capabilities that sway
people's opinion towards what is and is not "high-level".
Yet high-level simply means it's farther from machine code and closer
to human-readable form. Hence the need for a compiler/interpreter.
So don't get too worked up about granular specifics.
/* :: is the scope resolution operator
*
* It allows to access objects outside of their scope, e.g to implement
* a function of a class from outside the class
*/
class foo { // define class named foo
public:
foo(); // constructor
void bar(); // function
};
foo::foo()
{
// Implement the constructor from outside the class
}
void foo::bar()
{
// Implement bar from outside the class
}
void bar()
{
// Implement different bar which is not within the same scope
}
The Conditional (or Ternary) Operator (?:)
(expression 1) ? expression 2 : expression 3
If expression 1 evaluates to true, then expression 2 is evaluated.
If expression 1 evaluates to false, then expression 3 is evaluated instead.
// ternary operator checks if
// marks is greater than 40
int marks = 50;
string result = (marks >= 40) ? "passed" : "failed";
// result = "passed"
// BASIC C++ HELLO WORLD
// This is to include the needed library for basic programming in c++
#include <iostream>
// Getting rid of the need to use std::
using namespace std;
// Main Function
int main() {
// Cout is like print, << is used for sending the text to the cout.
//
is for new line.
cout << "Hello World
";
}
Abandon all hope ye who enter here. C++ is one of the most powerful programming languages.
And one of the hardest to learn.
C++ is a subset of C. All C files are C++ files but not all C++ files are C files.
It got its name form the increment operator as it's an incremented (upgraded) version of C.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
List<Fish> fishes = new List<Fish>()
{
new Fish(1, FishType.A),
new Fish(1, FishType.B),
new Fish(1, FishType.A)
};
Fish mainFish = new Fish(2, FishType.A);
mainFish.Eat(fishes);
Console.WriteLine(mainFish);
}
}
class Fish
{
public int Length { get; private set; }
public FishType Type { get; private set; }
public Fish(int length, FishType type)
{
Length = length;
Type = type;
}
public void Eat(List<Fish> fishes)
{
if (Type == FishType.B)
return;
foreach (Fish fish in fishes)
{
if (fish.Type == FishType.A && fish.Length < Length
|| fish.Type == FishType.B)
{
Length += fish.Length;
fishes.Remove(fish);
break;
}
}
}
public override string ToString()
{
return $"Length: {Length}, Type; {Type.ToString()}";
}
}
public enum FishType
{
A,
B
}
}
// wellcome to hell
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
// C++ program for the coloring the
// background and text with
// different color
#include <iostream>
// Header file to change color of
// text and background
#include <windows.h>
using namespace std;
// Driver Code
int main()
{
// Color of the console
HANDLE console_color;
console_color = GetStdHandle(
STD_OUTPUT_HANDLE);
// Print different colors from 1
// to 50 on the output screen
for (int P = 1; P < 50; P++) {
// P is color code of the
// corresponding color
SetConsoleTextAttribute(
console_color, P);
// Print Statement
cout << P << " Hello Geeks, "
<< "good night!!!";
}
return 0;
}
If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
#include<stdio.h>
#include<math.h>
int main()
{
int p,i,x,n,n1,n2,n3,n4,n5,n6,n7,n8;
i=0;
x=0;
n1=0;
do
{
printf("entrez une valeur positive: ");
scanf("%d",&n);
if (n>0)
x=x+1,
i=n;
do
{
p=10pow(i);
n1=n1*;
i=i-1;
}
while (i>0);
}
while (x<8);
}
//C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for creating large-scale applications. C++ is a superset of the C language.
//A related programming language, Java, is based on C++ but optimized for the distribution of program objects in a network such as the Internet. Java is somewhat simpler and easier to learn than C++ and has characteristics that give it other advantages over C++. However, both languages require a considerable amount of study.
//source: techtarget
def numero(numero):
contador = 0
for i in range(1, numero + 1):
if i == 1 or i == numero:
continue
if numero % i == 0:
contador += 1
if contador == 0:
return True
else:
return False
def run():
numero = int(input("indica un numero: "))
if es_primo == 0:
print("es primo")
else:
print("no es primo")
if __name__=='main':
run()```
#include <iostream>
using namespace std;
int main() {
// initialize an array without specifying size
int numbers[] = {7, 5, 6, 12, 35, 27};
cout << "The even numbers are: ";
// print array elements
// use of range-based for loop
for (auto i : numbers) {
if(numbers[i] % 2 == 0)
{
cout << numbers[i] << ", " << endl;
}
}
#include<iostream>
#include<algorithm>
using namespace std;
int binarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int mid = (start + (end - start) /2); //lấy vị trí giữa nhất của mảng
if(array[mid] == key)// tìm thấy thì trả về vị trí
return mid;
if(array[mid] > key)// không tìm thấy thì kiểm tra bên trái
return binarySearch(array, start, mid-1, key);
// không có bên trái thì tìm kiếm bên phải
return binarySearch(array, mid+1, end, key);
}
return -1;
}
int main() {
int n, searchKey, loc;
// cout<<"Hello T-Town";
cout << "nhập n: ";
cin >> n;
int arr[n];
cout << "Phần tử mảng: " << endl;
for(int i = 0; i< n; i++) {
cin >> arr[i];
}
cout << "Phần tử cần tìm kiếm: ";
cin >> searchKey;
// sắp xếp
sort(arr,arr+n-1);
// tìm kiếm
if((loc = binarySearch(arr, 0, n, searchKey)) >= 0)
cout << "Tồn tại ở vị trí: " << loc << endl;
else
cout << "Không tồn tại phần tử" << endl;
}
#include <iostream>
using namespace std;
int main()
{
long long n;
cin>>n;
int a[n];
int i;
for(i=0;i<n;i++){
cin>>a[i];
}
int cem=0;
for(i=0;i<n;i++){
cem=cem+a[i];
}
int cem1=(n*(n+1))/2;
cout<<cem1-cem;
}
#include<iostream>#include<fstream>#include<iomanip>using namespace std;// the class that stores dataclass student{int rollno;char name[50];int eng_marks, math_marks, sci_marks, lang2_marks, cs_marks;double average;char grade;public:void getdata();void showdata() const;void calculate();int retrollno() const;}; //class ends herevoid student::calculate(){average=(eng_marks+math_marks+sci_marks+lang2_marks+cs_marks)/5.0;if(average>=90)grade='A';else if(average>=75)grade='B';else if(average>=50)grade='C';elsegrade='F';}void student::getdata(){cout<<"
Enter student's roll number: ";cin>>rollno;cout<<"
Enter student name: ";cin.ignore();cin.getline(name,50);cout<<"
All marks should be out of 100";cout<<"
Enter marks in English: ";cin>>eng_marks;cout<<"
Enter marks in Math: ";cin>>math_marks;cout<<"
Enter marks in Science: ";cin>>sci_marks;cout<<"
Enter marks in 2nd language: ";cin>>lang2_marks;cout<<"
Enter marks in Computer science: ";cin>>cs_marks;calculate();}void student::showdata() const{cout<<"
Roll number of student : "<<rollno;cout<<"
Name of student : "<<name;cout<<"
English : "<<eng_marks;cout<<"
Maths : "<<math_marks;cout<<"
Science : "<<sci_marks;cout<<"
Language2 : "<<lang2_marks;cout<<"
Computer Science :"<<cs_marks;cout<<"
Average Marks :"<<average;cout<<"
Grade of student is :"<<grade;}int student::retrollno() const{return rollno;}//function declarationvoid create_student();void display_sp(int);//display particular recordvoid display_all(); // display all recordsvoid delete_student(int);//delete particular recordvoid change_student(int);//edit particular record//MAINint main(){char ch;cout<<setprecision(2); do{char ch;int num;system("cls");cout<<"
MENU";cout<<"
1.Create student record";cout<<"
2. Search student record";cout<<"
3. Display all students records ";cout<<"
4.Delete student record";cout<<"
5.Modify student record";cout<<"
6.Exit";cout<<"
What is your Choice (1/2/3/4/5/6) ";cin>>ch;system("cls");switch(ch){case '1': create_student(); break;case '2': cout<<"
Enter The roll number "; cin>>num;display_sp(num); break;case '3': display_all(); break;case '4': cout<<"
Enter The roll number: "; cin>>num;delete_student(num);break;case '5': cout<<"
Enter The roll number "; cin>>num;change_student(num);break;case '6': cout<<"Exiting, Thank you!";exit(0);}}while(ch!='6');return 0;}//write student details to filevoid create_student(){student stud;ofstream oFile;oFile.open("student.dat",ios::binary|ios::app);stud.getdata();oFile.write(reinterpret_cast<char *> (&stud), sizeof(student));oFile.close(); cout<<"
Student record Has Been Created ";cin.ignore();cin.get();}// read file recordsvoid display_all(){student stud;ifstream inFile;inFile.open("student.dat",ios::binary);if(!inFile){cout<<"File could not be opened !! Press any Key to exit";cin.ignore();cin.get();return;}cout<<"
DISPLAYING ALL RECORDS
";while(inFile.read(reinterpret_cast<char *> (&stud), sizeof(student))){st.showdata();cout<<"
====================================
";}inFile.close();cin.ignore();cin.get();}//read specific record based on roll numbervoid display_sp(int n){student stud;ifstream iFile;iFile.open("student.dat",ios::binary);if(!iFile){cout<<"File could not be opened... Press any Key to exit";cin.ignore();cin.get();return;}bool flag=false;while(iFile.read(reinterpret_cast<char *> (&stud), sizeof(student))){if(stud.retrollno()==n){ stud.showdata();flag=true;}}iFile.close();if(flag==false)cout<<"
record does not exist";cin.ignore();cin.get();}// modify record for specified roll numbervoid change_student(int n){bool found=false;student stud;fstream fl;fl.open("student.dat",ios::binary|ios::in|ios::out);if(!fl){cout<<"File could not be opened. Press any Key to exit...";cin.ignore();cin.get();return;} while(!fl.eof() && found==false){fl.read(reinterpret_cast<char *> (&stud), sizeof(student));if(stud.retrollno()==n){stud.showdata();cout<<"
Enter new student details:"<<endl;stud.getdata(); int pos=(-1)*static_cast<int>(sizeof(stud)); fl.seekp(pos,ios::cur); fl.write(reinterpret_cast<char *> (&stud), sizeof(student)); cout<<"
Record Updated"; found=true;}}File.close();if(found==false)cout<<"
Record Not Found ";cin.ignore();cin.get();}//delete record with particular roll numbervoid delete_student(int n){student stud;ifstream iFile;iFile.open("student.dat",ios::binary);if(!iFile){cout<<"File could not be opened... Press any Key to exit...";cin.ignore();cin.get();return;}ofstream oFile;oFile.open("Temp.dat",ios::out);iFile.seekg(0,ios::beg);while(iFile.read(reinterpret_cast<char *> (&stud), sizeof(student))){if(stud.retrollno()!=n){oFile.write(reinterpret_cast<char *> (&stud), sizeof(student));}}oFile.close();iFile.close();remove("student.dat");rename("Temp.dat","student.dat");cout<<"
Record Deleted ..";cin.ignore();cin.get();}
include<iostream>
class Date
{
public:
int Month;
int Day;
int Year;
void SetDate(int nDay,int nMonth,int nYear)
{
Day='nDAY';
Month= nMonth;
Year= nYear;
}
void ShowDate()
{
void ShowDate()
cout<<"Day of Birth:"<<Day<<endl;
cout<<"Month of birth:"<<Month<<endl;
cout<<"Year of birth:"<<Year;
}
};
int main()
{
Date d1;//Object creation
d1.SetDate(21,07,2010);//call to SetDate function
d1.ShowDate();//call to ShowDate function
d1.ShowDate();//call to ShowDate function
getch();
return 0;
}
Create class name student. The student class have name, address and average as a data members. The class have the following member functions:
Parametrized constructor to initialize data members of the class for five students. // array of objects
Member function Print () to print the student information in ascending order according to average field.
Write a main program to invoke member functions
Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Constraints:
0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000
// Test_TP_Programmation C++ (En utilisant la boucle While)
#include <iostream>
using namespace std;
int main()
{
int N,i,j;
cout<<"==> Taper un valeur entier 'N>3' = "; cin>>N;
// boucle pour vérifié N doit etre supérieur à 3.
while (N<3){
cout<<"==> Taper un valeur entier 'N>3' = "; cin>>N;
} cout<<endl;
// boucle pour créer les lignes de votre choix N.
i=1;
while (i<=N){
// boucle pour créer l'éspace.
j=1;
while (j<=N-i){
cout<<" ";
j++;}
// boucle créer un cadre en (*) et à l'intérieur en (+).
j=1;
while (j<=(2*i-1)){
if (i==N || j==1 || j==(2*i-1))
cout<<"*";
else
cout<<"+";
j++;}
cout<<endl;
i++;
} return 0;
} // Khaled Mouhoubi G2 - D.AbdeLaziz Daas
// C++ program for reversal algorithm
// of array rotation
#include <bits/stdc++.h>
using namespace std;
/*Function to reverse arr[] from index start to end*/
void reverseArray(int arr[], int start, int end)
{
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Function to left rotate arr[] of size n by d */
void leftRotate(int arr[], int d, int n)
{
if (d == 0)
return;
// in case the rotating factor is
// greater than array length
d = d % n;
reverseArray(arr, 0, d - 1);
reverseArray(arr, d, n - 1);
reverseArray(arr, 0, n - 1);
}
// Function to print an array
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
/* Driver program to test above functions */
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int d = 2;
// Function calling
leftRotate(arr, d, n);
printArray(arr, n);
return 0;
}