How to turn this C++ code into C?

Asked

Viewed 1,792 times

0

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, i, n1, c = 0, c1, c2, max, pos, bar[501], arr[250001], j;
    cin >> n >> n1;
    max = pos = 0;

    for (i = 1; i <= n*n1; i++)
    {
        cin >> arr[i];
    }

    for (i = 1; i <= n; i++)
    {
        c = 0;
        for (j = i; j <= n1*n; j += (n))
        {
            c += arr[j];
        }

        if (max <= c)
        {
            max = c;
            pos = i;
        }

    }

    cout << pos << endl;

    return 0;
}
  • I know that cis is scan, the rest I don’t even know where it goes

  • The code is almost valid in c. The include is distinct (only needs the <stdio>), is not used namespace, impression is with printf

  • @Sopergunto Did any of the answers solve your question? Do you think you can accept one of them? See the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

3

Except for the stream this code is already C, misspelled, but it is. It was not written the way C++, although Compile.

Change cin for scanf() and cout for printf().

Don’t forget to include the stdio.h and take everything connected to stream in and out.

#include <stdio.h>
int main() {
    int n, n1, arr[250001];
    scanf("%d %d", &n, &n1);
    int max = 0;
    int pos = 0;
    for (int i = 1; i <= n * n1; i++) scanf("%d", &arr[i]);
    for (int i = 1; i <= n; i++) {
        int c = 0;
        for (int j = i; j <= n1 * n; j += n) c += arr[j];
        if (max <= c) {
            max = c;
            pos = i;
        }
    }
    printf("%d", pos);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 1

    And remove the using namespace

  • 2

    Which is connected to stream :)

1

Just swap the Cin for scanf, and the Cout for printf and remove using namespace and switch the library to stdio. h

#include <stdio.h>  // printf e scanf

int main()
{
    int n, i, n1, c = 0, c1, c2, max, pos, bar[501], arr[250001], j;
    scanf("%i%i", &n, &n1);
    max = pos = 0;

    for (i = 1; i <= n*n1; i++)
    {
        scanf("%i", &arr[i]);
    }

    for (i = 1; i <= n; i++)
    {
        c = 0;
        for (j = i; j <= n1*n; j += (n))
        {
            c += arr[j];
        }

        if (max <= c)
        {
            max = c;
            pos = i;
        }

    }

    printf("%i", pos);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.