0% found this document useful (0 votes)
106 views11 pages

C Example

The document provides examples of C++ code demonstrating basic and complex syntax concepts, including: 1) Simple "Hello World" and number input/output programs. 2) Calculations like summing two numbers, computing quotients and remainders. 3) Variable sizes and data types. 4) Conditional logic like checking even/odd numbers and finding largest of three. 5) Loops for calculating sums, displaying tables, and generating Fibonacci sequences.

Uploaded by

yihun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
106 views11 pages

C Example

The document provides examples of C++ code demonstrating basic and complex syntax concepts, including: 1) Simple "Hello World" and number input/output programs. 2) Calculations like summing two numbers, computing quotients and remainders. 3) Variable sizes and data types. 4) Conditional logic like checking even/odd numbers and finding largest of three. 5) Loops for calculating sums, displaying tables, and generating Fibonacci sequences.

Uploaded by

yihun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

All example of C++ syntax from simple up to complex;

HELLO WORLD
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello World!";
return 0;
}
Example: Print Number Entered by User
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
cout << "You entered " << number;
return 0;
}
OTHER
#include <iostream>
using namespace std;

int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
// sum of two numbers in stored in variable sumOfTwoNumbers
sumOfTwoNumbers = firstNumber + secondNumber;
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " <<
sumOfTwoNumbers;
return 0;
}

Example: Compute quotient and remainder

#include <iostream>
using namespace std;
int main()
{
int divisor, dividend, quotient, remainder;
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
quotient = dividend / divisor;
remainder = dividend % divisor;
cout << "Quotient = " << quotient << endl;
cout << "Remainder = " << remainder;
return 0;
}

Example: Find Size of a Variable


#include <iostream>
using namespace std;
int main()
{
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
return 0;
}

Example 1: Swap Numbers (Using Temporary Variable)

#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}

Example: Print ASCII Value in C++

#include <iostream>
using namespace std;

int main()
{
char c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
}
C++Program to Multiply Two Numbers

#include <iostream>
using namespace std;

int main()
{
double firstNumber, secondNumber, productOfTwoNumbers;
cout << "Enter two numbers: ";

// Stores two floating point numbers in variable firstNumber and


secondNumber respectively
cin >> firstNumber >> secondNumber;

// Performs multiplication and stores the result in variable


productOfTwoNumbers
productOfTwoNumbers = firstNumber * secondNumber;

cout << "Product = " << productOfTwoNumbers;

return 0;
}

Example 1: Check Whether Number is Even or Odd using if else

#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
https://www.programiz.com/cpp-programming/examples/even-odd

Example 1: Find Largest Number Using if Statement

#include <iostream>
using namespace std;
int main() {
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;
if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;
if(n3 >= n1 && n3 >= n2)
cout << "Largest number: " << n3;
return 0;
}

Example: Roots of a Quadratic Equation


#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
discriminant = b*b - 4*a*c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
x1 = -b/(2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else {
realPart = -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
return 0;
}

Example: Sum of Natural Numbers using loop

#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}

Example: Check if a year is leap year or not


#include <iostream>
using namespace std;

int main() {
int year;

cout << "Enter a year: ";


cin >> year;

if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
cout << year << " is a leap year.";
else
cout << year << " is not a leap year.";
}
else
cout << year << " is a leap year.";
}
else
cout << year << " is not a leap year.";

return 0;
}

Example: Find Factorial of a given number

#include <iostream>
using namespace std;
int main()
{
unsigned int n;
unsigned long long factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
for(int i = 1; i <=n; ++i)
{
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
return 0;
}

Example 1: Display Multiplication table up to 10

#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= 10; ++i) {
cout << n << " * " << i << " = " << n * i << endl;
}
return 0;
}

Example 1: Fibonacci Series up to n number of terms


#include <iostream>
using namespace std;
int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i)
{
// Prints the first two terms.
if(i == 1)
{
cout << " " << t1;
continue;
}
if(i == 2)
{
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << " ";
}
return 0;
}

Example 1: Find GCD using while loop


#include <iostream>
using namespace std;
int main()
{
int n1, n2;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
cout << "HCF = " << n1;
return 0;
}

Example: 2. Find HCF/GCD using for loop


#include <iostream>
using namespace std;
int main() {
int n1, n2, hcf;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// Swapping variables n1 and n2 if n2 is greater than n1.
if ( n2 > n1) {
int temp = n2;
n2 = n1;
n1 = temp;
}

for (int i = 1; i <= n2; ++i) {


if (n1 % i == 0 && n2 % i ==0) {
hcf = i;
}
}
cout << "HCF = " << hcf;
return 0;
}

Example: Simple Calculator using switch statement

# include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
cout << "Enter operator either + or - or * or /: ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}

Example: Add Two Matrices using Multi-dimensional Arrays


#include <iostream>
using namespace std;
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
cout << "Enter number of rows (between 1 and 100): ";
cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
// Storing elements of first matrix entered by user.
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}
// Storing elements of second matrix entered by user.
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}
// Adding Two matrices
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.


cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}
return 0;
}
Example: Access Array Elements Using Pointer

#include <iostream>
using namespace std;
int main()
{
int data[5];
cout << "Enter elements: ";
for(int i = 0; i < 5; ++i)
cin >> data[i];
cout << "You entered: ";
for(int i = 0; i < 5; ++i)
cout << endl << *(data + i);
return 0;
}

Example: Program to Time Difference

// Computes time difference of two time period


// Time periods are entered by the user
#include <iostream>
using namespace std;
struct TIME
{
int seconds;
int minutes;
int hours;
};
void computeTimeDifference(struct TIME, struct TIME, struct TIME *);
int main()
{
struct TIME t1, t2, difference;
cout << "Enter start time." << endl;
cout << "Enter hours, minutes and seconds respectively: ";
cin >> t1.hours >> t1.minutes >> t1.seconds;
cout << "Enter stop time." << endl;
cout << "Enter hours, minutes and seconds respectively: ";
cin >> t2.hours >> t2.minutes >> t2.seconds;
computeTimeDifference(t1, t2, &difference);
cout << endl << "TIME DIFFERENCE: " << t1.hours << ":" << t1.minutes << ":" << t1.seconds;
cout << " - " << t2.hours << ":" << t2.minutes << ":" << t2.seconds;
cout << " = " << difference.hours << ":" << difference.minutes << ":" << difference.seconds;
return 0;
}
void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME *difference){
if(t2.seconds > t1.seconds)
{
--t1.minutes;
t1.seconds += 60;
}
difference->seconds = t1.seconds - t2.seconds;
if(t2.minutes > t1.minutes)
{
--t1.hours;
t1.minutes += 60;
}
difference->minutes = t1.minutes-t2.minutes;
difference->hours = t1.hours-t2.hours;
}
Example: Store Information in Structure and Display it

#include <iostream>
using namespace std;
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
cout << "Enter information of students: " << endl;
// storing information
for(int i = 0; i < 10; ++i)
{
s[i].roll = i+1;
cout << "For roll number" << s[i].roll << "," << endl;
cout << "Enter name: ";
cin >> s[i].name;
cout << "Enter marks: ";
cin >> s[i].marks;
cout << endl;
}
cout << "Displaying Information: " << endl;
// Displaying information
for(int i = 0; i < 10; ++i)
{
cout << "\nRoll number: " << i+1 << endl;
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}
return 0;
}

Example: Add Distances Using Structures

#include <iostream>
using namespace std;
struct Distance{
int feet;
float inch;
}d1 , d2, sum;
int main()
{
cout << "Enter 1st distance," << endl;
cout << "Enter feet: ";
cin >> d1.feet;
cout << "Enter inch: ";
cin >> d1.inch;
cout << "\nEnter information for 2nd distance" << endl;
cout << "Enter feet: ";
cin >> d2.feet;
cout << "Enter inch: ";
cin >> d2.inch;
sum.feet = d1.feet+d2.feet;
sum.inch = d1.inch+d2.inch;
// changing to feet if inch is greater than 12
if(sum.inch > 12)
{
++ sum.feet;
sum.inch -= 12;
}
cout << endl << "Sum of distances = " << sum.feet << " feet " << sum.inch << " inches";
return 0;
}
Example: Source Code to Add Two Complex Numbers

// Complex numbers are entered by the user


#include <iostream>
using namespace std;
typedef struct complex {
float real;
float imag;
} complexNumber;
complexNumber addComplexNumbers(complex, complex);
int main() {
complexNumber num1, num2, complexSum;
char signOfImag;
cout << "For 1st complex number," << endl;
cout << "Enter real and imaginary parts respectively:" << endl;
cin >> num1.real >> num1.imag;
cout << endl
<< "For 2nd complex number," << endl;
cout << "Enter real and imaginary parts respectively:" << endl;
cin >> num2.real >> num2.imag;
// Call add function and store result in complexSum
complexSum = addComplexNumbers(num1, num2);
// Use Ternary Operator to check the sign of the imaginary number
signOfImag = (complexSum.imag > 0) ? '+' : '-';
// Use Ternary Operator to adjust the sign of the imaginary number
complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag;
cout << "Sum = " << complexSum.real << signOfImag << complexSum.imag << "i";
return 0;
}
complexNumber addComplexNumbers(complex num1, complex num2) {
complex temp;
temp.real = num1.real + num2.real;
temp.imag = num1.imag + num2.imag;
return (temp);
}

Example 1: Displaying Array Elements

#include <iostream>
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
// Printing array elements
// using range based for loop
for (const int &n : numbers) {
cout << n << " ";
}
cout << "\nThe numbers are: ";
// Printing array elements
// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}
return 0;
}

Example 2: Calculate Average by array


// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);

for(i=0; i<n; ++i)


{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}

average = sum/n;
printf("Average = %d", average);

return 0;
}

// arrays example

#include <iostream>

using namespace std;

int foo [] = {16, 2, 77, 40, 12071};

int n, result=0;

int main ()

for ( n=0 ; n<5 ; ++n )

result += foo[n];

cout << result;

return 0;

You might also like