Click here to Skip to main content
15,074,377 members
Please Sign up or sign in to vote.
1.17/5 (6 votes)
See more:
This is my Code C++ for my assignment. Please help me to convert it to C code. Thank you!

What I have tried:

C++
#include<iostream>
using namespace std;
#define N 10

int main()
{
	int array[N],p,q;
	for(int i=0;i<N;i++)
	  array[i]=i;
	cout<<"For instance, given elements are ";
	for(int i=0;i<N;i++)
	  cout<<array[i];
	cout<<endl;
	int r=0;
	while(cin>>p)
	{
	 cin>>q;
	 if(p>=0 && p<N)
   {
   	for(int i=0;i<N;i++)
   	 if(array[i]==p)
   	   array[i]=q;
	  cout<<p<<" "<<q<<"  "<<r++<<"     ";
	  for(int i=0;i<N;i++)
	    cout<<array[i];
	  cout<<"\n";
   }
  }
}
Posted
Updated 25-Jun-21 0:26am
v3

You need to change your I/O code, so use printf and scanf functions.

Tip: visit some tutorial to learn the basics.
   
Comments
CPallini 21-Oct-20 5:50am
   
5
It's fairly close to C already, apart from the I/O. No one here will do it for you; you need to research it yourself. But I'll give you a hint. Remove
#include <iostream>
using namespace std;
and replace it with
#include <stdio.h>
Then find some documentation for stdio.h and decide how to fix the things that no longer compile now that iostream is gone.
   
Comments
CPallini 21-Oct-20 5:50am
   
5
Here is the converted code, using printf and scanf to replace C++'s cout and cin respectively.

C++
#include <stdio.h>

#define N 10

int main()
{
    int array[N], p, q;
    for (int i = 0; i < N; i++)
        array[i] = i;

    printf("For instance, given elements are ");
    for (int i = 0; i < N; i++)
        printf("%d ", array[i]);
    printf("\n");
    int r = 0;
    scanf("%d", &p);
    while (p>0)
    {
        scanf("%d", &q);
        if (p >= 0 && p < N)
        {
            for (int i = 0; i < N; i++)
                if (array[i] == p)
                    array[i] = q;


            printf("\n%d %d\n", p, q);
            for (int i = 0; i < N; i++)
                printf("%d ", array[i]);
            printf("\n");
        }
    }
    return 0;
}
   
v2
Comments
CPallini 21-Oct-20 5:51am
   
5
Shao Voon Wong 21-Oct-20 7:13am
   
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900