How should C/C++ be coded in competitive programming?
In this article, I will introduce the basics of coding in C/C++ so that you can better understand what it takes to be competitive with other programmers. It will help you to learn how to write efficient C/C++ code in competitive programming.
Introduction
C++ is a powerful and complex programming language. It is used to create games, apps and other software. However, it has unique features that make it difficult for beginners to understand how they should write efficient C/C++ code in competitive programming.
What are C and C++?
C and C++ are programming languages that are used for low-level programming, high-level programming and embedded systems programming. They can be used to code system software like operating systems or web servers as well.
C and C++ are the same programming languages with some minor differences. The syntax is similar, but there are some differences in their usage.
The most common use of C and C++ is in application software. Application software is software that performs tasks, such as managing databases or word processing.
Competitive programming: writing C/C++ code
These are some pieces of advice. that will helps to improve your C/C++ code in competitive programming.
- Use the standard library.
- Use a debugger, profiler and testing framework.
- Code coverage tools can be used to determine how often your code is executed in your tests, which can help you decide if there are parts of your program that need more work or should be refactored into another function.
It’s important to use a debugger and profiler when writing code. A debugger allows you to step through your program line-by-line and see what is happening in real-time, which can help identify bugs or potential issues. A profiler lets you track down performance issues by showing how much time is spent on each function call or section of code.
Let’s see some basics
Template
This is a programming technique that saves time and space by allowing the same code to be used for many different types of data. They are used to create classes that can be used multiple times. It also prevents code duplication by allowing the same class definition to be used for different types of data.
The best way to improve the performance of your code is by using templates. Templates allow you to create functions without having to write separate versions for each data type.
Macros
Macros are defined in a file, which is called a macro definition file. The macro definition file must be included in the source code file where you want to use it. You can also define macros in header files and link them with your source files or libraries.
You can also use macros in C++ because they are faster than functions when compiling time is short but slower when compiling time is long.
Macros are not functions and cannot be called directly; instead, they define constants or shorthand expressions that can be used within other C/C++ programs without having to rewrite them again every time you change something about them (e.g. their size).
For example, if you want to define a constant for the maximum number of elements in an array (which is usually 2^31 on 32-bit systems and 2^63 on 64-bit systems), you could do this: #define MAX_ELEMS 63
#include <bits/stdc++.h>
using namespace std;
#define MAX_ELEMS 63
int main() {
int minElement = MAX_ELEMS;
int arr[6] = [7,5,10,23,2,8];
for(int i = 0; i < 6; i++){
if(minElement > arr[i]){
minElement = arr[i];
};
}
cout<<" minimum element: "<<minElement;
return 0;
}
Code language: C++ (cpp)
Output
minElement: 2
Code language: C++ (cpp)
Template and Macro both are used to avoid repetitious code or to create a new language. The templates are preprocessor macros that allow you to create code that will work with many different types of data.
Vectors
A vector is a data container that stores multiple values of the same type. C/C++ provides a number of functions for working with vectors, including:
- a function for pushing a single value into a vector (push_back())
- a function for popping the last item off of a vector (pop_back())
Let’s see some basic code updates that can increase efficiency
You can use the following code to improve efficiency:
- Use a faster input/output method (e.g. std::cout instead of
cout
) - Assigning variables with the maximum and minimum value for each loop
- Creating range-based loops by using begin() and end() functions
- Using proper header files
Using a faster input/output method is C/C++
- Use std::cout to print
- Use std::cin to read
- Use std::cin.ignore() to ignore input
The most popular method is to use std::court
. The first part of this statement is the stream, which can be either cout
or wcout
depending on whether you want to print it to the screen or save it as a file. The second part is the format string, which tells C/C++ how you want your data printed out.
Assigning variables with the maximum and minimum value
You should assign variables with maximum and minimum values.
You also can use for
loops to assign the maximum and minimum values of a list, like this:
#include <iostream>
using namespace std;
int main() {
int min = 0;
int max = 0;
for (int i=0; i < 10; ++i) {
if (i > max) { max = i;}
if (i < min) { min = i; }}
cout<<"minimum:- "<<min<<"\n "<<"maximum:- "<<max;
return 0;
}
Code language: C++ (cpp)
Output
minimum:- 0
maximum:- 9
Code language: C++ (cpp)
In the example above, we use a for loop to assign the maximum and minimum values of a list. The first line in this code assigns 0 to min, which is our minimum value. Then, we use an if statement to check if i is greater than max (which has not been assigned yet). If so, then we set the max equal to i
. otherwise, we set the min equal to i
.
You can also assign the maximum and minimum values by using the max()
and min()
functions.
Creating Range based loops
Range-based loops iterate through a range of values. This means that you can use them with for, while and do while loops.
Range-based loops are faster than other types of loops because they don’t have to check the condition at every step in your code; they just keep going until they reach their end value or until there is an error (if you’re using a range-based for
loop).
You can also use range-based for and while statements within another range-based statement such as a do-while statement.
//Example showing a pattern.
//Both the for loops have a particular range.
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
for (int j = 1; j <= i; j++) {
if ((i*j % 2) == 1) {
break;
}
cout<<abs(j-i)<<" ";
}
cout<<"\n";
}
return 0;
}
Code language: C++ (cpp)
Output
1 0
3 2 1 0
5 4 3 2 1 0
7 6 5 4 3 2 1 0
Code language: C++ (cpp)
Using proper header files
- Use a header file to avoid multiple definitions.
- Using a header file will help you to avoid name conflicts.
- By using a header file you can avoid code duplication.
- Use a header file to avoid code errors, for example,
int main()
should be changed toint main(void)
.
// In C++ both are the same.
// But in C -
//int main(void) - specify that function will be called without any argument.
//int main() - This function can be called with any number of arguments.
Code language: C++ (cpp)
Use containers to reduce space
If you have a container, such as a vector or a map, use it to store the data. This can reduce the amount of space needed to store your data.
For example, if you have a vector with 10 elements in it, the size of that vector is 20 bytes (10 * sizeof(int)). If you use a map instead, it uses less memory than a vector. Thus the size of this map will be 16 bytes only (10 * sizeof(int)). This implies that, If you store the data in a map and then use a vector to access it, you will only need 16 bytes of memory. This can significantly reduce the amount of space needed to store your data.
If you’re not sure which type of container to use, it is best to use a vector as it is faster than maps. But, If you need to perform memory-intensive operations on your data, such as sorting or searching through it, then use a map instead.
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector(5, 0);
// Add some elements
myVector.push_back(10);
myVector.push_back(12);
myVector.push_back(13);
for (int i = 0; i < myVector.size(); i++) {
std::cout << myVector[i] << " ";
}
std::cout << std::endl;
return 0;
}
Code language: C++ (cpp)
Output
0 0 0 0 0 10 12 13
Code language: C++ (cpp)
Examples
//An example using vector.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> names;
names.push_back("Jack");
names.push_back("John");
names.push_back("Jill");
names.push_back("Jack Smith");
cout<<"All names stored in vector names: "<<endl;
for(auto& itr : names){
cout<<itr<<endl;
}
return 0;
}
Code language: C++ (cpp)
Output
All names stored in vector names:
Jack
John
Jill
Jack Smith
Code language: C++ (cpp)
Instead of storing data in separate variables and then using them later to read from memory. Use one variable for all your data. Then you can just add more objects to it whenever you need them.
//An example using Map
#include <bits/stdc++.h>
using namespace std;
int main() {
// first declare a map
map<int,string>map;
map[1] = "hi";
map[2] = "hello";
for (auto& it : map) {
cout<<it.first<<" "<<it.second<<endl;
}
return 0;
}
Code language: C++ (cpp)
Output
1 hi
2 hello
Code language: C++ (cpp)
Conclusion
This is the end of our article. We have seen all the basic code updates that can increase efficiency in competitive programming. If you want to learn more, we would like to recommend you some books or resources for further reading C programming language.
FAQ
Is C or C++ better for competitive programming?
The answer is both. C++ is a good choice for competitive programming because it has a lot of features that make the code more efficient and stable. However, C is also a good choice because it is easier to learn than C++, and it is more widely used in competitive programming.
Is C++ good for competitive programming?
Yes, It’s a good choice for competitive programming. As C++ codes are more efficient and have faster runtime.
Can we use C or C++ in competitive programming?
Of course, They are widely used in competitive programming.
Can I use C and C++ in the same project?
Yes, you can use C and C++ in the same project. But there are some limitations. You cannot use functions from one language in another language and vice versa.
Which is the best platform for competitive coding?
For beginners, I would suggest HackerRank or HackerEarth.
Sharing is caring
Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: