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
*/classfoo{// define class named foopublic:foo();// constructorvoidbar();// function};
foo::foo(){// Implement the constructor from outside the class}void foo::bar(){// Implement bar from outside the class}voidbar(){// 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 40int marks =50;
string result =(marks >=40)?"passed":"failed";// result = "passed"
#include<iostream>#include<fstream>#include<string>usingnamespace std;intmain(){
string constnomFichier("C:/Nanoc/scores.txt");
ofstream monFlux(nomFichier.c_str());if(monFlux){
monFlux <<"Bonjour, je suis une phrase écrite dans un fichier."<< endl;
monFlux <<42.1337<< endl;intage(36);
monFlux <<"J'ai "<< age <<" ans."<< endl;}else{
cout <<"ERREUR: Impossible d'ouvrir le fichier."<< endl;}return0;}
// 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::usingnamespace std;// Main Functionintmain(){// Cout is like print, << is used for sending the text to the cout.//
is fornew 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.
#include<iostream>usingnamespace std;intmain(void){
cout <<"Welcom to this small calulator.";
cout <<"/n";
cout <<"-----------------------------";
cout <<"/n";
cout <<"please,";
cout <<"/n";
cout <<"Enter your first number : ";
cin >> n ;
cout <<"/n";
cout <<"-------- Menu--------"<<endl;
cout <<"1. For Addition. "<<endl;
cout <<"2. For Substraction."<<endl;
cout <<"3. For Multiplication."<<endl;
cout <<"4. For Division."<<endl;
cout <<"---------------------"<<endl;
cin >> s ;
cout <<"/n";
cout <<"Enter your second number: ";
cin >> r;
cout <<"/n";switch s {case(1):
t = n+r ;return0;}
// wellcome to hellclassMyClass{// The classpublic:// Access specifiervoidmyMethod(){// Method/function defined inside the class
cout <<"Hello World!";}};intmain(){
MyClass myObj;// Create an object of MyClass
myObj.myMethod();// Call the methodreturn0;}
#include<iostream>usingnamespace std;intmain(void){
cout <<"Welcom to this small calulator.";
cout <<"/n";
cout <<"-----------------------------";
cout <<"/n";
cout <<"please,";
cout <<"/n";
cout <<"Enter your first number : ";
cin >> n ;
cout <<"/n";
cout <<"-------- Menu--------"<<endl;
cout <<"1. For Addition. "<<endl;
cout <<"2. For Substraction."<<endl;
cout <<"3. For Multiplication."<<endl;
cout <<"4. For Division."<<endl;
cout <<"---------------------"<<endl;
cin >> s ;
cout <<"/n";
cout <<"Enter your second number: ";
cin >> r;
cout <<"/n";switch s {case(1):
t = n+r ;return0;}
// 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>usingnamespace std;// Driver Codeintmain(){// Color of the console
HANDLE console_color;
console_color =GetStdHandle(
STD_OUTPUT_HANDLE);// Print different colors from 1// to 50 on the output screenfor(int P =1; P <50; P++){// P is color code of the// corresponding colorSetConsoleTextAttribute(
console_color, P);// Print Statement
cout << P <<" Hello Geeks, "<<"good night!!!";}return0;}
If root ==NULLreturnNULL;
If number == root->data
return root->data;
If number < root->data
returnsearch(root->left)
If number > root->data
returnsearch(root->right)
//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 =0for i in range(1, numero +1):if i ==1or i == numero:continueif numero % i ==0:
contador +=1if 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>usingnamespace std;intmain(){// initialize an array without specifying sizeint numbers[]={7,5,6,12,35,27};
cout <<"The even numbers are: ";// print array elements// use of range-based for loopfor(auto i : numbers){if(numbers[i]%2==0){
cout << numbers[i]<<", "<< endl;}}
#include<iostream>#include<algorithm>usingnamespace std;intbinarySearch(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ảngif(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áireturnbinarySearch(array, start, mid-1, key);// không có bên trái thì tìm kiếm bên phảireturnbinarySearch(array, mid+1, end, key);}return-1;}intmain(){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ếpsort(arr,arr+n-1);// tìm kiếmif((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>#include<fstream>#include<iomanip>usingnamespace 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>classDate{public:int Month;int Day;int Year;voidSetDate(int nDay,int nMonth,int nYear){
Day='nDAY';
Month= nMonth;
Year= nYear;}voidShowDate(){voidShowDate()
cout<<"Day of Birth:"<<Day<<endl;
cout<<"Month of birth:"<<Month<<endl;
cout<<"Year of birth:"<<Year;}};intmain(){
Date d1;//Object creation
d1.SetDate(21,07,2010);//call to SetDate function
d1.ShowDate();//call to ShowDate function
d1.ShowDate();//call to ShowDate functiongetch();return0;}
Create classname student. The student classhave name, address and average as a data members. The classhave the following member functions:
Parametrized constructor to initialize data members of the classfor 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 <=1000<= prices.length <=10000<= prices[i]<=1000
// Test_TP_Programmation C++ (En utilisant la boucle While)#include<iostream>usingnamespace std;intmain(){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++;}return0;}// Khaled Mouhoubi G2 - D.AbdeLaziz Daas
// C++ program for reversal algorithm// of array rotation#include<bits/stdc++.h>usingnamespace std;/*Function to reverse arr[] from index start to end*/voidreverseArray(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 */voidleftRotate(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 arrayvoidprintArray(int arr[],int size){for(int i =0; i < size; i++)
cout << arr[i]<<" ";}/* Driver program to test above functions */intmain(){int arr[]={1,2,3,4,5,6,7};int n =sizeof(arr)/sizeof(arr[0]);int d =2;// Function callingleftRotate(arr, d, n);printArray(arr, n);return0;}