Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Using printf() and scanf() in C++

cpp

#include <stdio.h>
#include <iostream>


int main(){
    char firstName[20];
    char crush[20];
    int numberOfBabies;
    
    printf("What is your name? \n")<
    scanf("%s", firstName);
    
    printf("Who are you going to marry? \n")<
    scanf("%s", crush);
    
    printf("How many kids will you have? \n")<
    scanf("%d", &numberOfBabies);
    //& and is used before every varible like int numberOfBabies(int, float, char, integer, always want to put & before variable name, or program will crash basically, except arrays i.e. char firstName[20], 
    
        printf("%s and %s are in love and will have %d babies",firstName, crush, numberOfBabies);
        
    
    return 0;
}

Ostringstream in C++

cpp

#include <iostream>
#include <locale>
#include <iomanip>


using namespace std;

int main()
{
   cout << "Hello World" << endl; 
   ostringstream oss;
    
   
   oss.imbue(std::locale("Something you dont have"));
    
   
    oss << std::fixed << std::setprecision(0);
    oss << 1000000;
    cout << "Value was : " << oss.str() << endl;
   
   return 0;
}

Print a part of string using C++

cpp

#include<iostream>
using namespace std;
class Demo {
   string text;
public:
   Demo(const string& name)
   :text(name)
   {}
   const char& operator[] (size_t pos) const
   //char& operator[] (size_t pos) const
   {return text[pos];}
   char& operator[] (size_t pos)
   {return text[pos+1];}
};
void print(Demo& cdemo)
{ cout << cdemo[0]; }
void print_const(const Demo& cdemo)
{ cout << cdemo[0]; }
int main() {
   Demo Test("Test");
   print(Test);
   print_const(Test);
   return 0;
}

DFS for directed graphs using C++

cpp

//
// Created by Himanshu Singh on 2019-04-09.
//
// DFS for directed graphs
// BPW, 4/2003

#include <stdio.h>
#include <stdlib.h>

#define WHITE 0
#define GRAY 1
#define BLACK 2

#define TREE 0
#define BACK 1
#define CROSS 2
#define FORWARD 3

int n;  // number of nodes
int e;  // number of edges
struct edge {
    int tail,head,type,flow;
};
typedef struct edge edgeType;
edgeType *edgeTab;
int *firstEdge;  // Table indicating first in range of edges with a common tail

int *discovery,*finish,*predecessor,*vertexStatus;

int minFlowInCycle=1000000, numberOfVerticesInCycle = 0, cycleStartVertex=0;
edgeType cancelledEdge;
bool cycleFound = false;
int edgeCreatingCycle=-1;

// Reading the input file and organize adjacency lists

int tailThenHead(const void* xin, const void* yin)
// Used in calls to qsort() and bsearch() for read_input_file()
{
    int result;
    edgeType *x,*y;

    x=(edgeType*) xin;
    y=(edgeType*) yin;
    result=x->tail - y->tail;
    if (result!=0)
        return result;
    else
        return x->head - y->head;
}

void read_input_file()
{
    int a,b,i,j,f;
    edgeType work;
    edgeType *ptr;

    scanf("%d %d",&n,&e);
    edgeTab=(edgeType*) malloc(e*sizeof(edgeType));
    if (!edgeTab)
    {
        printf("edgeTab malloc failed %d\n",__LINE__);
        exit(0);
    }

    for (i=0; i<e; i++)
    {
        scanf("%d %d %d",&a,&b,&f);
        if (a<0 || a>=n || b<0 || b>=n)
        {
            printf("Invalid input %d %d at %d\n",a,b,__LINE__);
            exit(0);
        }
        edgeTab[i].tail=a;
        edgeTab[i].head=b;
        edgeTab[i].flow=f;
    }

// sort edges
    qsort(edgeTab,e,sizeof(edgeType),tailThenHead);

// Coalesce duplicates into a single edge
    j=0;
    for (i=1; i<e; i++)
        if (edgeTab[j].tail==edgeTab[i].tail
            && edgeTab[j].head==edgeTab[i].head)
            ;
        else
        {
            j++;
            edgeTab[j].tail=edgeTab[i].tail;
            edgeTab[j].head=edgeTab[i].head;
        }
    e=j+1;

// For each vertex as a tail, determine first in range of edgeTab entries
    firstEdge=(int*) malloc((n+1)*sizeof(int));
    if (!firstEdge)
    {
        printf("malloc failed %d\n",__LINE__);
        exit(0);
    }
    j=0;
    for (i=0; i<n; i++)
    {
        firstEdge[i]=j;
        for ( ;
                j<e && edgeTab[j].tail==i;
                j++)
            ;
    }
    firstEdge[n]=e;
}

void removeCycle(int u){
    if(u==-1)
        return;
    int p;
 int head=edgeTab[u].head;//4    14 4 14
 int tail=edgeTab[u].tail;//14
 int minFlow=10000000000;
 int k=predecessor[tail];

 int* path=(int*) malloc(n*sizeof(int));
 int j=0;
 path[j++]=u;int minflowEdge=0;
    while(head!=tail){
     for(p=firstEdge[k];p<firstEdge[k+1];p++){
         edge e=edgeTab[p];
         if(tail==edgeTab[p].head && edgeTab[p].flow>0){
             e=edgeTab[p];
             //minFlow= minFlow>e.flow ? e.flow : minFlow;
             if(minFlow>=e.flow){
                 minFlow=e.flow;
                 minflowEdge=p;
             }
             k=predecessor[e.tail];
             path[j++]=p;
             tail=e.tail;

             break;
         }
     }
 }



 for(int i=0;i<j;i++){
    // printf("%d<=",edgeTab[path[i]].tail);
     edgeTab[path[i]].flow-=minFlow;
 }
 //printf("    min flow %d\n",minFlow);
 printf("Cancel cycle of %d vertices, limiting edge %d->%d has flow %d\n",j,edgeTab[minflowEdge].tail,edgeTab[minflowEdge].head,minFlow);
 free(path);

}




int time;  /*Keeps node numbering*/
bool b= false;
void DFSvisit(int u)
{
    int i,v;

    vertexStatus[u]=GRAY;
    time++;
    discovery[u]=time;

    for (i=firstEdge[u];i<firstEdge[u+1];i++)
    {
        if(cycleFound)
            return;
        if (edgeTab[i].flow == 0)
            continue;
        v=edgeTab[i].head;
        if (vertexStatus[v]==WHITE )
        {
            edgeTab[i].type=TREE;
            predecessor[v]=u;
            DFSvisit(v);
        }
        else if (vertexStatus[v]==GRAY){
            edgeTab[i].type=BACK;
            cycleFound = true;
            edgeCreatingCycle = i;
            cycleStartVertex=edgeTab[i].head;
            return;
        }
        else if (discovery[u]<discovery[v])
            edgeTab[i].type=FORWARD;
        else
            edgeTab[i].type=CROSS;
    }
    vertexStatus[u]=BLACK;
    time++;
    finish[u]=time;
    b= false;
}
/////final


void RemoveCycle1(int parentIndex) {
    if(parentIndex==0)
        return;
    numberOfVerticesInCycle++;
    int foundParentIndex = 0;
    if (edgeTab[parentIndex].flow < minFlowInCycle) {
        minFlowInCycle = edgeTab[parentIndex].flow;
        cancelledEdge = edgeTab[parentIndex];
    }
    if (edgeTab[parentIndex].tail == cycleStartVertex) {
        edgeTab[parentIndex].flow = edgeTab[parentIndex].flow - minFlowInCycle;
        printf("ss\n");
        return;
    }
    for (int i = 0; i < e; i++)
    {
        if ((edgeTab[i].type == FORWARD || edgeTab[i].type == TREE || edgeTab[i].type == CROSS || edgeTab[i].type == BACK)
            && edgeTab[parentIndex].tail == edgeTab[i].head && edgeTab[i].flow > 0) {
            foundParentIndex = i;
            printf("%d<=",edgeTab[i].head);
            break;
        }
        /*if (edge.tail == edgeTab[i].head)
            parentIndex = i;*/
    }
    RemoveCycle1(foundParentIndex);
    edgeTab[parentIndex].flow = edgeTab[parentIndex].flow - minFlowInCycle;

    ////int edgeWithMinFlow;
    //int cycleStartVertex = edgeTab[edgeCreatingCycle].head;
    ////int cycleEndVertex = edgeTab[edgeCreatingCycle].tail;
    //int minFlowInCycle = edgeTab[edgeCreatingCycle].flow;
    //std::vector<int> edgeTabIndices;

    //for (auto iter = visitedEdgeTab.rbegin(); iter != visitedEdgeTab.rend(); ++iter)
    //{
    //	edgeTabIndices.push_back(iter->first);
    //	if (iter->second.flow < minFlowInCycle)
    //		minFlowInCycle = iter->second.flow;
    //	if (cycleStartVertex == iter->second.tail)
    //		break;
    //}
}



//int minFlowInCycle, numberOfVerticesInCycle = 0, cycleStartVertex;
//edgeType cancelledEdge;

void DFSvisit1(int u)
{
    int i, v;

    vertexStatus[u] = GRAY;
    time++;
    discovery[u] = time;

    for (i = firstEdge[u]; i < firstEdge[u + 1]; i++)
    {
        if (cycleFound)
            return;
        if (edgeTab[i].flow == 0)
            continue;
        v = edgeTab[i].head;
        if (vertexStatus[v] == WHITE)
        {
            edgeTab[i].type = TREE;
            predecessor[v] = u;
            DFSvisit1(v);
        }
        else if (vertexStatus[v] == GRAY) {
            edgeTab[i].type = BACK;
            cycleFound = true;
            edgeCreatingCycle = i;
            cycleStartVertex=edgeTab[i].head;
            return;
        }
        else if (discovery[u] < discovery[v])
            edgeTab[i].type = FORWARD;
        else
            edgeTab[i].type = CROSS;
    }
    vertexStatus[u] = BLACK;
    time++;
    finish[u] = time;
}

/////end final

int main ()
{
    int u,i,j,k,nextDFS;

    read_input_file();
    discovery=(int*) malloc(n*sizeof(int));
    finish=(int*) malloc(n*sizeof(int));
    predecessor=(int*) malloc(n*sizeof(int));
    vertexStatus=(int*) malloc(n*sizeof(int));
    if (!discovery || !finish || !predecessor ||!vertexStatus)
    {
        printf("malloc failed\n");
        exit(0);
    }
// DFS code
    int p=0;
    do{
        removeCycle(edgeCreatingCycle);
        cycleFound= false;
    for (u=0;u<n;u++)
    {
        vertexStatus[u]=WHITE;
        predecessor[u]=(-1);
    }
    time=0;
    for (u=0;u<n;u++)
        if (vertexStatus[u]==WHITE){
            DFSvisit(u);
            if(cycleFound)
                break;

        }
    }while (cycleFound);


//Output code
    printf("Vertex  discovery    finish     predecessor\n");
    for (i=0;i<n;i++)
        printf(" %3d      %3d         %3d       %3d\n",i,
               discovery[i],finish[i],predecessor[i]);
    printf("Edge Tail Head flow Type\n");
    for (i=0;i<e;i++)
    {
        printf(" %3d  %3d  %3d  %3d",i,edgeTab[i].tail,edgeTab[i].head,edgeTab[i].flow);
        switch(edgeTab[i].type)
        {
            case TREE:    printf("     tree\n"); break;
            case BACK:    printf("     back\n"); break;
            case CROSS:   printf("     cross\n"); break;
            case FORWARD: printf("     forward\n"); break;
        }
    }

    free(edgeTab);
    free(firstEdge);
    free(discovery);
    free(finish);
    free(predecessor);
    free(vertexStatus);
    return 0;
}

Implicit vs explicit Calls in C++

cpp

#include <iostream>

using namespace std;

class Test
{
  int a;
  public:
  void get(int x)
  {
      a = x;
  }
  void display(Test t)
  {
      //display caller object data "implecit call"
      cout << "t1.a = " << this->a << endl;
      //or
      cout << "t1.a = " << a << endl;
      
      //display argument object "explicit"
      cout << "t2.a = " << t.a << endl;
  }
};

int main()
{
    Test t1, t2;
    t1.get(15);
    t2.get(20);
    
    t1.display(t2);
    
    return 0;
}

leftStart() and rightStart() functions in C++

cpp

#include <iostream>

using namespace std;

int leftStart();
int rightStart();

int main()
{
   cout << "Expression: (x += 1) + (y - x)" << endl; 
   cout << "x = 1" << endl;
   cout << "y = 2" << endl;
   leftStart();
   rightStart();
   
   return 0;
}

int leftStart() {
    int x = 1;
    int y = 2;
    int result = 0;
    result = (x += 1) + (y - x);
    cout << "Left Start: " << result << endl;
    
    return 0;
}
int rightStart() {
    int x = 1;
    int y = 2;
    int result = 0;
    result =  (y - x) + (x += 1);
    cout << "Right Start: " << result << endl;
    
    return 0;
}

gradinaJaponeza

cpp

#include<iostream>

using namespace std;

int xv[20], yv[20];
int l,h,n,xf,yf,lf,hf, aria;

void Citire() {
    int i;
    cout<<"numarul de pietre: "; cin>>n; cout<<n<<endl;
    cout<<"coordonatele pietrelor: "<<endl<<endl;
    for(i=1; i<=n; i++){
        cout<<"piatra cu numarul "<<i<<" :"<<endl;
        cout<<"  xv: "; cin>>xv[i]; cout<<xv[i]<<endl;
        cout<<"  yv: "; cin>>yv[i]; cout<<yv[i]<<endl;
        cout<<endl;
    }
    cout<<"lungimea gradinii: "; cin>>l; cout<<l<<endl;
    cout<<"latimea gradinii:  "; cin>>h; cout<<h<<endl;
    cout<<endl;
}

void caut(int x,int y,int l,int h,int& xf,int& yf,int& lf,int& hf) {
    int gasit=0,i=1;
    while(i<=n && !gasit)
       if(xv[i]>x && xv[i]<x+l && yv[i]>y && yv[i]<y+h) gasit=1;
       else i++;
    if(gasit) {
        caut(x,y,xv[i]-x,h,xf,yf,lf,hf);
        caut(xv[i],y,l+x-xv[i],h,xf,yf,lf,hf);
        caut(x,y,l,yv[i]-y,xf,yf,lf,hf);
        caut(x,yv[i],l,h+y-yv[i],xf,yf,lf,hf);
    }
    else
        if(l*h>lf*hf) {  xf=x; yf=y; lf=l; hf=h; }
}

int main()
{
   Citire();
   lf=0; hf=0;
   caut(0,0,l,h,xf,yf,lf,hf);
   aria=(lf-xf)*(hf-yf);
   cout<<"bucata de arie maxima are coordonatele:  "<<"xf="<<xf<<"  yf="<<yf<<"  lf="<<lf<<"  hf="<<hf<<"    si aria="<<aria<<endl<<endl;
   return 0;
}

Compile and Execute C++ Online

cpp

#include <iostream>

using namespace std;

int empty (int a[], int n){
    for (int i=0;i<n;i++){
        if (a[i]==0){
            return 1;
        }
    }
    return 0;
}

int sum(int a[], int n) {
    int d=0;
    for(int i=0;i<n;i++){
        d = d + a[i];
    }
    return d;
}

int min(int a, int b){
    if (a<b) return a;
    else return b;
}

int main()
{
 int N, k, m=10000, i=0, j=0;
 cin >> N >> k;
 int kordela[N]={0}, counter[k]={0};
 for (i=0;i<N;i++){
     cin >> kordela[i];
 }
 
 while (i<N && j<N) {
     counter[kordela[j]]++;
     if (empty(counter,k)==0){
        counter[kordela[i]]--;
        m = min(m,j+1-i);
        i++;
     }
     else {
        if (j<N-1) j++;
     }
 }
 
 cout << "number = " << m << endl;
 
   
   return 0;
}

Jaswinder Singh

cpp

#include <iostream>
 
using namespace std;
 
class Box {
   double width;
   
   public:
      friend void printWidth( Box box );
      void setWidth( double wid );
};

// Member function definition
void Box::setWidth( double wid ) {
   width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
   /* Because printWidth() is a friend of Box, it can
   directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}
 
// Main function for the program
int main() {
   Box box;
 
   // set box width without member function
   box.setWidth(10.0);
   
   // Use friend function to print the wdith.
   printWidth( box );
 
   return 0;
}

Chapter 1

cpp

#include <iostream> // for std::cout
 
int main()
{
    std::cout << "Hello world!"; // print Hello world! to console
    std::cout << "Hi!";
    std::cout << "My name is Alex.";
    std::cout << "Hi!" << std::endl; 
    std::cout << "My name is Alex." << std::endl;
     int x{ 5 };
    std::cout << "x is equal to: " << x << '\n'; 
    std::cout << "And that's all, folks!\n";
    return 0;


 
 
    return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.