class parent;
//Function finds the sum of natural numbers
function int sum_n_num(int number);
return number*(number+1)/2;
endfunction
endclass
module top;
initial begin
int num=5;
parent p=new();
//calling the function
p.sum_n_num(num);
$display("sum of %d number is %d",num,p.sum_n_num(num));
end
endmodule
class parent;
//Function finds the sum of natural numbers
function int sum_n_num(int number);
int sum;
//Using forloop construst
for(int i=1; i<=number; i++) begin
sum=i+sum;
end
return sum;
endfunction
endclass
module top;
initial begin
int num=5;
parent p=new();
//calling the function
p.sum_n_num(num);
$display("sum of %d number is %d",num,p.sum_n_num(num));
end
endmodule
to Find the Sum of n odd Numbers
class parent;
//to Find the Sum of n odd Numbers
function int sum_n_num(int number);
int sum;
//Using forloop construst
for(int i=1; i<=number; i++) begin
if(i%2 != 0)
sum=i+sum;
end
return sum;
endfunction
endclass
module top;
initial begin
int num=5;
parent p=new();
//calling the function
p.sum_n_num(num);
$display("sum of %d number is %d",num,p.sum_n_num(num));
end
endmodule
To find the sum of n even Numbers using system verilog function
class parent;
//to Find the Sum of n even Numbers
function int sum_n_num(int number);
int sum;
//Using forloop construst
for(int i=1; i<=number; i++) begin
if(i%2 == 0)
sum=i+sum;
end
return sum;
endfunction
endclass
module top;
initial begin
int num=5;
parent p=new();
//calling the function
p.sum_n_num(num);
$display("sum of %d number is %d",num,p.sum_n_num(num));
end
endmodule