Java Performance Tuning Tips For Programmers

Java Performance Tuning Tips For Programmers 2018. Want to make your project always high-performance operation? Here Coding compiler sharing some tips you can take to eliminate cache bottlenecks, as well as some other performance tuning suggestions. All the best and happy learning.

Java Performance Tuning

Most developers think that performance optimization is a complex topic that requires a lot of work experience and related knowledge theory. Well, this is not completely wrong. Optimizing an application for performance optimization may not be an easy task, but that does not mean you can not do anything without knowledge.

Java Performance Tuning Tips

Here are some easy to follow recommendations and best practices to help you create a good application.

  1. Do not rush to optimize until you clearly need it
  2. Use the analyzer to find the real bottleneck
  3. Create a performance test suite for the entire application
  4. Give priority to the biggest bottleneck
  5. Use StringBuilder to programmatically concatenate strings
  6. Use + to concatenate a string in a statement
  7. Use basic types whenever possible
  8. Try to avoid large integers and decimals
  9. Priority check the current log level
  10. Use Apache Commons StringUtils.Replace instead of String.replace
  11. Expensive cache resources, such as database connections

Most of these suggestions are for the Java language. But there are some languages that are not language-specific and you can apply them to any application or program. Before we learn about Java programming performance tuning, let’s explore some common techniques.

1) Do not rush to optimize until you clearly need it

This is probably one of the most important performance tuning tips. You should follow common best practices and apply it effectively in your case. However, this does not mean that you should replace any standard library or build complex optimizations until proven necessary.

In most cases, premature optimization can take a long time and can make the code harder to read and read. To make matters worse, these optimizations do not usually make any difference because you spend a lot of time optimizing non-critical parts of your application.

So, how to prove that things need to be optimized?

First, you need to define your code much faster. For example, specify the maximum response time for all API calls, or specify the number of records to import within a specific time range. After doing this, you need to determine which parts of your application are too slow to improve. When done, you can take a look at the second tip.

2) Use the analyzer to find the real bottleneck

After completing the first part of the optimization recommendations to identify your application need to enhance the part, where to start from?

There are two ways you can solve this problem:

  1. Check your code, starting with something that looks suspicious or where you think it might cause problems.
  2. Or use the analyzer to get the behavior of each part of the code (execution process) and performance details.

I hope I do not need to explain why you should always follow the second approach / method.

Obviously, the parser-based approach allows you to better understand the performance impact of code and allows you to focus on the more critical part (code). Even if you’ve used parsers before, you’ll have to remember how surprised you were to find out which parts of your code are causing performance problems. My first guess led me more than once in the wrong direction.

3) Create a performance test suite for the entire application

This is another general-purpose trick that can help you avoid many of the unexpected issues that often occur after deploying performance improvements into your product. You should always define a performance test suite to test the entire application and run it before and after performance improvements.

These extra tests will help you identify the functional and performance side effects of your changes and ensure they do not lead to more harm than good updates. This is especially important if you are dealing with components that are used by different parts of the application, such as databases or caches.

4) Give priority to the biggest bottleneck

After you have created a test suite and analyzed your application with a profiler, you can list a list of issues that need to be addressed to improve performance. This is fine, but it does not answer the question of where you need to start. You can focus on quick fixes or start with the most important questions.

The quick start may be appealing at the beginning because you can quickly show the first result. But sometimes, it may be necessary to convince other team members or management that performance analysis is worth it.

In general, I suggest starting with the top-level, first to start with the most important performance issues. This will provide you with the maximum performance improvement, and you may only need to address a few of these problems to meet your performance requirements.

This is the end of common tuning techniques. Let’s take a closer look at some Java-specific skills.

5) Use StringBuilder to programmatically concatenate strings

There are many different options in Java to concatenate strings. For example, you could use simple + or + = as well as old StringBuffer or StringBuilder.

So, what method should you choose?

The answer depends on the code that concatenates the string. If you programmatically add new content to a string, such as in a for loop, you should use StringBuilder. It’s easy to use and offers better performance than StringBuffer. However, keep in mind that StringBuilder is not thread-safe compared to StringBuffer and may not be suitable for all situations.

You only need to instantiate a new StringBuilder and call the append method to add a new part to the String. After you have added all the parts, you can call the toString () method to retrieve the connected string.

The following code snippet shows a simple example. During each iteration, the loop converts i to a String and adds it to the StringBuilder sb  along with spaces  . So, finally, this code writes “This is a test0 1 2 3 4 5 6 7 8 9” in the log file.

StringBuilder sb = new StringBuilder ("This is a test"); for (int i = 0; i <10; i ++) {
    sb.append (i);
    sb.append ("");
}
log.info (sb.toString ());

As you can see in the code snippet. We can provide the first element of the string into the constructor. This will create a  StringBuilder  that contains the string you provide and the capacity of 16 additional characters. When you add more characters to  StringBuilder  , your JVM will dynamically increase  the size of the StringBuilder  .

If you already know how many characters the string will contain, you can supply that number to a different constructor to instantiate a StringBuilder with the specified size. This further increases efficiency because it does not need to dynamically scale its capacity.

6) Use + to concatenate a string in a statement

When you use Java to implement your first application, someone may have told you not to use + to connect strings. This is true if you are concatenating strings within your application logic. Strings are immutable, and the concatenation of each string is stored in a new string object. This requires extra storage and may slow down your application, especially if you are connecting multiple strings within a loop.

In these cases, you should follow Tip 5 and use  StringBuilder.

However, this does not apply if you simply improve the readability of the code by breaking the string into multiple lines.

Query q = em.createQuery ("SELECT a.id, a.firstName, a.lastName"
+ "FROM Author a"
+ "WHERE a.id =: id");

In these scenarios, you should use simple + to concatenate strings. Your Java compiler optimizes it and completes the connection at compile time. Therefore, your code will only use one string at runtime, and does not require any linking operations.

7) Use basic types whenever possible

Another quick and easy way to avoid any overhead and improve application performance is to use base types instead of their wrapper classes. So, it’s best to use int instead of Integer, double instead of Double. This will allow your  JVM  to store the value on the stack instead of the heap to reduce memory consumption and handle it more efficiently.

8) Try to avoid large integers and decimals

Since we are already talking about data types, we should also be able to quickly browse for large integers and decimals. In particular, the latter is popular for its accuracy. But this is a price.

Larger integers and decimals  require more memory than a simple  long  or  double type and can significantly slow down all operations. So, if you need extra precision, or if your numbers go beyond a longer range, it’s best to think twice. This may be the only way you need to change and solve performance problems, especially when implementing mathematical algorithms.

9) Priority check the current log level

This advice should be obvious, but unfortunately, many people ignore it when writing code. Before creating a debug message, you should always prioritize the current log level. Otherwise, you might create a string that appends your log message, and the string is ignored after that.

Here are two negative examples that you should not do.

// do not do this
log.debug ("User [" + userName + "] called method X with [" + i + "]");
// or this
log.debug (String.format ("User [% s] called method X with [% d]", userName, i));

In both of these examples, you will perform all the necessary steps to create a log message without knowing if the log framework will use log messages. Therefore, before creating debug messages, it is best to check the current log level.

// do thisif (log.isDebugEnabled ()) {
    log.debug ("User [" + userName + "] called method X with [" + i + "]");
}

10) Use Apache Commons StringUtils.Replace instead of String.replace

In general, the String.replace method works fine and is very efficient, especially if you are using Java 9. However, if your application requires a large number of replacements and does not update to the latest Java version, it may still be necessary to examine faster and more efficient alternatives.

One alternative is  the  StringUtils.replace method of  Apache Commons Lang . It outperforms Java 8’s String.replace method. 

And it requires only minor changes. You simply add the Maven dependencies for the Apache Commons Lang project to your application’s pom.xml and replace all calls to String.replacemethod with the StringUtils.replace method.

// replace this
test.replace ("test", "simple test");
// with this
StringUtils.replace (test, "test", "simple test");

11) expensive cache resources, such as database connections

Caching is a popular solution to avoid repeatedly executing expensive or commonly used code snippets. The general idea is simple: reusing these resources is more cost-effective than creating a new one.

A typical example is the database connection in the cache pool. The creation of a new connection takes time, and you can avoid it if you reuse existing connections.

You can find other examples in the Java language source. For example, the valueOf method in the Integer class caches values between -128 and 127. You might argue that creating a new Integer is not too expensive, but since it is often used, the most common value for caching can also provide performance benefits.

However, when you consider caching, keep in mind that the cache implementation also incurs overhead. You need to spend extra memory to store reusable resources, so you may need to manage your cache to make the resources accessible and remove outdated resources.

So, before you start caching any resource, make sure that they are often used to exceed the cost of the cache implementation.

Related Articles

Aricent Java Interview Questions

Accenture Java Interview Questions

Core Java Interview Questions

Advanced Java Interview Questions

What is Python?

Advantages of Python

Python Tutorial For Beginners

295 Android Interview Questions

Top 20 Online C Compiler And Runner For C Programmers

Top 20 Online C Compiler And Runner For C Programmers 2018. In this blog post Coding compiler sharing a very good list of 20 Online Compiler C for programming lovers. According to the expert programmers, these are the best online compiler for c. Let’s explore the collection of the online compiler in  C and enjoy reading this blog post. Happy learning.

Best Online C Compiler

  1. OnlineGDB Online C Compiler
  2. JDoodle Online C Compiler
  3. CodeChef Online C Compiler
  4. TutorialsPoint Online C Compiler
  5. Codepad Online C Compiler
  6. Rextester Online C Compiler
  7. Repl Online C Compiler
  8. C++ Shell Online C Compiler
  9. Codetable HackerEarth Online C Compiler
  10. Ideone Online C Compiler
  11. Godbolt Compiler Explorer Online C Compiler
  12. Paiza Online C Compiler
  13. Codiva Online C Compiler
  14. The Online C Compiler
  15. Wandbox Online C Compiler
  16. Dcoder Mobile Compiler IDE – Online C Compiler For Android
  17. Online C Compiler For Mobile
  18. Online C Compiler For Android
  19. CppDroid Online C Compiler For Mobile
  20. Programming Hub Online C Compiler For Mobile

Top 20 Online C Compilers

If you want to code, compile and run the C programs online then these are the best Online C Compilers and Runners.

1) OnlineGDB C Compiler

OnlineGDB is an online IDE with the c compiler. It provides a quick and easy way to compile c program online. It supports GCC compiler for c.  By using OnlineGDB Online C Compiler you can easily Code, Compile, Run and Debug C program online. Write your own code in the editor and press “Run” button to compile and execute it. It’s very easy to use.

Try GDB Online C Compiler

2) JDoodle Online C Compiler

JDoodle is an Online Compiler of C, Online C Editor, Online C IDE. By using JDoodle you can write your own C coding online and run programs.
JDoodle also provides features like Save and Share C Programs online. It supports 68 language compilers and editors.

Try JDoodle Online C Compiler

3) CodeChef Online C Compiler

CodeChef is a online compiler for C proram. It is created as a platform to help C programmers make it big in the world of C algorithms, C computer programming. By using CodeChef IDE you can try your hand at C programming and compile online.

It has many practice problems on their platform on different programming languages. Users can try their practice problems and submit a solution in a language of your choice. It’s a great place to learn C programming by solving new problems.

Try CodeChef Online C Compiler

4) TutorialsPoint Online C Compiler

TutorialsPoint Coding Ground Online C Compiler provides features like Online C Editor, Online C IDE, C Coding Online, Practice C Online, Execute C Online, Compile C Online, Run C Online, Online C Interpreter.

Programmers can Compile and Execute C Online (GNU GCC v7.1.1) using TutorialsPoint Online C Compiler. It’s the best place to learn C programming tutorials and doing in C compiler.

Try TutorialsPoint Online C Compiler

5) Codepad Online C Compiler

With the help of Codepad Online C Compiler, you can Edit, Compile, Run and Execute C, C#, and C++ programs online. Codepad also provides features like pair program or interview C developers for FREE.

Try Codepad Online C Compiler

Best Online Compiler For C

6) Rextester Online C Compiler

Rextester is an online GCC compiler for C. It is a simple platform to compile c gcc online. By using users can learn C programming very easily by practicing on Rextester online C compiler.

Try Rextester Online C Compiler

7) Repl Online C Compiler

Repl.it is a powerful and simple online compiler, IDE, interpreter, and REPL. Users can Code, compile, and run code in C programming and other major programming languages.

Try Repl Online C Compiler

8) C++ Shell Online C Compiler

C++ Shell Online Compiler For C Programming. It provides functionalities like coding, compiling and running C programs online.

Try C++ Shell Online Compiler

9) Codetable HackerEarth Online C Compiler

HackerEarth helps users to write and practice C programming online. You can code, compile and run C programs. It also features like connecting smart programmers and great companies. Take up online C programming challenges and get hired by the reputed companies.

Try Codetable HackerEarth Online C Compiler

10) Ideone Online C Compiler

Ideone is an online turbo C compiler and debugging tool which allows you to compile C programming code, compile and execute it online. It supports more than 60 programming languages to execute online.

Try Ideone Online C Compiler

Top 20 Online Compilers In C

11) Godbolt Compiler Explorer Online C Compiler

Compiler Explorer is a unique online C compiler. Compiler Explorer is a compile as you type IDE with unique features. It displays the assembly produced by the compilers. The resulting assembler can be color-mapped to the originating C programming code. It supports more than 60 programming languages.

Try Godbolt Compiler Explorer Online C Compiler

12) Paiza Online C Compiler

Paiza is a full-screen online C compiler with output. Paiza IDE that allows to edit, compile, execute and share multiple C programming files. It has a feature like live editing, multiple file editing, Internet connection, and GitHub(gist) integration.

Try Paiza Online C Compiler

13) Codiva Online C Compiler

Codiva is an online C compiler and IDE that allows users to write code, edit, compile, runs and share. It compiles the C programming code with very few keystrokes and highlights the error lines in the editor. It works on mobile also.

Try Codiva Online C Compiler

14) The Online C Compiler

The online compiler C is an online coding platform that lets you code in C programming language. Users can code online in their cloud-based interpreters. You can also save your code permanently by downloading it.

Try The Online C Compiler

15) Wandbox Online C Compiler

Wandbox Online Compiler For C.  provides pretty much all of the functionality you’d want from a typical online compiler, including support for multiple files and different editor keybindings.

The compiled programs run in a sandbox environment that allows file I/O. The snapshot versions of GCC and Clang that are provided make it possible to play with the latest versions.

Try Wandbox Online C Compiler

Best Online C Compilers For Android

16) Dcoder Mobile Compiler IDE For Android

Dcoder is a mobile coding IDE ( Online C Compiler for mobile ), where users can write code and learn algorithms. Decoder is tailored with many features to enhance your coding skills, let’s try it on your mobile and enjoy learning coding.

Try Dcoder Online C Compiler For Android

17) Online C Compiler For Mobile

Online Compiler is the best IDE on mobile to Edit, Compile and run programs. It has the online compiler for C programming language and 23 programming languages.

Try Online C Compiler

18) Online C Compiler For Android

Online C Compiler For Android is a user friendly all-in-one compiler that supports C, C++, and other programming languages. It enables users to compile and run your code on the android device. It is light-weight, easy to install and use.

Try Online C Compiler For Android

19) CppDroid Online C Compiler For Mobile

CppDroid is the simple online compiler of C. C/C++ IDE focused on learning programming languages and libraries.

Try CppDroid Online C Compiler For Mobile

 

20) Programming Hub Online C Compiler Mobile

Programming Hub is an online C compiler for mobile. It is your one-stop solution to learn all the top programming languages and compile, run and execute programs in mobile.

Try Programming Hub Online C Compiler For Mobile

We tried our best to compile all the best Online C compiler and runner for C programming. If you feel, if we have missed any great tool please let us know by commenting below. We will include that on the list. All the best and happy coding.

C Program To Reverse An Array

C Program To Reverse An Array. If you are looking for C Program for Reverse Array, here in this tutorial we will help you to learn how to write a C program to reverse an array elements.

C Program To Reverse An Array

Learn how to write a C program to reverse an array. Writing a C reverse array program can be done using various techniques but here in this program, we show how to write a program to reverse an array logic in a proper way.

Reversing An Array Elements Example

These are some examples of reversing array elements.

Input : arr[] = {11, 12, 13}
Output : arr[] = {13, 12, 11}

Input : arr[] = {41, 51, 11, 21}
Output : arr[] = {21, 11, 51, 41}

C Program To Reverse An Array Source Code

Find the below source code to reverse an array and how to write c program to reverse an array using while loop.

/* C Proram to reverse an array using while loop - ReverseArray.C */

#include<stdio.h>

int main() {
//variable declaration
 int arr[30], i, j, num, temp;
//asking user to enter size of an array elements
printf("\nEnter no of elements : ");
 scanf("%d", &num);

//Reading elements in an array
 for (i = 0; i < num; i++) {
 scanf("%d", &arr[i]);
 }

j = i - 1; // j will Point to last element of an array
 i = 0; // i will be pointing to first element of ann array

while (i < j) {
 temp = arr[i];
 arr[i] = arr[j];
 arr[j] = temp;
 i++; // increment i
 j--; // decrement j
 }

//Printing output of an array elements in a reverse order
 printf("\nThe result after reversing of an array : ");
 for (i = 0; i < num; i++) {
 printf("%d \t", arr[i]);
 }

return (0);
}

C Program To Reverse An Array Output

Enter no of elements : 3

41     51     11     21

The result after reversing of an array

21     11     51     41

C PROGRAMMING TUTORIALS

  1. C Program For Pascal Triangle
  2. C Program to Print Prime Numbers from 1 to 100
  3. C Program to Find LCM and GCD of Two Numbers
  4. C Program to Add Spaces in a String
  5. C Program To Add Digits Of A Number
  6. C Program To Find Leap Year
  7. C Program To Append Data Into A File
  8. C Program to Accept Only Integer Values
  9. C Program To Arrange Numbers In Descending Order
  10. C Program to Add Days to Date
  11. C Program to Add Two Fractions
  12. C Program To Reverse A Number
  13. C Program to Find Maximum and Minimum Numbers
  14. C Program to Read a Text File
  15. C Program to Convert Decimal to Hexadecimal
  16. C Program to Convert Decimal to Binary
  17. C Program to Convert Celsius to Fahrenheit
  18. C Program To Find Absolute Value
  19. Ternary Operator Program in C
  20. C Program For Addition Table Using For Loop

C Program To Print Pascal Triangle

C Program To Print Pascal Triangle. If you are looking for C Program for Pascal Triangle, here in this tutorial we will help you to learn how to write a C program to display Pascal triangle.

C Program to Print Pascal Triangle

Learn how to write a C program to print Pascal Triangle. Writing a Pascal Triangle C program can be done using various techniques but here in this program, we show how to write a pascal triangle logic in a proper way.

Pascal Triangle Example

           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1 

C Program to Print Pascal Triangle Source Code

/* C Program to print pascal traiangle - PascalTriangle.C */

#include <stdio.h>
int main()
{
//variable declaration
 int rows, coef = 1, space, i, j;

//asking user to enter number of rows and reading
printf("Enter number of rows: ");
 scanf("%d",&rows);

//logic for printing pascal triangle
for(i=0; i<rows; i++)
 {
 for(space=1; space <= rows-i; space++)
 printf(" ");

for(j=0; j <= i; j++)
 {
 if (j==0 || i==0)
 coef = 1;
 else
 coef = coef*(i-j+1)/j;

printf("%4d", coef);
 }
 printf("\n");
 }

return 0;
}

C Program to Print Pascal Triangle Output

Enter number of rows: 6


           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1 

C PROGRAMMING TUTORIALS

  1. C Program to Print Prime Numbers from 1 to 100
  2. C Program to Find LCM and GCD of Two Numbers
  3. C Program to Add Spaces in a String
  4. C Program To Add Digits Of A Number
  5. C Program To Find Leap Year
  6. C Program To Append Data Into A File
  7. C Program to Accept Only Integer Values
  8. C Program To Arrange Numbers In Descending Order
  9. C Program to Add Days to Date
  10. C Program to Add Two Fractions
  11. C Program To Reverse A Number
  12. C Program to Find Maximum and Minimum Numbers
  13. C Program to Read a Text File
  14. C Program to Convert Decimal to Hexadecimal
  15. C Program to Convert Decimal to Binary
  16. C Program to Convert Celsius to Fahrenheit
  17. C Program To Find Absolute Value
  18. Ternary Operator Program in C
  19. C Program For Addition Table Using For Loop
  20. Denomination Program in C

C Program To Print Prime Numbers From 1 To 100

C program to print prime numbers from 1 to 100. If you are looking for C program to find prime numbers, here in this tutorial we will help you to learn how to write a C program for prime numbers.

C Program to Print Prime Numbers

Learn how to write a C program to print all Prime numbers between 1 to 100. Writing a C program to display prime numbers between two intervals can be done using various techniques but here in this program, we show how to write a C program to print prime numbers from 1 to 100 in a proper way.

C Program to Print Prime Numbers Source Code

/* C Program to print prime numbers from 1 to 100 - PrimeNumbers.C */

#include <stdio.h>
#include <stdlib.h>
 
void main()
{
//variable declaration
 int num1, num2, i, j, flag, temp, count = 0;
 
//asking user to enter lower and upper limit numbers and reading
 printf("Enter the value of num1 and num2 \n");
 scanf("%d %d", &num1, &num2);
//logic to finding and printing prime numbers from 1 to 100
 if (num2 < 2)
 {
   printf("There are no primes upto %d\n", num2);
   exit(0);
 }
 
 printf("Prime numbers are \n");
 temp = num1;
 
 if ( num1 % 2 == 0)
 {
   num1++;
 }
 
 for (i = num1; i <= num2; i = i + 2)
 {
 flag = 0;
 for (j = 2; j <= i / 2; j++)
 {
 if ((i % j) == 0)
 {
 flag = 1;
 break;
 }
 }
 if (flag == 0)
 {
 printf("%d\n", i);
 count++;
 }
 }
 printf("Number of primes between %d & %d = %d\n", temp, num2, count);
}

C Program to Print Prime Numbers Output

Enter the value of num1 and num2

1

100

Prime numbers are

2     3    5     7    11    13    17    19     23      29

31      37      41      43      47      53      59      61

67      71     73      79      83      89      97

Number of primes between 1 & 100 = 25

C PROGRAMMING TUTORIALS

  1. C Program to Find LCM and GCD of Two Numbers
  2. C Program to Add Spaces in a String
  3. C Program To Add Digits Of A Number
  4. C Program To Find Leap Year
  5. C Program To Append Data Into A File
  6. C Program to Accept Only Integer Values
  7. C Program To Arrange Numbers In Descending Order
  8. C Program to Add Days to Date
  9. C Program to Add Two Fractions
  10. C Program To Reverse A Number
  11. C Program to Find Maximum and Minimum Numbers
  12. C Program to Read a Text File
  13. C Program to Convert Decimal to Hexadecimal
  14. C Program to Convert Decimal to Binary
  15. C Program to Convert Celsius to Fahrenheit
  16. C Program To Find Absolute Value
  17. Ternary Operator Program in C
  18. C Program For Addition Table Using For Loop
  19. Denomination Program in C
  20. C Program to Print Multiplication Table 

C Program To Find LCM GCD Of Two Numbers

C Program To Find LCM GCD Of Two Numbers. If you are looking for C program to calculate LCM and GCD of two numbers, here in this tutorial we will help you to learn how to write a program to find LCM in C language.

C Program to Find LCM and GCD

Learn how to write a C program to find LCM. Writing C Program to finding GCD of a number can be done using various techniques but here in this program, we show how to write a C program to find LCM GCD of two numbers in a proper way.

C Program to Find LCM and GCD of Two Numbers Source Code

/* C program to find the LCM and GCD of two numbers - LcmGcd.C */

 #include <stdio.h>

void main()
 {
//variable declaration
 int num1, num2, gcd, lcm, remainder, numerator, denominator;

//asking user to enter two numbers and reading them
printf("Enter two numbers\n");
 scanf("%d %d", &num1, &num2);

//checking for bigger number
 if (num1 > num2)
 {
 numerator = num1;
 denominator = num2;
 }
 else
 {
 numerator = num2;
 denominator = num1;
 }

//calculating remainder
 remainder = numerator % denominator;

//logic to find gcd and lcm of two numbers
 while (remainder != 0)
 {
 numerator = denominator;
 denominator = remainder;
 remainder = numerator % denominator;
 }

//finding lcm and gcd of two numbers
 gcd = denominator;
 lcm = num1 * num2 / gcd;

//printing lcm and gcd of two numbers
 printf("GCD of %d and %d = %d\n", num1, num2, gcd);
 printf("LCM of %d and %d = %d\n", num1, num2, lcm);
 }

C Program to Find LCM and GCD of Two Numbers Output

Enter two numbers

65

30

GCD of 65 and 30 = 5

LCM of 65 and 30 = 390

C PROGRAMMING TUTORIALS

  1. C Program to Add Spaces in a String
  2. C Program To Add Digits Of A Number
  3. C Program To Find Leap Year
  4. C Program To Append Data Into A File
  5. C Program to Accept Only Integer Values
  6. C Program To Arrange Numbers In Descending Order
  7. C Program to Add Days to Date
  8. C Program to Add Two Fractions
  9. C Program To Reverse A Number
  10. C Program to Find Maximum and Minimum Numbers
  11. C Program to Read a Text File
  12. C Program to Convert Decimal to Hexadecimal
  13. C Program to Convert Decimal to Binary
  14. C Program to Convert Celsius to Fahrenheit
  15. C Program To Find Absolute Value
  16. Ternary Operator Program in C
  17. C Program For Addition Table Using For Loop
  18. Denomination Program in C
  19. C Program to Print Multiplication Table 
  20. C Program Array with Example

C Program To Print Hello World

C Program To Print Hello World. If you are looking for writing your first C program to Hello World, here in this tutorial we will help you to learn how to write a program to display Hello World in C language.

C Program To Print Hellow World

/* C program to print hello world - HelloWorld.C */

#include <stdio.h>
void main()
{
  printf("Hello World.!");
}

C Program To Print Hellow World Output

Hello World.!

C PROGRAMMING TUTORIALS

  1. C Program to Find Area of a Circle
  2. C Program to Add Spaces in a String
  3. C Program To Add Digits Of A Number
  4. C Program To Find Leap Year
  5. C Program To Append Data Into A File
  6. C Program to Accept Only Integer Values
  7. C Program To Arrange Numbers In Descending Order
  8. C Program to Add Days to Date
  9. C Program to Add Two Fractions
  10. C Program To Reverse A Number
  11. C Program to Find Maximum and Minimum Numbers
  12. C Program to Read a Text File
  13. C Program to Convert Decimal to Hexadecimal
  14. C Program to Convert Decimal to Binary
  15. C Program to Convert Celsius to Fahrenheit
  16. C Program To Find Absolute Value
  17. Ternary Operator Program in C
  18. C Program For Addition Table Using For Loop
  19. Denomination Program in C
  20. C Program to Print Multiplication Table 

C Program To Find Area Of A Circle

C Program To Find Area Of A Circle. If you are looking for C program to calculate area of a circle, here in this tutorial we will help you to learn how to write a program to find area of a circle in C language.

C Program to Find Area of a Circle

Learn how to write a C program to find area of a circle. Writing C Program to finding area of circle can be done using various techniques but here in this program, we show how to write a C program to calculate area of a circle in a proper way.

C Program to Calculate Area of a Circle Source Code

/* C program to calculate area of a circle - AreaOfCircle.C */
#include <stdio.h>
#include <math.h>
#define PI 3.142
 
void main()
{
 //variable declaration
 float radius, area; 
 //asking user to enter the radius of a circle
 printf("Enter the radius of a circle \n");
 //reading user entered radius value to calculate area
 scanf("%f", &radius);
 //logic to find area of a cirlce
 area = PI * pow(radius, 2); //area of a circle formula
 //printing area of a cirlce
 printf("Area of a circle = %5.2f\n", area);
}

C Program to Find Area of a Circle Source Code

/* C program to find area of a circle - AreaOfCircle.C */

#include<stdio.h>
 
int main() 
{
 //variables declaration
 float radius, area;
 //Taking input from user and reading it
 printf("\nEnter the radius of Circle : ");
 scanf("%d", &radius);
 //formula to find area of a circle
 area = 3.14 * radius * radius;
//printing area of a circle
 printf("\nArea of a Circle is: %f", area);
 
 return (0);
}

C Program to Find Area of a Circle Output

Enter the radius of Circle : 15

Area of a Circle is: 706.5

C PROGRAMMING tutorials

  1. C Program to Add Spaces in a String
  2. C Program To Add Digits Of A Number
  3. C Program To Find Leap Year
  4. C Program To Append Data Into A File
  5. C Program to Accept Only Integer Values
  6. C Program To Arrange Numbers In Descending Order
  7. C Program to Add Days to Date
  8. C Program to Add Two Fractions
  9. C Program To Reverse A Number
  10. C Program to Find Maximum and Minimum Numbers
  11. C Program to Read a Text File
  12. C Program to Convert Decimal to Hexadecimal
  13. C Program to Convert Decimal to Binary
  14. C Program to Convert Celsius to Fahrenheit
  15. C Program To Find Absolute Value
  16. Ternary Operator Program in C
  17. C Program For Addition Table Using For Loop
  18. Denomination Program in C
  19. C Program to Print Multiplication Table 
  20. C Program Array with Example

 

C Program To Add Spaces In A String

C Program To Add Spaces In A String. If you are looking for C program to add space to a string, here in this tutorial we will help you to learn how to write a C program to add space to a string.

C Program to Add Spaces in a String

Learn how to write a C program to add spaces in a string. Writing C Program to add space to a string can be done using various techniques but here in this program, we show how to write a C program to adding spaces in a string in a proper way.

C Program to Add Spaces in a String Source Code

/* C Program to add spaces in a string - AddSpacesInString.C */
#include <iostream>
//#include <iomanip>
#include <cctype>
#include <string>

using namespace std;

//void fixPuct(string);
void fixPuct(string&);



int main()
{
 //char *statement; // don't mix C strings with C++
 //statement = new char [60];
 cout << "Enter a statement with Caps at start of each new word ..." << endl;
 // Enter a statement with Caps at start of each new word ...

string statement; // construct an empty C++ string
 if( getline(cin, statement) )
 //if (statement != NULL)
 {
 //cout << "Enter a statement: ";
 //cin. getline(statement, 60);// see above re. using C++ strings with C++
 //getline( cin statement ); // see above re. using C++ strings with C++
 cout << "You entered " << '"' << statement << '"' << endl;

fixPuct(statement);
 cout << "Here it is fixed ...\n"
 << statement << endl;
 //delete [] statement;
 }
 
 cout << "\nPress 'Enter' to continue/exit ... " << flush;
 getline( cin, statement );
}



//void fixPuct(string s)
void fixPuct(string& s) // Note: NEED to pass in by reference so calling string gets updated ...
{
 int size = s.size();
 if(size)
 {
 string nLine(1, s[0]);
 for( int i=1; i<size; i++ )
 {
 if( isupper(s[i]) )
 {
 if( i > 0 && !isspace(s[i-1]) ) nLine += ' ';
 nLine += tolower(s[i]);
 }
 else nLine += s[i];
 }
 s = nLine;
 }
}

C Program to Add Spaces in a String Output

Enter a statement with Caps at start of each new word …

TheBig BrownBear sat OnTheLittleBlueBox.

Here it is fixed …

The big brown bear sat on the little blue box.

Press ‘Enter’ to continue/exit …

C PROGRAMMING EXAMPLES

  1. C Program To Add Digits Of A Number
  2. C Program To Find Leap Year
  3. C Program To Append Data Into A File
  4. C Program to Accept Only Integer Values
  5. C Program To Arrange Numbers In Descending Order
  6. C Program to Add Days to Date
  7. C Program to Add Two Fractions
  8. C Program To Reverse A Number
  9. C Program to Find Maximum and Minimum Numbers
  10. C Program to Read a Text File
  11. C Program to Convert Decimal to Hexadecimal
  12. C Program to Convert Decimal to Binary
  13. C Program to Convert Celsius to Fahrenheit
  14. C Program To Find Absolute Value
  15. Ternary Operator Program in C
  16. C Program For Addition Table Using For Loop
  17. Denomination Program in C
  18. C Program to Print Multiplication Table 
  19. C Program Array with Example
  20. Binary Search in C Program Using Recursion

C Program To Add Digits Of A Number

C Program To Add Digits Of A Number.  If you are looking find sum of the digits of a number program in C, here in this tutorial we will help you to learn how to write a C program to compute sum of digits in a given number.

C Program to Add Digits of a Number

Learn how to write a C program to find sum of digits of a number. Writing C Program to add digits of a given number can be done using various techniques but here in this program, we show how to write a C program to find sum of digits of a number using while loop in a proper way.

How do you find the sum of digits in C?

If a user enters a number 1234, then we have to write a logic to calculate sum of the digits of 1234. That is 1 + 2 + 3 + 4 = 10. The program should read the individual digits and then it should add digits and print sum of the digits in a given number.

C Program to Compute Digits of a Number Source Code

Just copy paste the below source code to find sum of the digits of a number in C compiler to test, how the source code works. Happy Learning.

/* C program to add digits of a number - AddDigits.C */

#include <stdio.h>
 
void main()
{
 long num, temp, digit, sum = 0;
 
 printf("Enter the number to find sum of the digits: \n");
 scanf("%ld", &num);
 temp = num;
 while (num > 0)
 {
  digit = num % 10;
  sum = sum + digit;
  num /= 10;
 }
 printf("Given number is = %ld\n", temp);
 printf("Sum of the digits of %ld = %ld\n", temp, sum);
}

C Program to Find Sum of Digits of a Number Output

Run the above program to add digits of a given number to print sum of digits. For this enter a number to check, the c compiler will execute the logic and display the sum of the digits of a number.

Output:

Enter the number to find sum of the digits: 1234

Given number is = 1234

Sum of the digits of 1234 = 10

C PROGRAMMING EXAMPLES

  1. C Program To Find Leap Year
  2. C Program To Append Data Into A File
  3. C Program to Accept Only Integer Values
  4. C Program To Arrange Numbers In Descending Order
  5. C Program to Add Days to Date
  6. C Program to Add Two Fractions
  7. C Program To Reverse A Number
  8. C Program to Find Maximum and Minimum Numbers
  9. C Program to Read a Text File
  10. C Program to Convert Decimal to Hexadecimal
  11. C Program to Convert Decimal to Binary
  12. C Program to Convert Celsius to Fahrenheit
  13. C Program To Find Absolute Value
  14. Ternary Operator Program in C
  15. C Program For Addition Table Using For Loop
  16. Denomination Program in C
  17. C Program to Print Multiplication Table 
  18. C Program Array with Example
  19. Binary Search in C Program Using Recursion
  20. Bubble Sort in C Using Pointers